SemaDecl.cpp 562 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "TypeLocBuilder.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTLambda.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/CommentDiagnostic.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/Basic/Builtins.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  32. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  33. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  34. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  35. #include "clang/Parse/ParseDiagnostic.h"
  36. #include "clang/Sema/CXXFieldCollector.h"
  37. #include "clang/Sema/DeclSpec.h"
  38. #include "clang/Sema/DelayedDiagnostic.h"
  39. #include "clang/Sema/Initialization.h"
  40. #include "clang/Sema/Lookup.h"
  41. #include "clang/Sema/ParsedTemplate.h"
  42. #include "clang/Sema/Scope.h"
  43. #include "clang/Sema/ScopeInfo.h"
  44. #include "clang/Sema/Template.h"
  45. #include "llvm/ADT/SmallString.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include <algorithm>
  48. #include <cstring>
  49. #include <functional>
  50. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  51. using namespace clang;
  52. using namespace sema;
  53. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  54. if (OwnedType) {
  55. Decl *Group[2] = { OwnedType, Ptr };
  56. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  57. }
  58. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  59. }
  60. namespace {
  61. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  62. public:
  63. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
  64. bool AllowTemplates=false)
  65. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  66. AllowClassTemplates(AllowTemplates) {
  67. WantExpressionKeywords = false;
  68. WantCXXNamedCasts = false;
  69. WantRemainingKeywords = false;
  70. }
  71. bool ValidateCandidate(const TypoCorrection &candidate) override {
  72. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  73. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  74. bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
  75. return (IsType || AllowedTemplate) &&
  76. (AllowInvalidDecl || !ND->isInvalidDecl());
  77. }
  78. return !WantClassName && candidate.isKeyword();
  79. }
  80. private:
  81. bool AllowInvalidDecl;
  82. bool WantClassName;
  83. bool AllowClassTemplates;
  84. };
  85. }
  86. /// \brief Determine whether the token kind starts a simple-type-specifier.
  87. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  88. switch (Kind) {
  89. // FIXME: Take into account the current language when deciding whether a
  90. // token kind is a valid type specifier
  91. case tok::kw_short:
  92. case tok::kw_long:
  93. case tok::kw___int64:
  94. case tok::kw___int128:
  95. case tok::kw_signed:
  96. case tok::kw_unsigned:
  97. case tok::kw_void:
  98. case tok::kw_char:
  99. case tok::kw_int:
  100. case tok::kw_half:
  101. case tok::kw_float:
  102. case tok::kw_double:
  103. case tok::kw_wchar_t:
  104. case tok::kw_bool:
  105. case tok::kw___underlying_type:
  106. return true;
  107. case tok::annot_typename:
  108. case tok::kw_char16_t:
  109. case tok::kw_char32_t:
  110. case tok::kw_typeof:
  111. case tok::annot_decltype:
  112. case tok::kw_decltype:
  113. return getLangOpts().CPlusPlus;
  114. default:
  115. break;
  116. }
  117. return false;
  118. }
  119. namespace {
  120. enum class UnqualifiedTypeNameLookupResult {
  121. NotFound,
  122. FoundNonType,
  123. FoundType
  124. };
  125. } // namespace
  126. /// \brief Tries to perform unqualified lookup of the type decls in bases for
  127. /// dependent class.
  128. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  129. /// type decl, \a FoundType if only type decls are found.
  130. static UnqualifiedTypeNameLookupResult
  131. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  132. SourceLocation NameLoc,
  133. const CXXRecordDecl *RD) {
  134. if (!RD->hasDefinition())
  135. return UnqualifiedTypeNameLookupResult::NotFound;
  136. // Look for type decls in base classes.
  137. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  138. UnqualifiedTypeNameLookupResult::NotFound;
  139. for (const auto &Base : RD->bases()) {
  140. const CXXRecordDecl *BaseRD = nullptr;
  141. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  142. BaseRD = BaseTT->getAsCXXRecordDecl();
  143. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  144. // Look for type decls in dependent base classes that have known primary
  145. // templates.
  146. if (!TST || !TST->isDependentType())
  147. continue;
  148. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  149. if (!TD)
  150. continue;
  151. auto *BasePrimaryTemplate =
  152. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
  153. if (!BasePrimaryTemplate)
  154. continue;
  155. BaseRD = BasePrimaryTemplate;
  156. }
  157. if (BaseRD) {
  158. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  159. if (!isa<TypeDecl>(ND))
  160. return UnqualifiedTypeNameLookupResult::FoundNonType;
  161. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  162. }
  163. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  164. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  165. case UnqualifiedTypeNameLookupResult::FoundNonType:
  166. return UnqualifiedTypeNameLookupResult::FoundNonType;
  167. case UnqualifiedTypeNameLookupResult::FoundType:
  168. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  169. break;
  170. case UnqualifiedTypeNameLookupResult::NotFound:
  171. break;
  172. }
  173. }
  174. }
  175. }
  176. return FoundTypeDecl;
  177. }
  178. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  179. const IdentifierInfo &II,
  180. SourceLocation NameLoc) {
  181. // Lookup in the parent class template context, if any.
  182. const CXXRecordDecl *RD = nullptr;
  183. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  184. UnqualifiedTypeNameLookupResult::NotFound;
  185. for (DeclContext *DC = S.CurContext;
  186. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  187. DC = DC->getParent()) {
  188. // Look for type decls in dependent base classes that have known primary
  189. // templates.
  190. RD = dyn_cast<CXXRecordDecl>(DC);
  191. if (RD && RD->getDescribedClassTemplate())
  192. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  193. }
  194. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  195. return ParsedType();
  196. // We found some types in dependent base classes. Recover as if the user
  197. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  198. // lookup during template instantiation.
  199. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  200. ASTContext &Context = S.Context;
  201. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  202. cast<Type>(Context.getRecordType(RD)));
  203. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  204. CXXScopeSpec SS;
  205. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  206. TypeLocBuilder Builder;
  207. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  208. DepTL.setNameLoc(NameLoc);
  209. DepTL.setElaboratedKeywordLoc(SourceLocation());
  210. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  211. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  212. }
  213. /// \brief If the identifier refers to a type name within this scope,
  214. /// return the declaration of that type.
  215. ///
  216. /// This routine performs ordinary name lookup of the identifier II
  217. /// within the given scope, with optional C++ scope specifier SS, to
  218. /// determine whether the name refers to a type. If so, returns an
  219. /// opaque pointer (actually a QualType) corresponding to that
  220. /// type. Otherwise, returns NULL.
  221. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  222. Scope *S, CXXScopeSpec *SS,
  223. bool isClassName, bool HasTrailingDot,
  224. ParsedType ObjectTypePtr,
  225. bool IsCtorOrDtorName,
  226. bool WantNontrivialTypeSourceInfo,
  227. IdentifierInfo **CorrectedII) {
  228. // Determine where we will perform name lookup.
  229. DeclContext *LookupCtx = nullptr;
  230. if (ObjectTypePtr) {
  231. QualType ObjectType = ObjectTypePtr.get();
  232. if (ObjectType->isRecordType())
  233. LookupCtx = computeDeclContext(ObjectType);
  234. } else if (SS && SS->isNotEmpty()) {
  235. LookupCtx = computeDeclContext(*SS, false);
  236. if (!LookupCtx) {
  237. if (isDependentScopeSpecifier(*SS)) {
  238. // C++ [temp.res]p3:
  239. // A qualified-id that refers to a type and in which the
  240. // nested-name-specifier depends on a template-parameter (14.6.2)
  241. // shall be prefixed by the keyword typename to indicate that the
  242. // qualified-id denotes a type, forming an
  243. // elaborated-type-specifier (7.1.5.3).
  244. //
  245. // We therefore do not perform any name lookup if the result would
  246. // refer to a member of an unknown specialization.
  247. if (!isClassName && !IsCtorOrDtorName)
  248. return ParsedType();
  249. // We know from the grammar that this name refers to a type,
  250. // so build a dependent node to describe the type.
  251. if (WantNontrivialTypeSourceInfo)
  252. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  253. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  254. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  255. II, NameLoc);
  256. return ParsedType::make(T);
  257. }
  258. return ParsedType();
  259. }
  260. if (!LookupCtx->isDependentContext() &&
  261. RequireCompleteDeclContext(*SS, LookupCtx))
  262. return ParsedType();
  263. }
  264. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  265. // lookup for class-names.
  266. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  267. LookupOrdinaryName;
  268. LookupResult Result(*this, &II, NameLoc, Kind);
  269. if (LookupCtx) {
  270. // Perform "qualified" name lookup into the declaration context we
  271. // computed, which is either the type of the base of a member access
  272. // expression or the declaration context associated with a prior
  273. // nested-name-specifier.
  274. LookupQualifiedName(Result, LookupCtx);
  275. if (ObjectTypePtr && Result.empty()) {
  276. // C++ [basic.lookup.classref]p3:
  277. // If the unqualified-id is ~type-name, the type-name is looked up
  278. // in the context of the entire postfix-expression. If the type T of
  279. // the object expression is of a class type C, the type-name is also
  280. // looked up in the scope of class C. At least one of the lookups shall
  281. // find a name that refers to (possibly cv-qualified) T.
  282. LookupName(Result, S);
  283. }
  284. } else {
  285. // Perform unqualified name lookup.
  286. LookupName(Result, S);
  287. // For unqualified lookup in a class template in MSVC mode, look into
  288. // dependent base classes where the primary class template is known.
  289. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  290. if (ParsedType TypeInBase =
  291. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  292. return TypeInBase;
  293. }
  294. }
  295. NamedDecl *IIDecl = nullptr;
  296. switch (Result.getResultKind()) {
  297. case LookupResult::NotFound:
  298. case LookupResult::NotFoundInCurrentInstantiation:
  299. if (CorrectedII) {
  300. TypoCorrection Correction = CorrectTypo(
  301. Result.getLookupNameInfo(), Kind, S, SS,
  302. llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
  303. CTK_ErrorRecovery);
  304. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  305. TemplateTy Template;
  306. bool MemberOfUnknownSpecialization;
  307. UnqualifiedId TemplateName;
  308. TemplateName.setIdentifier(NewII, NameLoc);
  309. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  310. CXXScopeSpec NewSS, *NewSSPtr = SS;
  311. if (SS && NNS) {
  312. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  313. NewSSPtr = &NewSS;
  314. }
  315. if (Correction && (NNS || NewII != &II) &&
  316. // Ignore a correction to a template type as the to-be-corrected
  317. // identifier is not a template (typo correction for template names
  318. // is handled elsewhere).
  319. !(getLangOpts().CPlusPlus && NewSSPtr &&
  320. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  321. false, Template, MemberOfUnknownSpecialization))) {
  322. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  323. isClassName, HasTrailingDot, ObjectTypePtr,
  324. IsCtorOrDtorName,
  325. WantNontrivialTypeSourceInfo);
  326. if (Ty) {
  327. diagnoseTypo(Correction,
  328. PDiag(diag::err_unknown_type_or_class_name_suggest)
  329. << Result.getLookupName() << isClassName);
  330. if (SS && NNS)
  331. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  332. *CorrectedII = NewII;
  333. return Ty;
  334. }
  335. }
  336. }
  337. // If typo correction failed or was not performed, fall through
  338. case LookupResult::FoundOverloaded:
  339. case LookupResult::FoundUnresolvedValue:
  340. Result.suppressDiagnostics();
  341. return ParsedType();
  342. case LookupResult::Ambiguous:
  343. // Recover from type-hiding ambiguities by hiding the type. We'll
  344. // do the lookup again when looking for an object, and we can
  345. // diagnose the error then. If we don't do this, then the error
  346. // about hiding the type will be immediately followed by an error
  347. // that only makes sense if the identifier was treated like a type.
  348. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  349. Result.suppressDiagnostics();
  350. return ParsedType();
  351. }
  352. // Look to see if we have a type anywhere in the list of results.
  353. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  354. Res != ResEnd; ++Res) {
  355. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  356. if (!IIDecl ||
  357. (*Res)->getLocation().getRawEncoding() <
  358. IIDecl->getLocation().getRawEncoding())
  359. IIDecl = *Res;
  360. }
  361. }
  362. if (!IIDecl) {
  363. // None of the entities we found is a type, so there is no way
  364. // to even assume that the result is a type. In this case, don't
  365. // complain about the ambiguity. The parser will either try to
  366. // perform this lookup again (e.g., as an object name), which
  367. // will produce the ambiguity, or will complain that it expected
  368. // a type name.
  369. Result.suppressDiagnostics();
  370. return ParsedType();
  371. }
  372. // We found a type within the ambiguous lookup; diagnose the
  373. // ambiguity and then return that type. This might be the right
  374. // answer, or it might not be, but it suppresses any attempt to
  375. // perform the name lookup again.
  376. break;
  377. case LookupResult::Found:
  378. IIDecl = Result.getFoundDecl();
  379. break;
  380. }
  381. assert(IIDecl && "Didn't find decl");
  382. QualType T;
  383. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  384. DiagnoseUseOfDecl(IIDecl, NameLoc);
  385. T = Context.getTypeDeclType(TD);
  386. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  387. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  388. // constructor or destructor name (in such a case, the scope specifier
  389. // will be attached to the enclosing Expr or Decl node).
  390. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  391. if (WantNontrivialTypeSourceInfo) {
  392. // Construct a type with type-source information.
  393. TypeLocBuilder Builder;
  394. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  395. T = getElaboratedType(ETK_None, *SS, T);
  396. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  397. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  398. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  399. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  400. } else {
  401. T = getElaboratedType(ETK_None, *SS, T);
  402. }
  403. }
  404. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  405. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  406. if (!HasTrailingDot)
  407. T = Context.getObjCInterfaceType(IDecl);
  408. }
  409. if (T.isNull()) {
  410. // If it's not plausibly a type, suppress diagnostics.
  411. Result.suppressDiagnostics();
  412. return ParsedType();
  413. }
  414. return ParsedType::make(T);
  415. }
  416. // Builds a fake NNS for the given decl context.
  417. static NestedNameSpecifier *
  418. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  419. for (;; DC = DC->getLookupParent()) {
  420. DC = DC->getPrimaryContext();
  421. auto *ND = dyn_cast<NamespaceDecl>(DC);
  422. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  423. return NestedNameSpecifier::Create(Context, nullptr, ND);
  424. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  425. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  426. RD->getTypeForDecl());
  427. else if (isa<TranslationUnitDecl>(DC))
  428. return NestedNameSpecifier::GlobalSpecifier(Context);
  429. }
  430. llvm_unreachable("something isn't in TU scope?");
  431. }
  432. ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
  433. SourceLocation NameLoc) {
  434. // Accepting an undeclared identifier as a default argument for a template
  435. // type parameter is a Microsoft extension.
  436. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  437. // Build a fake DependentNameType that will perform lookup into CurContext at
  438. // instantiation time. The name specifier isn't dependent, so template
  439. // instantiation won't transform it. It will retry the lookup, however.
  440. NestedNameSpecifier *NNS =
  441. synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  442. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  443. // Build type location information. We synthesized the qualifier, so we have
  444. // to build a fake NestedNameSpecifierLoc.
  445. NestedNameSpecifierLocBuilder NNSLocBuilder;
  446. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  447. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  448. TypeLocBuilder Builder;
  449. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  450. DepTL.setNameLoc(NameLoc);
  451. DepTL.setElaboratedKeywordLoc(SourceLocation());
  452. DepTL.setQualifierLoc(QualifierLoc);
  453. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  454. }
  455. /// isTagName() - This method is called *for error recovery purposes only*
  456. /// to determine if the specified name is a valid tag name ("struct foo"). If
  457. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  458. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  459. /// cases in C where the user forgot to specify the tag.
  460. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  461. // Do a tag name lookup in this scope.
  462. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  463. LookupName(R, S, false);
  464. R.suppressDiagnostics();
  465. if (R.getResultKind() == LookupResult::Found)
  466. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  467. switch (TD->getTagKind()) {
  468. case TTK_Struct: return DeclSpec::TST_struct;
  469. case TTK_Interface: return DeclSpec::TST_interface;
  470. case TTK_Union: return DeclSpec::TST_union;
  471. case TTK_Class: return DeclSpec::TST_class;
  472. case TTK_Enum: return DeclSpec::TST_enum;
  473. }
  474. }
  475. return DeclSpec::TST_unspecified;
  476. }
  477. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  478. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  479. /// then downgrade the missing typename error to a warning.
  480. /// This is needed for MSVC compatibility; Example:
  481. /// @code
  482. /// template<class T> class A {
  483. /// public:
  484. /// typedef int TYPE;
  485. /// };
  486. /// template<class T> class B : public A<T> {
  487. /// public:
  488. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  489. /// };
  490. /// @endcode
  491. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  492. if (CurContext->isRecord()) {
  493. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  494. return true;
  495. const Type *Ty = SS->getScopeRep()->getAsType();
  496. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  497. for (const auto &Base : RD->bases())
  498. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  499. return true;
  500. return S->isFunctionPrototypeScope();
  501. }
  502. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  503. }
  504. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  505. SourceLocation IILoc,
  506. Scope *S,
  507. CXXScopeSpec *SS,
  508. ParsedType &SuggestedType,
  509. bool AllowClassTemplates) {
  510. // We don't have anything to suggest (yet).
  511. SuggestedType = ParsedType();
  512. // There may have been a typo in the name of the type. Look up typo
  513. // results, in case we have something that we can suggest.
  514. if (TypoCorrection Corrected =
  515. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  516. llvm::make_unique<TypeNameValidatorCCC>(
  517. false, false, AllowClassTemplates),
  518. CTK_ErrorRecovery)) {
  519. if (Corrected.isKeyword()) {
  520. // We corrected to a keyword.
  521. diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
  522. II = Corrected.getCorrectionAsIdentifierInfo();
  523. } else {
  524. // We found a similarly-named type or interface; suggest that.
  525. if (!SS || !SS->isSet()) {
  526. diagnoseTypo(Corrected,
  527. PDiag(diag::err_unknown_typename_suggest) << II);
  528. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  529. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  530. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  531. II->getName().equals(CorrectedStr);
  532. diagnoseTypo(Corrected,
  533. PDiag(diag::err_unknown_nested_typename_suggest)
  534. << II << DC << DroppedSpecifier << SS->getRange());
  535. } else {
  536. llvm_unreachable("could not have corrected a typo here");
  537. }
  538. CXXScopeSpec tmpSS;
  539. if (Corrected.getCorrectionSpecifier())
  540. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  541. SourceRange(IILoc));
  542. SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
  543. IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
  544. false, ParsedType(),
  545. /*IsCtorOrDtorName=*/false,
  546. /*NonTrivialTypeSourceInfo=*/true);
  547. }
  548. return;
  549. }
  550. if (getLangOpts().CPlusPlus) {
  551. // See if II is a class template that the user forgot to pass arguments to.
  552. UnqualifiedId Name;
  553. Name.setIdentifier(II, IILoc);
  554. CXXScopeSpec EmptySS;
  555. TemplateTy TemplateResult;
  556. bool MemberOfUnknownSpecialization;
  557. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  558. Name, ParsedType(), true, TemplateResult,
  559. MemberOfUnknownSpecialization) == TNK_Type_template) {
  560. TemplateName TplName = TemplateResult.get();
  561. Diag(IILoc, diag::err_template_missing_args) << TplName;
  562. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  563. if (TplDecl->getLocation().isValid()) { // HLSL Change - ellide location notes for built-ins
  564. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  565. << TplDecl->getTemplateParameters()->getSourceRange();
  566. }
  567. }
  568. return;
  569. }
  570. }
  571. // FIXME: Should we move the logic that tries to recover from a missing tag
  572. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  573. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  574. Diag(IILoc, diag::err_unknown_typename) << II;
  575. else if (DeclContext *DC = computeDeclContext(*SS, false))
  576. Diag(IILoc, diag::err_typename_nested_not_found)
  577. << II << DC << SS->getRange();
  578. else if (isDependentScopeSpecifier(*SS)) {
  579. unsigned DiagID = diag::err_typename_missing;
  580. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  581. DiagID = diag::ext_typename_missing;
  582. Diag(SS->getRange().getBegin(), DiagID)
  583. << SS->getScopeRep() << II->getName()
  584. << SourceRange(SS->getRange().getBegin(), IILoc)
  585. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  586. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  587. *SS, *II, IILoc).get();
  588. } else {
  589. assert(SS && SS->isInvalid() &&
  590. "Invalid scope specifier has already been diagnosed");
  591. }
  592. }
  593. /// \brief Determine whether the given result set contains either a type name
  594. /// or
  595. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  596. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  597. NextToken.is(tok::less);
  598. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  599. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  600. return true;
  601. if (CheckTemplate && isa<TemplateDecl>(*I))
  602. return true;
  603. }
  604. return false;
  605. }
  606. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  607. Scope *S, CXXScopeSpec &SS,
  608. IdentifierInfo *&Name,
  609. SourceLocation NameLoc) {
  610. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  611. SemaRef.LookupParsedName(R, S, &SS);
  612. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  613. StringRef FixItTagName;
  614. switch (Tag->getTagKind()) {
  615. case TTK_Class:
  616. FixItTagName = "class ";
  617. break;
  618. case TTK_Enum:
  619. FixItTagName = "enum ";
  620. break;
  621. case TTK_Struct:
  622. FixItTagName = "struct ";
  623. break;
  624. case TTK_Interface:
  625. FixItTagName = "__interface ";
  626. break;
  627. case TTK_Union:
  628. FixItTagName = "union ";
  629. break;
  630. }
  631. StringRef TagName = FixItTagName.drop_back();
  632. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  633. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  634. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  635. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  636. I != IEnd; ++I)
  637. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  638. << Name << TagName;
  639. // Replace lookup results with just the tag decl.
  640. Result.clear(Sema::LookupTagName);
  641. SemaRef.LookupParsedName(Result, S, &SS);
  642. return true;
  643. }
  644. return false;
  645. }
  646. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  647. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  648. QualType T, SourceLocation NameLoc) {
  649. ASTContext &Context = S.Context;
  650. TypeLocBuilder Builder;
  651. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  652. T = S.getElaboratedType(ETK_None, SS, T);
  653. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  654. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  655. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  656. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  657. }
  658. Sema::NameClassification
  659. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  660. SourceLocation NameLoc, const Token &NextToken,
  661. bool IsAddressOfOperand,
  662. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  663. DeclarationNameInfo NameInfo(Name, NameLoc);
  664. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  665. if (NextToken.is(tok::coloncolon)) {
  666. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  667. QualType(), false, SS, nullptr, false);
  668. }
  669. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  670. LookupParsedName(Result, S, &SS, !CurMethod);
  671. // For unqualified lookup in a class template in MSVC mode, look into
  672. // dependent base classes where the primary class template is known.
  673. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  674. if (ParsedType TypeInBase =
  675. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  676. return TypeInBase;
  677. }
  678. // Perform lookup for Objective-C instance variables (including automatically
  679. // synthesized instance variables), if we're in an Objective-C method.
  680. // FIXME: This lookup really, really needs to be folded in to the normal
  681. // unqualified lookup mechanism.
  682. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  683. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  684. if (E.get() || E.isInvalid())
  685. return E;
  686. }
  687. bool SecondTry = false;
  688. bool IsFilteredTemplateName = false;
  689. Corrected:
  690. switch (Result.getResultKind()) {
  691. case LookupResult::NotFound:
  692. // If an unqualified-id is followed by a '(', then we have a function
  693. // call.
  694. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  695. // In C++, this is an ADL-only call.
  696. // FIXME: Reference?
  697. if (getLangOpts().CPlusPlus)
  698. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  699. // C90 6.3.2.2:
  700. // If the expression that precedes the parenthesized argument list in a
  701. // function call consists solely of an identifier, and if no
  702. // declaration is visible for this identifier, the identifier is
  703. // implicitly declared exactly as if, in the innermost block containing
  704. // the function call, the declaration
  705. //
  706. // extern int identifier ();
  707. //
  708. // appeared.
  709. //
  710. // We also allow this in C99 as an extension.
  711. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  712. Result.addDecl(D);
  713. Result.resolveKind();
  714. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  715. }
  716. }
  717. // In C, we first see whether there is a tag type by the same name, in
  718. // which case it's likely that the user just forget to write "enum",
  719. // "struct", or "union".
  720. if (!getLangOpts().CPlusPlus && !SecondTry &&
  721. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  722. break;
  723. }
  724. // Perform typo correction to determine if there is another name that is
  725. // close to this name.
  726. if (!SecondTry && CCC) {
  727. SecondTry = true;
  728. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  729. Result.getLookupKind(), S,
  730. &SS, std::move(CCC),
  731. CTK_ErrorRecovery)) {
  732. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  733. unsigned QualifiedDiag = diag::err_no_member_suggest;
  734. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  735. NamedDecl *UnderlyingFirstDecl
  736. = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
  737. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  738. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  739. UnqualifiedDiag = diag::err_no_template_suggest;
  740. QualifiedDiag = diag::err_no_member_template_suggest;
  741. } else if (UnderlyingFirstDecl &&
  742. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  743. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  744. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  745. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  746. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  747. }
  748. if (SS.isEmpty()) {
  749. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  750. } else {// FIXME: is this even reachable? Test it.
  751. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  752. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  753. Name->getName().equals(CorrectedStr);
  754. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  755. << Name << computeDeclContext(SS, false)
  756. << DroppedSpecifier << SS.getRange());
  757. }
  758. // Update the name, so that the caller has the new name.
  759. Name = Corrected.getCorrectionAsIdentifierInfo();
  760. // Typo correction corrected to a keyword.
  761. if (Corrected.isKeyword())
  762. return Name;
  763. // Also update the LookupResult...
  764. // FIXME: This should probably go away at some point
  765. Result.clear();
  766. Result.setLookupName(Corrected.getCorrection());
  767. if (FirstDecl)
  768. Result.addDecl(FirstDecl);
  769. // If we found an Objective-C instance variable, let
  770. // LookupInObjCMethod build the appropriate expression to
  771. // reference the ivar.
  772. // FIXME: This is a gross hack.
  773. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  774. Result.clear();
  775. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  776. return E;
  777. }
  778. goto Corrected;
  779. }
  780. }
  781. // We failed to correct; just fall through and let the parser deal with it.
  782. Result.suppressDiagnostics();
  783. return NameClassification::Unknown();
  784. case LookupResult::NotFoundInCurrentInstantiation: {
  785. // We performed name lookup into the current instantiation, and there were
  786. // dependent bases, so we treat this result the same way as any other
  787. // dependent nested-name-specifier.
  788. // C++ [temp.res]p2:
  789. // A name used in a template declaration or definition and that is
  790. // dependent on a template-parameter is assumed not to name a type
  791. // unless the applicable name lookup finds a type name or the name is
  792. // qualified by the keyword typename.
  793. //
  794. // FIXME: If the next token is '<', we might want to ask the parser to
  795. // perform some heroics to see if we actually have a
  796. // template-argument-list, which would indicate a missing 'template'
  797. // keyword here.
  798. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  799. NameInfo, IsAddressOfOperand,
  800. /*TemplateArgs=*/nullptr);
  801. }
  802. case LookupResult::Found:
  803. case LookupResult::FoundOverloaded:
  804. case LookupResult::FoundUnresolvedValue:
  805. break;
  806. case LookupResult::Ambiguous:
  807. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  808. hasAnyAcceptableTemplateNames(Result)) {
  809. // C++ [temp.local]p3:
  810. // A lookup that finds an injected-class-name (10.2) can result in an
  811. // ambiguity in certain cases (for example, if it is found in more than
  812. // one base class). If all of the injected-class-names that are found
  813. // refer to specializations of the same class template, and if the name
  814. // is followed by a template-argument-list, the reference refers to the
  815. // class template itself and not a specialization thereof, and is not
  816. // ambiguous.
  817. //
  818. // This filtering can make an ambiguous result into an unambiguous one,
  819. // so try again after filtering out template names.
  820. FilterAcceptableTemplateNames(Result);
  821. if (!Result.isAmbiguous()) {
  822. IsFilteredTemplateName = true;
  823. break;
  824. }
  825. }
  826. // Diagnose the ambiguity and return an error.
  827. return NameClassification::Error();
  828. }
  829. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  830. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  831. // C++ [temp.names]p3:
  832. // After name lookup (3.4) finds that a name is a template-name or that
  833. // an operator-function-id or a literal- operator-id refers to a set of
  834. // overloaded functions any member of which is a function template if
  835. // this is followed by a <, the < is always taken as the delimiter of a
  836. // template-argument-list and never as the less-than operator.
  837. if (!IsFilteredTemplateName)
  838. FilterAcceptableTemplateNames(Result);
  839. if (!Result.empty()) {
  840. bool IsFunctionTemplate;
  841. bool IsVarTemplate;
  842. TemplateName Template;
  843. if (Result.end() - Result.begin() > 1) {
  844. IsFunctionTemplate = true;
  845. Template = Context.getOverloadedTemplateName(Result.begin(),
  846. Result.end());
  847. } else {
  848. TemplateDecl *TD
  849. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  850. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  851. IsVarTemplate = isa<VarTemplateDecl>(TD);
  852. if (SS.isSet() && !SS.isInvalid())
  853. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  854. /*TemplateKeyword=*/false,
  855. TD);
  856. else
  857. Template = TemplateName(TD);
  858. }
  859. if (IsFunctionTemplate) {
  860. // Function templates always go through overload resolution, at which
  861. // point we'll perform the various checks (e.g., accessibility) we need
  862. // to based on which function we selected.
  863. Result.suppressDiagnostics();
  864. return NameClassification::FunctionTemplate(Template);
  865. }
  866. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  867. : NameClassification::TypeTemplate(Template);
  868. }
  869. }
  870. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  871. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  872. DiagnoseUseOfDecl(Type, NameLoc);
  873. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  874. QualType T = Context.getTypeDeclType(Type);
  875. if (SS.isNotEmpty())
  876. return buildNestedType(*this, SS, T, NameLoc);
  877. return ParsedType::make(T);
  878. }
  879. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  880. if (!Class) {
  881. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  882. if (ObjCCompatibleAliasDecl *Alias =
  883. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  884. Class = Alias->getClassInterface();
  885. }
  886. if (Class) {
  887. DiagnoseUseOfDecl(Class, NameLoc);
  888. if (NextToken.is(tok::period)) {
  889. // Interface. <something> is parsed as a property reference expression.
  890. // Just return "unknown" as a fall-through for now.
  891. Result.suppressDiagnostics();
  892. return NameClassification::Unknown();
  893. }
  894. QualType T = Context.getObjCInterfaceType(Class);
  895. return ParsedType::make(T);
  896. }
  897. // We can have a type template here if we're classifying a template argument.
  898. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
  899. return NameClassification::TypeTemplate(
  900. TemplateName(cast<TemplateDecl>(FirstDecl)));
  901. // Check for a tag type hidden by a non-type decl in a few cases where it
  902. // seems likely a type is wanted instead of the non-type that was found.
  903. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  904. if ((NextToken.is(tok::identifier) ||
  905. (NextIsOp &&
  906. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  907. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  908. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  909. DiagnoseUseOfDecl(Type, NameLoc);
  910. QualType T = Context.getTypeDeclType(Type);
  911. if (SS.isNotEmpty())
  912. return buildNestedType(*this, SS, T, NameLoc);
  913. return ParsedType::make(T);
  914. }
  915. if (FirstDecl->isCXXClassMember())
  916. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  917. nullptr);
  918. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  919. return BuildDeclarationNameExpr(SS, Result, ADL);
  920. }
  921. // Determines the context to return to after temporarily entering a
  922. // context. This depends in an unnecessarily complicated way on the
  923. // exact ordering of callbacks from the parser.
  924. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  925. // Functions defined inline within classes aren't parsed until we've
  926. // finished parsing the top-level class, so the top-level class is
  927. // the context we'll need to return to.
  928. // A Lambda call operator whose parent is a class must not be treated
  929. // as an inline member function. A Lambda can be used legally
  930. // either as an in-class member initializer or a default argument. These
  931. // are parsed once the class has been marked complete and so the containing
  932. // context would be the nested class (when the lambda is defined in one);
  933. // If the class is not complete, then the lambda is being used in an
  934. // ill-formed fashion (such as to specify the width of a bit-field, or
  935. // in an array-bound) - in which case we still want to return the
  936. // lexically containing DC (which could be a nested class).
  937. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  938. DC = DC->getLexicalParent();
  939. // A function not defined within a class will always return to its
  940. // lexical context.
  941. if (!isa<CXXRecordDecl>(DC))
  942. return DC;
  943. // A C++ inline method/friend is parsed *after* the topmost class
  944. // it was declared in is fully parsed ("complete"); the topmost
  945. // class is the context we need to return to.
  946. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  947. DC = RD;
  948. // Return the declaration context of the topmost class the inline method is
  949. // declared in.
  950. return DC;
  951. }
  952. return DC->getLexicalParent();
  953. }
  954. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  955. assert(getContainingDC(DC) == CurContext &&
  956. "The next DeclContext should be lexically contained in the current one.");
  957. CurContext = DC;
  958. S->setEntity(DC);
  959. }
  960. void Sema::PopDeclContext() {
  961. assert(CurContext && "DeclContext imbalance!");
  962. CurContext = getContainingDC(CurContext);
  963. assert(CurContext && "Popped translation unit!");
  964. }
  965. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  966. Decl *D) {
  967. // Unlike PushDeclContext, the context to which we return is not necessarily
  968. // the containing DC of TD, because the new context will be some pre-existing
  969. // TagDecl definition instead of a fresh one.
  970. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  971. CurContext = cast<TagDecl>(D)->getDefinition();
  972. assert(CurContext && "skipping definition of undefined tag");
  973. S->setEntity(CurContext);
  974. return Result;
  975. }
  976. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  977. CurContext = static_cast<decltype(CurContext)>(Context);
  978. }
  979. /// EnterDeclaratorContext - Used when we must lookup names in the context
  980. /// of a declarator's nested name specifier.
  981. ///
  982. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  983. // C++0x [basic.lookup.unqual]p13:
  984. // A name used in the definition of a static data member of class
  985. // X (after the qualified-id of the static member) is looked up as
  986. // if the name was used in a member function of X.
  987. // C++0x [basic.lookup.unqual]p14:
  988. // If a variable member of a namespace is defined outside of the
  989. // scope of its namespace then any name used in the definition of
  990. // the variable member (after the declarator-id) is looked up as
  991. // if the definition of the variable member occurred in its
  992. // namespace.
  993. // Both of these imply that we should push a scope whose context
  994. // is the semantic context of the declaration. We can't use
  995. // PushDeclContext here because that context is not necessarily
  996. // lexically contained in the current context. Fortunately,
  997. // the containing scope should have the appropriate information.
  998. assert(!S->getEntity() && "scope already has entity");
  999. #ifndef NDEBUG
  1000. Scope *Ancestor = S->getParent();
  1001. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1002. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1003. #endif
  1004. CurContext = DC;
  1005. S->setEntity(DC);
  1006. }
  1007. void Sema::ExitDeclaratorContext(Scope *S) {
  1008. assert(S->getEntity() == CurContext && "Context imbalance!");
  1009. // Switch back to the lexical context. The safety of this is
  1010. // enforced by an assert in EnterDeclaratorContext.
  1011. Scope *Ancestor = S->getParent();
  1012. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1013. CurContext = Ancestor->getEntity();
  1014. // We don't need to do anything with the scope, which is going to
  1015. // disappear.
  1016. }
  1017. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1018. // We assume that the caller has already called
  1019. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1020. FunctionDecl *FD = D->getAsFunction();
  1021. if (!FD)
  1022. return;
  1023. // Same implementation as PushDeclContext, but enters the context
  1024. // from the lexical parent, rather than the top-level class.
  1025. assert(CurContext == FD->getLexicalParent() &&
  1026. "The next DeclContext should be lexically contained in the current one.");
  1027. CurContext = FD;
  1028. S->setEntity(CurContext);
  1029. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1030. ParmVarDecl *Param = FD->getParamDecl(P);
  1031. // If the parameter has an identifier, then add it to the scope
  1032. if (Param->getIdentifier()) {
  1033. S->AddDecl(Param);
  1034. IdResolver.AddDecl(Param);
  1035. }
  1036. }
  1037. }
  1038. void Sema::ActOnExitFunctionContext() {
  1039. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1040. // rather than the top-level class.
  1041. assert(CurContext && "DeclContext imbalance!");
  1042. CurContext = CurContext->getLexicalParent();
  1043. assert(CurContext && "Popped translation unit!");
  1044. }
  1045. /// \brief Determine whether we allow overloading of the function
  1046. /// PrevDecl with another declaration.
  1047. ///
  1048. /// This routine determines whether overloading is possible, not
  1049. /// whether some new function is actually an overload. It will return
  1050. /// true in C++ (where we can always provide overloads) or, as an
  1051. /// extension, in C when the previous function is already an
  1052. /// overloaded function declaration or has the "overloadable"
  1053. /// attribute.
  1054. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1055. ASTContext &Context) {
  1056. if (Context.getLangOpts().CPlusPlus)
  1057. return true;
  1058. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1059. return true;
  1060. return (Previous.getResultKind() == LookupResult::Found
  1061. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  1062. }
  1063. /// Add this decl to the scope shadowed decl chains.
  1064. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1065. // Move up the scope chain until we find the nearest enclosing
  1066. // non-transparent context. The declaration will be introduced into this
  1067. // scope.
  1068. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1069. S = S->getParent();
  1070. // Add scoped declarations into their context, so that they can be
  1071. // found later. Declarations without a context won't be inserted
  1072. // into any context.
  1073. if (AddToContext)
  1074. CurContext->addDecl(D);
  1075. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1076. // are function-local declarations.
  1077. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1078. !D->getDeclContext()->getRedeclContext()->Equals(
  1079. D->getLexicalDeclContext()->getRedeclContext()) &&
  1080. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1081. return;
  1082. // Template instantiations should also not be pushed into scope.
  1083. if (isa<FunctionDecl>(D) &&
  1084. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1085. return;
  1086. // If this replaces anything in the current scope,
  1087. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1088. IEnd = IdResolver.end();
  1089. for (; I != IEnd; ++I) {
  1090. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1091. S->RemoveDecl(*I);
  1092. IdResolver.RemoveDecl(*I);
  1093. // Should only need to replace one decl.
  1094. break;
  1095. }
  1096. }
  1097. S->AddDecl(D);
  1098. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1099. // Implicitly-generated labels may end up getting generated in an order that
  1100. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1101. // the label at the appropriate place in the identifier chain.
  1102. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1103. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1104. if (IDC == CurContext) {
  1105. if (!S->isDeclScope(*I))
  1106. continue;
  1107. } else if (IDC->Encloses(CurContext))
  1108. break;
  1109. }
  1110. IdResolver.InsertDeclAfter(I, D);
  1111. } else {
  1112. IdResolver.AddDecl(D);
  1113. }
  1114. }
  1115. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1116. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1117. TUScope->AddDecl(D);
  1118. }
  1119. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1120. bool AllowInlineNamespace) {
  1121. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1122. }
  1123. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1124. DeclContext *TargetDC = DC->getPrimaryContext();
  1125. do {
  1126. if (DeclContext *ScopeDC = S->getEntity())
  1127. if (ScopeDC->getPrimaryContext() == TargetDC)
  1128. return S;
  1129. } while ((S = S->getParent()));
  1130. return nullptr;
  1131. }
  1132. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1133. DeclContext*,
  1134. ASTContext&);
  1135. /// Filters out lookup results that don't fall within the given scope
  1136. /// as determined by isDeclInScope.
  1137. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1138. bool ConsiderLinkage,
  1139. bool AllowInlineNamespace) {
  1140. LookupResult::Filter F = R.makeFilter();
  1141. while (F.hasNext()) {
  1142. NamedDecl *D = F.next();
  1143. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1144. continue;
  1145. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1146. continue;
  1147. F.erase();
  1148. }
  1149. F.done();
  1150. }
  1151. static bool isUsingDecl(NamedDecl *D) {
  1152. return isa<UsingShadowDecl>(D) ||
  1153. isa<UnresolvedUsingTypenameDecl>(D) ||
  1154. isa<UnresolvedUsingValueDecl>(D);
  1155. }
  1156. /// Removes using shadow declarations from the lookup results.
  1157. static void RemoveUsingDecls(LookupResult &R) {
  1158. LookupResult::Filter F = R.makeFilter();
  1159. while (F.hasNext())
  1160. if (isUsingDecl(F.next()))
  1161. F.erase();
  1162. F.done();
  1163. }
  1164. /// \brief Check for this common pattern:
  1165. /// @code
  1166. /// class S {
  1167. /// S(const S&); // DO NOT IMPLEMENT
  1168. /// void operator=(const S&); // DO NOT IMPLEMENT
  1169. /// };
  1170. /// @endcode
  1171. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1172. // FIXME: Should check for private access too but access is set after we get
  1173. // the decl here.
  1174. if (D->doesThisDeclarationHaveABody())
  1175. return false;
  1176. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1177. return CD->isCopyConstructor();
  1178. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1179. return Method->isCopyAssignmentOperator();
  1180. return false;
  1181. }
  1182. // We need this to handle
  1183. //
  1184. // typedef struct {
  1185. // void *foo() { return 0; }
  1186. // } A;
  1187. //
  1188. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1189. // for example. If 'A', foo will have external linkage. If we have '*A',
  1190. // foo will have no linkage. Since we can't know until we get to the end
  1191. // of the typedef, this function finds out if D might have non-external linkage.
  1192. // Callers should verify at the end of the TU if it D has external linkage or
  1193. // not.
  1194. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1195. const DeclContext *DC = D->getDeclContext();
  1196. while (!DC->isTranslationUnit()) {
  1197. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1198. if (!RD->hasNameForLinkage())
  1199. return true;
  1200. }
  1201. DC = DC->getParent();
  1202. }
  1203. return !D->isExternallyVisible();
  1204. }
  1205. // FIXME: This needs to be refactored; some other isInMainFile users want
  1206. // these semantics.
  1207. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1208. if (S.TUKind != TU_Complete)
  1209. return false;
  1210. return S.SourceMgr.isInMainFile(Loc);
  1211. }
  1212. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1213. assert(D);
  1214. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1215. return false;
  1216. // Ignore all entities declared within templates, and out-of-line definitions
  1217. // of members of class templates.
  1218. if (D->getDeclContext()->isDependentContext() ||
  1219. D->getLexicalDeclContext()->isDependentContext())
  1220. return false;
  1221. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1222. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1223. return false;
  1224. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1225. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1226. return false;
  1227. } else {
  1228. // 'static inline' functions are defined in headers; don't warn.
  1229. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1230. return false;
  1231. }
  1232. if (FD->doesThisDeclarationHaveABody() &&
  1233. Context.DeclMustBeEmitted(FD))
  1234. return false;
  1235. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1236. // Constants and utility variables are defined in headers with internal
  1237. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1238. // like "inline".)
  1239. if (!isMainFileLoc(*this, VD->getLocation()))
  1240. return false;
  1241. if (Context.DeclMustBeEmitted(VD))
  1242. return false;
  1243. if (VD->isStaticDataMember() &&
  1244. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1245. return false;
  1246. } else {
  1247. return false;
  1248. }
  1249. // Only warn for unused decls internal to the translation unit.
  1250. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1251. // for inline functions defined in the main source file, for instance.
  1252. return mightHaveNonExternalLinkage(D);
  1253. }
  1254. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1255. if (!D)
  1256. return;
  1257. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1258. const FunctionDecl *First = FD->getFirstDecl();
  1259. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1260. return; // First should already be in the vector.
  1261. }
  1262. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1263. const VarDecl *First = VD->getFirstDecl();
  1264. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1265. return; // First should already be in the vector.
  1266. }
  1267. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1268. UnusedFileScopedDecls.push_back(D);
  1269. }
  1270. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1271. if (D->isInvalidDecl())
  1272. return false;
  1273. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
  1274. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1275. return false;
  1276. if (isa<LabelDecl>(D))
  1277. return true;
  1278. // Except for labels, we only care about unused decls that are local to
  1279. // functions.
  1280. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1281. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1282. // For dependent types, the diagnostic is deferred.
  1283. WithinFunction =
  1284. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1285. if (!WithinFunction)
  1286. return false;
  1287. if (isa<TypedefNameDecl>(D))
  1288. return true;
  1289. // White-list anything that isn't a local variable.
  1290. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1291. return false;
  1292. // Types of valid local variables should be complete, so this should succeed.
  1293. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1294. // White-list anything with an __attribute__((unused)) type.
  1295. QualType Ty = VD->getType();
  1296. // Only look at the outermost level of typedef.
  1297. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1298. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1299. return false;
  1300. }
  1301. // If we failed to complete the type for some reason, or if the type is
  1302. // dependent, don't diagnose the variable.
  1303. if (Ty->isIncompleteType() || Ty->isDependentType())
  1304. return false;
  1305. if (const TagType *TT = Ty->getAs<TagType>()) {
  1306. const TagDecl *Tag = TT->getDecl();
  1307. if (Tag->hasAttr<UnusedAttr>())
  1308. return false;
  1309. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1310. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1311. return false;
  1312. if (const Expr *Init = VD->getInit()) {
  1313. if (const ExprWithCleanups *Cleanups =
  1314. dyn_cast<ExprWithCleanups>(Init))
  1315. Init = Cleanups->getSubExpr();
  1316. const CXXConstructExpr *Construct =
  1317. dyn_cast<CXXConstructExpr>(Init);
  1318. if (Construct && !Construct->isElidable()) {
  1319. CXXConstructorDecl *CD = Construct->getConstructor();
  1320. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
  1321. return false;
  1322. }
  1323. }
  1324. }
  1325. }
  1326. // TODO: __attribute__((unused)) templates?
  1327. }
  1328. return true;
  1329. }
  1330. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1331. FixItHint &Hint) {
  1332. if (isa<LabelDecl>(D)) {
  1333. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1334. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1335. if (AfterColon.isInvalid())
  1336. return;
  1337. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1338. getCharRange(D->getLocStart(), AfterColon));
  1339. }
  1340. return;
  1341. }
  1342. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1343. if (D->getTypeForDecl()->isDependentType())
  1344. return;
  1345. for (auto *TmpD : D->decls()) {
  1346. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1347. DiagnoseUnusedDecl(T);
  1348. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1349. DiagnoseUnusedNestedTypedefs(R);
  1350. }
  1351. }
  1352. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1353. /// unless they are marked attr(unused).
  1354. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1355. if (!ShouldDiagnoseUnusedDecl(D))
  1356. return;
  1357. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1358. // typedefs can be referenced later on, so the diagnostics are emitted
  1359. // at end-of-translation-unit.
  1360. UnusedLocalTypedefNameCandidates.insert(TD);
  1361. return;
  1362. }
  1363. FixItHint Hint;
  1364. GenerateFixForUnusedDecl(D, Context, Hint);
  1365. unsigned DiagID;
  1366. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1367. DiagID = diag::warn_unused_exception_param;
  1368. else if (isa<LabelDecl>(D))
  1369. DiagID = diag::warn_unused_label;
  1370. else
  1371. DiagID = diag::warn_unused_variable;
  1372. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1373. }
  1374. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1375. // Verify that we have no forward references left. If so, there was a goto
  1376. // or address of a label taken, but no definition of it. Label fwd
  1377. // definitions are indicated with a null substmt which is also not a resolved
  1378. // MS inline assembly label name.
  1379. bool Diagnose = false;
  1380. if (L->isMSAsmLabel())
  1381. Diagnose = !L->isResolvedMSAsmLabel();
  1382. else
  1383. Diagnose = L->getStmt() == nullptr;
  1384. if (Diagnose)
  1385. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1386. }
  1387. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1388. S->mergeNRVOIntoParent();
  1389. if (S->decl_empty()) return;
  1390. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1391. "Scope shouldn't contain decls!");
  1392. for (auto *TmpD : S->decls()) {
  1393. assert(TmpD && "This decl didn't get pushed??");
  1394. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1395. NamedDecl *D = cast<NamedDecl>(TmpD);
  1396. if (!D->getDeclName()) continue;
  1397. // Diagnose unused variables in this scope.
  1398. if (!S->hasUnrecoverableErrorOccurred()) {
  1399. DiagnoseUnusedDecl(D);
  1400. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1401. DiagnoseUnusedNestedTypedefs(RD);
  1402. }
  1403. // If this was a forward reference to a label, verify it was defined.
  1404. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1405. CheckPoppedLabel(LD, *this);
  1406. // Remove this name from our lexical scope.
  1407. IdResolver.RemoveDecl(D);
  1408. }
  1409. }
  1410. /// \brief Look for an Objective-C class in the translation unit.
  1411. ///
  1412. /// \param Id The name of the Objective-C class we're looking for. If
  1413. /// typo-correction fixes this name, the Id will be updated
  1414. /// to the fixed name.
  1415. ///
  1416. /// \param IdLoc The location of the name in the translation unit.
  1417. ///
  1418. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1419. /// if there is no class with the given name.
  1420. ///
  1421. /// \returns The declaration of the named Objective-C class, or NULL if the
  1422. /// class could not be found.
  1423. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1424. SourceLocation IdLoc,
  1425. bool DoTypoCorrection) {
  1426. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1427. // creation from this context.
  1428. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1429. if (!IDecl && DoTypoCorrection) {
  1430. // Perform typo correction at the given location, but only if we
  1431. // find an Objective-C class name.
  1432. if (TypoCorrection C = CorrectTypo(
  1433. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1434. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1435. CTK_ErrorRecovery)) {
  1436. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1437. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1438. Id = IDecl->getIdentifier();
  1439. }
  1440. }
  1441. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1442. // This routine must always return a class definition, if any.
  1443. if (Def && Def->getDefinition())
  1444. Def = Def->getDefinition();
  1445. return Def;
  1446. }
  1447. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1448. /// from S, where a non-field would be declared. This routine copes
  1449. /// with the difference between C and C++ scoping rules in structs and
  1450. /// unions. For example, the following code is well-formed in C but
  1451. /// ill-formed in C++:
  1452. /// @code
  1453. /// struct S6 {
  1454. /// enum { BAR } e;
  1455. /// };
  1456. ///
  1457. /// void test_S6() {
  1458. /// struct S6 a;
  1459. /// a.e = BAR;
  1460. /// }
  1461. /// @endcode
  1462. /// For the declaration of BAR, this routine will return a different
  1463. /// scope. The scope S will be the scope of the unnamed enumeration
  1464. /// within S6. In C++, this routine will return the scope associated
  1465. /// with S6, because the enumeration's scope is a transparent
  1466. /// context but structures can contain non-field names. In C, this
  1467. /// routine will return the translation unit scope, since the
  1468. /// enumeration's scope is a transparent context and structures cannot
  1469. /// contain non-field names.
  1470. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1471. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1472. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1473. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1474. S = S->getParent();
  1475. return S;
  1476. }
  1477. /// \brief Looks up the declaration of "struct objc_super" and
  1478. /// saves it for later use in building builtin declaration of
  1479. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1480. /// pre-existing declaration exists no action takes place.
  1481. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1482. IdentifierInfo *II) {
  1483. if (!II->isStr("objc_msgSendSuper"))
  1484. return;
  1485. ASTContext &Context = ThisSema.Context;
  1486. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1487. SourceLocation(), Sema::LookupTagName);
  1488. ThisSema.LookupName(Result, S);
  1489. if (Result.getResultKind() == LookupResult::Found)
  1490. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1491. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1492. }
  1493. static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
  1494. switch (Error) {
  1495. case ASTContext::GE_None:
  1496. return "";
  1497. case ASTContext::GE_Missing_stdio:
  1498. return "stdio.h";
  1499. case ASTContext::GE_Missing_setjmp:
  1500. return "setjmp.h";
  1501. case ASTContext::GE_Missing_ucontext:
  1502. return "ucontext.h";
  1503. }
  1504. llvm_unreachable("unhandled error kind");
  1505. }
  1506. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1507. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1508. /// if we're creating this built-in in anticipation of redeclaring the
  1509. /// built-in.
  1510. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1511. Scope *S, bool ForRedeclaration,
  1512. SourceLocation Loc) {
  1513. LookupPredefedObjCSuperType(*this, S, II);
  1514. ASTContext::GetBuiltinTypeError Error;
  1515. QualType R = Context.GetBuiltinType(ID, Error);
  1516. if (Error) {
  1517. if (ForRedeclaration)
  1518. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1519. << getHeaderName(Error)
  1520. << Context.BuiltinInfo.GetName(ID);
  1521. return nullptr;
  1522. }
  1523. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
  1524. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1525. << Context.BuiltinInfo.GetName(ID)
  1526. << R;
  1527. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1528. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1529. Diag(Loc, diag::note_include_header_or_declare)
  1530. << Context.BuiltinInfo.getHeaderName(ID)
  1531. << Context.BuiltinInfo.GetName(ID);
  1532. }
  1533. DeclContext *Parent = Context.getTranslationUnitDecl();
  1534. if (getLangOpts().CPlusPlus) {
  1535. LinkageSpecDecl *CLinkageDecl =
  1536. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1537. LinkageSpecDecl::lang_c, false);
  1538. CLinkageDecl->setImplicit();
  1539. Parent->addDecl(CLinkageDecl);
  1540. Parent = CLinkageDecl;
  1541. }
  1542. FunctionDecl *New = FunctionDecl::Create(Context,
  1543. Parent,
  1544. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1545. SC_Extern,
  1546. false,
  1547. R->isFunctionProtoType());
  1548. New->setImplicit();
  1549. // Create Decl objects for each parameter, adding them to the
  1550. // FunctionDecl.
  1551. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1552. SmallVector<ParmVarDecl*, 16> Params;
  1553. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1554. ParmVarDecl *parm =
  1555. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1556. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1557. SC_None, nullptr);
  1558. parm->setScopeInfo(0, i);
  1559. Params.push_back(parm);
  1560. }
  1561. New->setParams(Params);
  1562. }
  1563. AddKnownFunctionAttributes(New);
  1564. RegisterLocallyScopedExternCDecl(New, S);
  1565. // TUScope is the translation-unit scope to insert this function into.
  1566. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1567. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1568. // entirely, but we're not there yet.
  1569. DeclContext *SavedContext = CurContext;
  1570. CurContext = Parent;
  1571. PushOnScopeChains(New, TUScope);
  1572. CurContext = SavedContext;
  1573. return New;
  1574. }
  1575. /// \brief Filter out any previous declarations that the given declaration
  1576. /// should not consider because they are not permitted to conflict, e.g.,
  1577. /// because they come from hidden sub-modules and do not refer to the same
  1578. /// entity.
  1579. static void filterNonConflictingPreviousDecls(Sema &S,
  1580. NamedDecl *decl,
  1581. LookupResult &previous){
  1582. // This is only interesting when modules are enabled.
  1583. if ((!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) ||
  1584. !S.getLangOpts().ModulesHideInternalLinkage)
  1585. return;
  1586. // Empty sets are uninteresting.
  1587. if (previous.empty())
  1588. return;
  1589. LookupResult::Filter filter = previous.makeFilter();
  1590. while (filter.hasNext()) {
  1591. NamedDecl *old = filter.next();
  1592. // Non-hidden declarations are never ignored.
  1593. if (S.isVisible(old))
  1594. continue;
  1595. if (!old->isExternallyVisible())
  1596. filter.erase();
  1597. }
  1598. filter.done();
  1599. }
  1600. /// Typedef declarations don't have linkage, but they still denote the same
  1601. /// entity if their types are the same.
  1602. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1603. /// isSameEntity.
  1604. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1605. TypedefNameDecl *Decl,
  1606. LookupResult &Previous) {
  1607. // This is only interesting when modules are enabled.
  1608. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1609. return;
  1610. // Empty sets are uninteresting.
  1611. if (Previous.empty())
  1612. return;
  1613. LookupResult::Filter Filter = Previous.makeFilter();
  1614. while (Filter.hasNext()) {
  1615. NamedDecl *Old = Filter.next();
  1616. // Non-hidden declarations are never ignored.
  1617. if (S.isVisible(Old))
  1618. continue;
  1619. // Declarations of the same entity are not ignored, even if they have
  1620. // different linkages.
  1621. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1622. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1623. Decl->getUnderlyingType()))
  1624. continue;
  1625. // If both declarations give a tag declaration a typedef name for linkage
  1626. // purposes, then they declare the same entity.
  1627. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1628. Decl->getAnonDeclWithTypedefName())
  1629. continue;
  1630. }
  1631. if (!Old->isExternallyVisible())
  1632. Filter.erase();
  1633. }
  1634. Filter.done();
  1635. }
  1636. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1637. QualType OldType;
  1638. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1639. OldType = OldTypedef->getUnderlyingType();
  1640. else
  1641. OldType = Context.getTypeDeclType(Old);
  1642. QualType NewType = New->getUnderlyingType();
  1643. if (NewType->isVariablyModifiedType()) {
  1644. // Must not redefine a typedef with a variably-modified type.
  1645. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1646. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1647. << Kind << NewType;
  1648. if (Old->getLocation().isValid())
  1649. Diag(Old->getLocation(), diag::note_previous_definition);
  1650. New->setInvalidDecl();
  1651. return true;
  1652. }
  1653. if (OldType != NewType &&
  1654. !OldType->isDependentType() &&
  1655. !NewType->isDependentType() &&
  1656. !Context.hasSameType(OldType, NewType)) {
  1657. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1658. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1659. << Kind << NewType << OldType;
  1660. if (Old->getLocation().isValid())
  1661. Diag(Old->getLocation(), diag::note_previous_definition);
  1662. New->setInvalidDecl();
  1663. return true;
  1664. }
  1665. return false;
  1666. }
  1667. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1668. /// same name and scope as a previous declaration 'Old'. Figure out
  1669. /// how to resolve this situation, merging decls or emitting
  1670. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1671. ///
  1672. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1673. // If the new decl is known invalid already, don't bother doing any
  1674. // merging checks.
  1675. if (New->isInvalidDecl()) return;
  1676. // Allow multiple definitions for ObjC built-in typedefs.
  1677. // FIXME: Verify the underlying types are equivalent!
  1678. if (getLangOpts().ObjC1) {
  1679. const IdentifierInfo *TypeID = New->getIdentifier();
  1680. switch (TypeID->getLength()) {
  1681. default: break;
  1682. case 2:
  1683. {
  1684. if (!TypeID->isStr("id"))
  1685. break;
  1686. QualType T = New->getUnderlyingType();
  1687. if (!T->isPointerType())
  1688. break;
  1689. if (!T->isVoidPointerType()) {
  1690. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1691. if (!PT->isStructureType())
  1692. break;
  1693. }
  1694. Context.setObjCIdRedefinitionType(T);
  1695. // Install the built-in type for 'id', ignoring the current definition.
  1696. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1697. return;
  1698. }
  1699. case 5:
  1700. if (!TypeID->isStr("Class"))
  1701. break;
  1702. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1703. // Install the built-in type for 'Class', ignoring the current definition.
  1704. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1705. return;
  1706. case 3:
  1707. if (!TypeID->isStr("SEL"))
  1708. break;
  1709. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1710. // Install the built-in type for 'SEL', ignoring the current definition.
  1711. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1712. return;
  1713. }
  1714. // Fall through - the typedef name was not a builtin type.
  1715. }
  1716. // Verify the old decl was also a type.
  1717. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1718. if (!Old) {
  1719. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1720. << New->getDeclName();
  1721. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1722. if (OldD->getLocation().isValid())
  1723. Diag(OldD->getLocation(), diag::note_previous_definition);
  1724. return New->setInvalidDecl();
  1725. }
  1726. // If the old declaration is invalid, just give up here.
  1727. if (Old->isInvalidDecl())
  1728. return New->setInvalidDecl();
  1729. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1730. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1731. auto *NewTag = New->getAnonDeclWithTypedefName();
  1732. NamedDecl *Hidden = nullptr;
  1733. if (getLangOpts().CPlusPlus && OldTag && NewTag &&
  1734. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1735. !hasVisibleDefinition(OldTag, &Hidden)) {
  1736. // There is a definition of this tag, but it is not visible. Use it
  1737. // instead of our tag.
  1738. New->setTypeForDecl(OldTD->getTypeForDecl());
  1739. if (OldTD->isModed())
  1740. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1741. OldTD->getUnderlyingType());
  1742. else
  1743. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1744. // Make the old tag definition visible.
  1745. makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
  1746. }
  1747. }
  1748. // If the typedef types are not identical, reject them in all languages and
  1749. // with any extensions enabled.
  1750. if (isIncompatibleTypedef(Old, New))
  1751. return;
  1752. // The types match. Link up the redeclaration chain and merge attributes if
  1753. // the old declaration was a typedef.
  1754. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1755. New->setPreviousDecl(Typedef);
  1756. mergeDeclAttributes(New, Old);
  1757. }
  1758. if (getLangOpts().MicrosoftExt)
  1759. return;
  1760. if (getLangOpts().CPlusPlus) {
  1761. // C++ [dcl.typedef]p2:
  1762. // In a given non-class scope, a typedef specifier can be used to
  1763. // redefine the name of any type declared in that scope to refer
  1764. // to the type to which it already refers.
  1765. if (!isa<CXXRecordDecl>(CurContext))
  1766. return;
  1767. // C++0x [dcl.typedef]p4:
  1768. // In a given class scope, a typedef specifier can be used to redefine
  1769. // any class-name declared in that scope that is not also a typedef-name
  1770. // to refer to the type to which it already refers.
  1771. //
  1772. // This wording came in via DR424, which was a correction to the
  1773. // wording in DR56, which accidentally banned code like:
  1774. //
  1775. // struct S {
  1776. // typedef struct A { } A;
  1777. // };
  1778. //
  1779. // in the C++03 standard. We implement the C++0x semantics, which
  1780. // allow the above but disallow
  1781. //
  1782. // struct S {
  1783. // typedef int I;
  1784. // typedef int I;
  1785. // };
  1786. //
  1787. // since that was the intent of DR56.
  1788. if (!isa<TypedefNameDecl>(Old))
  1789. return;
  1790. Diag(New->getLocation(), diag::err_redefinition)
  1791. << New->getDeclName();
  1792. Diag(Old->getLocation(), diag::note_previous_definition);
  1793. return New->setInvalidDecl();
  1794. }
  1795. // Modules always permit redefinition of typedefs, as does C11.
  1796. if (getLangOpts().Modules || getLangOpts().C11)
  1797. return;
  1798. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1799. // is normally mapped to an error, but can be controlled with
  1800. // -Wtypedef-redefinition. If either the original or the redefinition is
  1801. // in a system header, don't emit this for compatibility with GCC.
  1802. if (getDiagnostics().getSuppressSystemWarnings() &&
  1803. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1804. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1805. return;
  1806. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  1807. << New->getDeclName();
  1808. Diag(Old->getLocation(), diag::note_previous_definition);
  1809. }
  1810. /// DeclhasAttr - returns true if decl Declaration already has the target
  1811. /// attribute.
  1812. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  1813. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1814. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1815. for (const auto *i : D->attrs())
  1816. if (i->getKind() == A->getKind()) {
  1817. if (Ann) {
  1818. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  1819. return true;
  1820. continue;
  1821. }
  1822. // FIXME: Don't hardcode this check
  1823. if (OA && isa<OwnershipAttr>(i))
  1824. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  1825. return true;
  1826. }
  1827. return false;
  1828. }
  1829. static bool isAttributeTargetADefinition(Decl *D) {
  1830. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  1831. return VD->isThisDeclarationADefinition();
  1832. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  1833. return TD->isCompleteDefinition() || TD->isBeingDefined();
  1834. return true;
  1835. }
  1836. /// Merge alignment attributes from \p Old to \p New, taking into account the
  1837. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  1838. ///
  1839. /// \return \c true if any attributes were added to \p New.
  1840. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  1841. // Look for alignas attributes on Old, and pick out whichever attribute
  1842. // specifies the strictest alignment requirement.
  1843. AlignedAttr *OldAlignasAttr = nullptr;
  1844. AlignedAttr *OldStrictestAlignAttr = nullptr;
  1845. unsigned OldAlign = 0;
  1846. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  1847. // FIXME: We have no way of representing inherited dependent alignments
  1848. // in a case like:
  1849. // template<int A, int B> struct alignas(A) X;
  1850. // template<int A, int B> struct alignas(B) X {};
  1851. // For now, we just ignore any alignas attributes which are not on the
  1852. // definition in such a case.
  1853. if (I->isAlignmentDependent())
  1854. return false;
  1855. if (I->isAlignas())
  1856. OldAlignasAttr = I;
  1857. unsigned Align = I->getAlignment(S.Context);
  1858. if (Align > OldAlign) {
  1859. OldAlign = Align;
  1860. OldStrictestAlignAttr = I;
  1861. }
  1862. }
  1863. // Look for alignas attributes on New.
  1864. AlignedAttr *NewAlignasAttr = nullptr;
  1865. unsigned NewAlign = 0;
  1866. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  1867. if (I->isAlignmentDependent())
  1868. return false;
  1869. if (I->isAlignas())
  1870. NewAlignasAttr = I;
  1871. unsigned Align = I->getAlignment(S.Context);
  1872. if (Align > NewAlign)
  1873. NewAlign = Align;
  1874. }
  1875. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  1876. // Both declarations have 'alignas' attributes. We require them to match.
  1877. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  1878. // fall short. (If two declarations both have alignas, they must both match
  1879. // every definition, and so must match each other if there is a definition.)
  1880. // If either declaration only contains 'alignas(0)' specifiers, then it
  1881. // specifies the natural alignment for the type.
  1882. if (OldAlign == 0 || NewAlign == 0) {
  1883. QualType Ty;
  1884. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  1885. Ty = VD->getType();
  1886. else
  1887. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  1888. if (OldAlign == 0)
  1889. OldAlign = S.Context.getTypeAlign(Ty);
  1890. if (NewAlign == 0)
  1891. NewAlign = S.Context.getTypeAlign(Ty);
  1892. }
  1893. if (OldAlign != NewAlign) {
  1894. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  1895. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  1896. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  1897. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  1898. }
  1899. }
  1900. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  1901. // C++11 [dcl.align]p6:
  1902. // if any declaration of an entity has an alignment-specifier,
  1903. // every defining declaration of that entity shall specify an
  1904. // equivalent alignment.
  1905. // C11 6.7.5/7:
  1906. // If the definition of an object does not have an alignment
  1907. // specifier, any other declaration of that object shall also
  1908. // have no alignment specifier.
  1909. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  1910. << OldAlignasAttr;
  1911. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  1912. << OldAlignasAttr;
  1913. }
  1914. bool AnyAdded = false;
  1915. // Ensure we have an attribute representing the strictest alignment.
  1916. if (OldAlign > NewAlign) {
  1917. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  1918. Clone->setInherited(true);
  1919. New->addAttr(Clone);
  1920. AnyAdded = true;
  1921. }
  1922. // Ensure we have an alignas attribute if the old declaration had one.
  1923. if (OldAlignasAttr && !NewAlignasAttr &&
  1924. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  1925. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  1926. Clone->setInherited(true);
  1927. New->addAttr(Clone);
  1928. AnyAdded = true;
  1929. }
  1930. return AnyAdded;
  1931. }
  1932. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  1933. const InheritableAttr *Attr, bool Override) {
  1934. InheritableAttr *NewAttr = nullptr;
  1935. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  1936. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  1937. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  1938. AA->getIntroduced(), AA->getDeprecated(),
  1939. AA->getObsoleted(), AA->getUnavailable(),
  1940. AA->getMessage(), Override,
  1941. AttrSpellingListIndex);
  1942. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  1943. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1944. AttrSpellingListIndex);
  1945. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  1946. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1947. AttrSpellingListIndex);
  1948. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  1949. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  1950. AttrSpellingListIndex);
  1951. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  1952. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  1953. AttrSpellingListIndex);
  1954. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  1955. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  1956. FA->getFormatIdx(), FA->getFirstArg(),
  1957. AttrSpellingListIndex);
  1958. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  1959. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  1960. AttrSpellingListIndex);
  1961. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  1962. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  1963. AttrSpellingListIndex,
  1964. IA->getSemanticSpelling());
  1965. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  1966. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  1967. &S.Context.Idents.get(AA->getSpelling()),
  1968. AttrSpellingListIndex);
  1969. else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  1970. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  1971. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  1972. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  1973. else if (isa<AlignedAttr>(Attr))
  1974. // AlignedAttrs are handled separately, because we need to handle all
  1975. // such attributes on a declaration at the same time.
  1976. NewAttr = nullptr;
  1977. else if (isa<DeprecatedAttr>(Attr) && Override)
  1978. NewAttr = nullptr;
  1979. else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
  1980. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  1981. if (NewAttr) {
  1982. NewAttr->setInherited(true);
  1983. D->addAttr(NewAttr);
  1984. return true;
  1985. }
  1986. return false;
  1987. }
  1988. static const Decl *getDefinition(const Decl *D) {
  1989. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  1990. return TD->getDefinition();
  1991. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1992. const VarDecl *Def = VD->getDefinition();
  1993. if (Def)
  1994. return Def;
  1995. return VD->getActingDefinition();
  1996. }
  1997. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1998. const FunctionDecl* Def;
  1999. if (FD->isDefined(Def))
  2000. return Def;
  2001. }
  2002. return nullptr;
  2003. }
  2004. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2005. for (const auto *Attribute : D->attrs())
  2006. if (Attribute->getKind() == Kind)
  2007. return true;
  2008. return false;
  2009. }
  2010. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2011. /// there are no new attributes in this declaration.
  2012. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2013. if (!New->hasAttrs())
  2014. return;
  2015. const Decl *Def = getDefinition(Old);
  2016. if (!Def || Def == New)
  2017. return;
  2018. AttrVec &NewAttributes = New->getAttrs();
  2019. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2020. const Attr *NewAttribute = NewAttributes[I];
  2021. if (isa<AliasAttr>(NewAttribute)) {
  2022. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
  2023. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
  2024. else {
  2025. VarDecl *VD = cast<VarDecl>(New);
  2026. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2027. VarDecl::TentativeDefinition
  2028. ? diag::err_alias_after_tentative
  2029. : diag::err_redefinition;
  2030. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2031. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2032. VD->setInvalidDecl();
  2033. }
  2034. ++I;
  2035. continue;
  2036. }
  2037. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2038. // Tentative definitions are only interesting for the alias check above.
  2039. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2040. ++I;
  2041. continue;
  2042. }
  2043. }
  2044. if (hasAttribute(Def, NewAttribute->getKind())) {
  2045. ++I;
  2046. continue; // regular attr merging will take care of validating this.
  2047. }
  2048. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2049. // C's _Noreturn is allowed to be added to a function after it is defined.
  2050. ++I;
  2051. continue;
  2052. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2053. if (AA->isAlignas()) {
  2054. // C++11 [dcl.align]p6:
  2055. // if any declaration of an entity has an alignment-specifier,
  2056. // every defining declaration of that entity shall specify an
  2057. // equivalent alignment.
  2058. // C11 6.7.5/7:
  2059. // If the definition of an object does not have an alignment
  2060. // specifier, any other declaration of that object shall also
  2061. // have no alignment specifier.
  2062. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2063. << AA;
  2064. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2065. << AA;
  2066. NewAttributes.erase(NewAttributes.begin() + I);
  2067. --E;
  2068. continue;
  2069. }
  2070. }
  2071. S.Diag(NewAttribute->getLocation(),
  2072. diag::warn_attribute_precede_definition);
  2073. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2074. NewAttributes.erase(NewAttributes.begin() + I);
  2075. --E;
  2076. }
  2077. }
  2078. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2079. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2080. AvailabilityMergeKind AMK) {
  2081. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2082. UsedAttr *NewAttr = OldAttr->clone(Context);
  2083. NewAttr->setInherited(true);
  2084. New->addAttr(NewAttr);
  2085. }
  2086. if (!Old->hasAttrs() && !New->hasAttrs())
  2087. return;
  2088. // attributes declared post-definition are currently ignored
  2089. checkNewAttributesAfterDef(*this, New, Old);
  2090. if (!Old->hasAttrs())
  2091. return;
  2092. bool foundAny = New->hasAttrs();
  2093. // Ensure that any moving of objects within the allocated map is done before
  2094. // we process them.
  2095. if (!foundAny) New->setAttrs(AttrVec());
  2096. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2097. bool Override = false;
  2098. // Ignore deprecated/unavailable/availability attributes if requested.
  2099. if (isa<DeprecatedAttr>(I) ||
  2100. isa<UnavailableAttr>(I) ||
  2101. isa<AvailabilityAttr>(I)) {
  2102. switch (AMK) {
  2103. case AMK_None:
  2104. continue;
  2105. case AMK_Redeclaration:
  2106. break;
  2107. case AMK_Override:
  2108. Override = true;
  2109. break;
  2110. }
  2111. }
  2112. // Already handled.
  2113. if (isa<UsedAttr>(I))
  2114. continue;
  2115. if (mergeDeclAttribute(*this, New, I, Override))
  2116. foundAny = true;
  2117. }
  2118. if (mergeAlignedAttrs(*this, New, Old))
  2119. foundAny = true;
  2120. if (!foundAny) New->dropAttrs();
  2121. }
  2122. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2123. /// to the new one.
  2124. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2125. const ParmVarDecl *oldDecl,
  2126. Sema &S) {
  2127. // C++11 [dcl.attr.depend]p2:
  2128. // The first declaration of a function shall specify the
  2129. // carries_dependency attribute for its declarator-id if any declaration
  2130. // of the function specifies the carries_dependency attribute.
  2131. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2132. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2133. S.Diag(CDA->getLocation(),
  2134. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2135. // Find the first declaration of the parameter.
  2136. // FIXME: Should we build redeclaration chains for function parameters?
  2137. const FunctionDecl *FirstFD =
  2138. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2139. const ParmVarDecl *FirstVD =
  2140. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2141. S.Diag(FirstVD->getLocation(),
  2142. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2143. }
  2144. if (!oldDecl->hasAttrs())
  2145. return;
  2146. bool foundAny = newDecl->hasAttrs();
  2147. // Ensure that any moving of objects within the allocated map is
  2148. // done before we process them.
  2149. if (!foundAny) newDecl->setAttrs(AttrVec());
  2150. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2151. if (!DeclHasAttr(newDecl, I)) {
  2152. InheritableAttr *newAttr =
  2153. cast<InheritableParamAttr>(I->clone(S.Context));
  2154. newAttr->setInherited(true);
  2155. newDecl->addAttr(newAttr);
  2156. foundAny = true;
  2157. }
  2158. }
  2159. if (!foundAny) newDecl->dropAttrs();
  2160. }
  2161. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2162. const ParmVarDecl *OldParam,
  2163. Sema &S) {
  2164. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2165. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2166. if (*Oldnullability != *Newnullability) {
  2167. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2168. << DiagNullabilityKind(
  2169. *Newnullability,
  2170. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2171. != 0))
  2172. << DiagNullabilityKind(
  2173. *Oldnullability,
  2174. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2175. != 0));
  2176. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2177. }
  2178. } else {
  2179. QualType NewT = NewParam->getType();
  2180. NewT = S.Context.getAttributedType(
  2181. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2182. NewT, NewT);
  2183. NewParam->setType(NewT);
  2184. }
  2185. }
  2186. }
  2187. namespace {
  2188. /// Used in MergeFunctionDecl to keep track of function parameters in
  2189. /// C.
  2190. struct GNUCompatibleParamWarning {
  2191. ParmVarDecl *OldParm;
  2192. ParmVarDecl *NewParm;
  2193. QualType PromotedType;
  2194. };
  2195. }
  2196. /// getSpecialMember - get the special member enum for a method.
  2197. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2198. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2199. if (Ctor->isDefaultConstructor())
  2200. return Sema::CXXDefaultConstructor;
  2201. if (Ctor->isCopyConstructor())
  2202. return Sema::CXXCopyConstructor;
  2203. if (Ctor->isMoveConstructor())
  2204. return Sema::CXXMoveConstructor;
  2205. } else if (isa<CXXDestructorDecl>(MD)) {
  2206. return Sema::CXXDestructor;
  2207. } else if (MD->isCopyAssignmentOperator()) {
  2208. return Sema::CXXCopyAssignment;
  2209. } else if (MD->isMoveAssignmentOperator()) {
  2210. return Sema::CXXMoveAssignment;
  2211. }
  2212. return Sema::CXXInvalid;
  2213. }
  2214. // Determine whether the previous declaration was a definition, implicit
  2215. // declaration, or a declaration.
  2216. template <typename T>
  2217. static std::pair<diag::kind, SourceLocation>
  2218. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2219. diag::kind PrevDiag;
  2220. SourceLocation OldLocation = Old->getLocation();
  2221. if (Old->isThisDeclarationADefinition())
  2222. PrevDiag = diag::note_previous_definition;
  2223. else if (Old->isImplicit()) {
  2224. PrevDiag = diag::note_previous_implicit_declaration;
  2225. if (OldLocation.isInvalid())
  2226. OldLocation = New->getLocation();
  2227. } else
  2228. PrevDiag = diag::note_previous_declaration;
  2229. return std::make_pair(PrevDiag, OldLocation);
  2230. }
  2231. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2232. /// only extern inline functions can be redefined, and even then only in
  2233. /// GNU89 mode.
  2234. static bool canRedefineFunction(const FunctionDecl *FD,
  2235. const LangOptions& LangOpts) {
  2236. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2237. !LangOpts.CPlusPlus &&
  2238. FD->isInlineSpecified() &&
  2239. FD->getStorageClass() == SC_Extern);
  2240. }
  2241. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2242. const AttributedType *AT = T->getAs<AttributedType>();
  2243. while (AT && !AT->isCallingConv())
  2244. AT = AT->getModifiedType()->getAs<AttributedType>();
  2245. return AT;
  2246. }
  2247. template <typename T>
  2248. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2249. const DeclContext *DC = Old->getDeclContext();
  2250. if (DC->isRecord())
  2251. return false;
  2252. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2253. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2254. return true;
  2255. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2256. return true;
  2257. return false;
  2258. }
  2259. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2260. static bool isExternC(VarTemplateDecl *) { return false; }
  2261. /// \brief Check whether a redeclaration of an entity introduced by a
  2262. /// using-declaration is valid, given that we know it's not an overload
  2263. /// (nor a hidden tag declaration).
  2264. template<typename ExpectedDecl>
  2265. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2266. ExpectedDecl *New) {
  2267. // C++11 [basic.scope.declarative]p4:
  2268. // Given a set of declarations in a single declarative region, each of
  2269. // which specifies the same unqualified name,
  2270. // -- they shall all refer to the same entity, or all refer to functions
  2271. // and function templates; or
  2272. // -- exactly one declaration shall declare a class name or enumeration
  2273. // name that is not a typedef name and the other declarations shall all
  2274. // refer to the same variable or enumerator, or all refer to functions
  2275. // and function templates; in this case the class name or enumeration
  2276. // name is hidden (3.3.10).
  2277. // C++11 [namespace.udecl]p14:
  2278. // If a function declaration in namespace scope or block scope has the
  2279. // same name and the same parameter-type-list as a function introduced
  2280. // by a using-declaration, and the declarations do not declare the same
  2281. // function, the program is ill-formed.
  2282. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2283. if (Old &&
  2284. !Old->getDeclContext()->getRedeclContext()->Equals(
  2285. New->getDeclContext()->getRedeclContext()) &&
  2286. !(isExternC(Old) && isExternC(New)))
  2287. Old = nullptr;
  2288. if (!Old) {
  2289. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2290. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2291. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2292. return true;
  2293. }
  2294. return false;
  2295. }
  2296. /// MergeFunctionDecl - We just parsed a function 'New' from
  2297. /// declarator D which has the same name and scope as a previous
  2298. /// declaration 'Old'. Figure out how to resolve this situation,
  2299. /// merging decls or emitting diagnostics as appropriate.
  2300. ///
  2301. /// In C++, New and Old must be declarations that are not
  2302. /// overloaded. Use IsOverload to determine whether New and Old are
  2303. /// overloaded, and to select the Old declaration that New should be
  2304. /// merged with.
  2305. ///
  2306. /// Returns true if there was an error, false otherwise.
  2307. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2308. Scope *S, bool MergeTypeWithOld) {
  2309. // Verify the old decl was also a function.
  2310. FunctionDecl *Old = OldD->getAsFunction();
  2311. if (!Old) {
  2312. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2313. if (New->getFriendObjectKind()) {
  2314. Diag(New->getLocation(), diag::err_using_decl_friend);
  2315. Diag(Shadow->getTargetDecl()->getLocation(),
  2316. diag::note_using_decl_target);
  2317. Diag(Shadow->getUsingDecl()->getLocation(),
  2318. diag::note_using_decl) << 0;
  2319. return true;
  2320. }
  2321. // Check whether the two declarations might declare the same function.
  2322. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2323. return true;
  2324. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2325. } else {
  2326. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2327. << New->getDeclName();
  2328. Diag(OldD->getLocation(), diag::note_previous_definition);
  2329. return true;
  2330. }
  2331. }
  2332. // If the old declaration is invalid, just give up here.
  2333. if (Old->isInvalidDecl())
  2334. return true;
  2335. diag::kind PrevDiag;
  2336. SourceLocation OldLocation;
  2337. std::tie(PrevDiag, OldLocation) =
  2338. getNoteDiagForInvalidRedeclaration(Old, New);
  2339. // Don't complain about this if we're in GNU89 mode and the old function
  2340. // is an extern inline function.
  2341. // Don't complain about specializations. They are not supposed to have
  2342. // storage classes.
  2343. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2344. New->getStorageClass() == SC_Static &&
  2345. Old->hasExternalFormalLinkage() &&
  2346. !New->getTemplateSpecializationInfo() &&
  2347. !canRedefineFunction(Old, getLangOpts())) {
  2348. if (getLangOpts().MicrosoftExt) {
  2349. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2350. Diag(OldLocation, PrevDiag);
  2351. } else {
  2352. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2353. Diag(OldLocation, PrevDiag);
  2354. return true;
  2355. }
  2356. }
  2357. // If a function is first declared with a calling convention, but is later
  2358. // declared or defined without one, all following decls assume the calling
  2359. // convention of the first.
  2360. //
  2361. // It's OK if a function is first declared without a calling convention,
  2362. // but is later declared or defined with the default calling convention.
  2363. //
  2364. // To test if either decl has an explicit calling convention, we look for
  2365. // AttributedType sugar nodes on the type as written. If they are missing or
  2366. // were canonicalized away, we assume the calling convention was implicit.
  2367. //
  2368. // Note also that we DO NOT return at this point, because we still have
  2369. // other tests to run.
  2370. QualType OldQType = Context.getCanonicalType(Old->getType());
  2371. QualType NewQType = Context.getCanonicalType(New->getType());
  2372. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2373. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2374. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2375. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2376. bool RequiresAdjustment = false;
  2377. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2378. FunctionDecl *First = Old->getFirstDecl();
  2379. const FunctionType *FT =
  2380. First->getType().getCanonicalType()->castAs<FunctionType>();
  2381. FunctionType::ExtInfo FI = FT->getExtInfo();
  2382. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2383. if (!NewCCExplicit) {
  2384. // Inherit the CC from the previous declaration if it was specified
  2385. // there but not here.
  2386. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2387. RequiresAdjustment = true;
  2388. } else {
  2389. // Calling conventions aren't compatible, so complain.
  2390. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2391. Diag(New->getLocation(), diag::err_cconv_change)
  2392. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2393. << !FirstCCExplicit
  2394. << (!FirstCCExplicit ? "" :
  2395. FunctionType::getNameForCallConv(FI.getCC()));
  2396. // Put the note on the first decl, since it is the one that matters.
  2397. Diag(First->getLocation(), diag::note_previous_declaration);
  2398. return true;
  2399. }
  2400. }
  2401. // FIXME: diagnose the other way around?
  2402. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2403. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2404. RequiresAdjustment = true;
  2405. }
  2406. // Merge regparm attribute.
  2407. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2408. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2409. if (NewTypeInfo.getHasRegParm()) {
  2410. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2411. << NewType->getRegParmType()
  2412. << OldType->getRegParmType();
  2413. Diag(OldLocation, diag::note_previous_declaration);
  2414. return true;
  2415. }
  2416. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2417. RequiresAdjustment = true;
  2418. }
  2419. // Merge ns_returns_retained attribute.
  2420. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2421. if (NewTypeInfo.getProducesResult()) {
  2422. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  2423. Diag(OldLocation, diag::note_previous_declaration);
  2424. return true;
  2425. }
  2426. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2427. RequiresAdjustment = true;
  2428. }
  2429. if (RequiresAdjustment) {
  2430. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2431. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2432. New->setType(QualType(AdjustedType, 0));
  2433. NewQType = Context.getCanonicalType(New->getType());
  2434. NewType = cast<FunctionType>(NewQType);
  2435. }
  2436. // If this redeclaration makes the function inline, we may need to add it to
  2437. // UndefinedButUsed.
  2438. if (!Old->isInlined() && New->isInlined() &&
  2439. !New->hasAttr<GNUInlineAttr>() &&
  2440. !getLangOpts().GNUInline &&
  2441. Old->isUsed(false) &&
  2442. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2443. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2444. SourceLocation()));
  2445. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2446. // about it.
  2447. if (New->hasAttr<GNUInlineAttr>() &&
  2448. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2449. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2450. }
  2451. if (getLangOpts().CPlusPlus) {
  2452. // (C++98 13.1p2):
  2453. // Certain function declarations cannot be overloaded:
  2454. // -- Function declarations that differ only in the return type
  2455. // cannot be overloaded.
  2456. // Go back to the type source info to compare the declared return types,
  2457. // per C++1y [dcl.type.auto]p13:
  2458. // Redeclarations or specializations of a function or function template
  2459. // with a declared return type that uses a placeholder type shall also
  2460. // use that placeholder, not a deduced type.
  2461. QualType OldDeclaredReturnType =
  2462. (Old->getTypeSourceInfo()
  2463. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2464. : OldType)->getReturnType();
  2465. QualType NewDeclaredReturnType =
  2466. (New->getTypeSourceInfo()
  2467. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2468. : NewType)->getReturnType();
  2469. QualType ResQT;
  2470. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2471. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2472. New->isLocalExternDecl())) {
  2473. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2474. OldDeclaredReturnType->isObjCObjectPointerType())
  2475. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2476. if (ResQT.isNull()) {
  2477. if (New->isCXXClassMember() && New->isOutOfLine())
  2478. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2479. << New << New->getReturnTypeSourceRange();
  2480. else
  2481. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2482. << New->getReturnTypeSourceRange();
  2483. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2484. << Old->getReturnTypeSourceRange();
  2485. return true;
  2486. }
  2487. else
  2488. NewQType = ResQT;
  2489. }
  2490. QualType OldReturnType = OldType->getReturnType();
  2491. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2492. if (OldReturnType != NewReturnType) {
  2493. // If this function has a deduced return type and has already been
  2494. // defined, copy the deduced value from the old declaration.
  2495. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2496. if (OldAT && OldAT->isDeduced()) {
  2497. New->setType(
  2498. SubstAutoType(New->getType(),
  2499. OldAT->isDependentType() ? Context.DependentTy
  2500. : OldAT->getDeducedType()));
  2501. NewQType = Context.getCanonicalType(
  2502. SubstAutoType(NewQType,
  2503. OldAT->isDependentType() ? Context.DependentTy
  2504. : OldAT->getDeducedType()));
  2505. }
  2506. }
  2507. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2508. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2509. if (OldMethod && NewMethod) {
  2510. // Preserve triviality.
  2511. NewMethod->setTrivial(OldMethod->isTrivial());
  2512. // MSVC allows explicit template specialization at class scope:
  2513. // 2 CXXMethodDecls referring to the same function will be injected.
  2514. // We don't want a redeclaration error.
  2515. bool IsClassScopeExplicitSpecialization =
  2516. OldMethod->isFunctionTemplateSpecialization() &&
  2517. NewMethod->isFunctionTemplateSpecialization();
  2518. bool isFriend = NewMethod->getFriendObjectKind();
  2519. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2520. !IsClassScopeExplicitSpecialization) {
  2521. // -- Member function declarations with the same name and the
  2522. // same parameter types cannot be overloaded if any of them
  2523. // is a static member function declaration.
  2524. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2525. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2526. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2527. return true;
  2528. }
  2529. // C++ [class.mem]p1:
  2530. // [...] A member shall not be declared twice in the
  2531. // member-specification, except that a nested class or member
  2532. // class template can be declared and then later defined.
  2533. if (ActiveTemplateInstantiations.empty()) {
  2534. unsigned NewDiag;
  2535. if (isa<CXXConstructorDecl>(OldMethod))
  2536. NewDiag = diag::err_constructor_redeclared;
  2537. else if (isa<CXXDestructorDecl>(NewMethod))
  2538. NewDiag = diag::err_destructor_redeclared;
  2539. else if (isa<CXXConversionDecl>(NewMethod))
  2540. NewDiag = diag::err_conv_function_redeclared;
  2541. else
  2542. NewDiag = diag::err_member_redeclared;
  2543. Diag(New->getLocation(), NewDiag);
  2544. } else {
  2545. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2546. << New << New->getType();
  2547. }
  2548. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2549. return true;
  2550. // Complain if this is an explicit declaration of a special
  2551. // member that was initially declared implicitly.
  2552. //
  2553. // As an exception, it's okay to befriend such methods in order
  2554. // to permit the implicit constructor/destructor/operator calls.
  2555. } else if (OldMethod->isImplicit()) {
  2556. if (isFriend) {
  2557. NewMethod->setImplicit();
  2558. } else {
  2559. Diag(NewMethod->getLocation(),
  2560. diag::err_definition_of_implicitly_declared_member)
  2561. << New << getSpecialMember(OldMethod);
  2562. return true;
  2563. }
  2564. } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
  2565. Diag(NewMethod->getLocation(),
  2566. diag::err_definition_of_explicitly_defaulted_member)
  2567. << getSpecialMember(OldMethod);
  2568. return true;
  2569. }
  2570. }
  2571. // C++11 [dcl.attr.noreturn]p1:
  2572. // The first declaration of a function shall specify the noreturn
  2573. // attribute if any declaration of that function specifies the noreturn
  2574. // attribute.
  2575. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2576. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2577. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2578. Diag(Old->getFirstDecl()->getLocation(),
  2579. diag::note_noreturn_missing_first_decl);
  2580. }
  2581. // C++11 [dcl.attr.depend]p2:
  2582. // The first declaration of a function shall specify the
  2583. // carries_dependency attribute for its declarator-id if any declaration
  2584. // of the function specifies the carries_dependency attribute.
  2585. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2586. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2587. Diag(CDA->getLocation(),
  2588. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2589. Diag(Old->getFirstDecl()->getLocation(),
  2590. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2591. }
  2592. // (C++98 8.3.5p3):
  2593. // All declarations for a function shall agree exactly in both the
  2594. // return type and the parameter-type-list.
  2595. // We also want to respect all the extended bits except noreturn.
  2596. // noreturn should now match unless the old type info didn't have it.
  2597. QualType OldQTypeForComparison = OldQType;
  2598. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2599. assert(OldQType == QualType(OldType, 0));
  2600. const FunctionType *OldTypeForComparison
  2601. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2602. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2603. assert(OldQTypeForComparison.isCanonical());
  2604. }
  2605. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2606. // As a special case, retain the language linkage from previous
  2607. // declarations of a friend function as an extension.
  2608. //
  2609. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  2610. // and is useful because there's otherwise no way to specify language
  2611. // linkage within class scope.
  2612. //
  2613. // Check cautiously as the friend object kind isn't yet complete.
  2614. if (New->getFriendObjectKind() != Decl::FOK_None) {
  2615. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  2616. Diag(OldLocation, PrevDiag);
  2617. } else {
  2618. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2619. Diag(OldLocation, PrevDiag);
  2620. return true;
  2621. }
  2622. }
  2623. if (OldQTypeForComparison == NewQType)
  2624. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2625. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2626. New->isLocalExternDecl()) {
  2627. // It's OK if we couldn't merge types for a local function declaraton
  2628. // if either the old or new type is dependent. We'll merge the types
  2629. // when we instantiate the function.
  2630. return false;
  2631. }
  2632. // Fall through for conflicting redeclarations and redefinitions.
  2633. }
  2634. // C: Function types need to be compatible, not identical. This handles
  2635. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2636. if (!getLangOpts().CPlusPlus &&
  2637. Context.typesAreCompatible(OldQType, NewQType)) {
  2638. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2639. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2640. const FunctionProtoType *OldProto = nullptr;
  2641. #if 1 // HLSL Change Starts - commenting this out rather than fixing for inout semantics - N/A for HLSL
  2642. assert(!(MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2643. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) &&
  2644. "else fn with no prototype found");
  2645. (void)OldFuncType;
  2646. (void)NewFuncType;
  2647. (void)OldProto;
  2648. #else
  2649. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2650. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2651. // The old declaration provided a function prototype, but the
  2652. // new declaration does not. Merge in the prototype.
  2653. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2654. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  2655. NewQType =
  2656. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  2657. OldProto->getExtProtoInfo());
  2658. New->setType(NewQType);
  2659. New->setHasInheritedPrototype();
  2660. // Synthesize parameters with the same types.
  2661. SmallVector<ParmVarDecl*, 16> Params;
  2662. for (const auto &ParamType : OldProto->param_types()) {
  2663. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  2664. SourceLocation(), nullptr,
  2665. ParamType, /*TInfo=*/nullptr,
  2666. SC_None, nullptr);
  2667. Param->setScopeInfo(0, Params.size());
  2668. Param->setImplicit();
  2669. Params.push_back(Param);
  2670. }
  2671. New->setParams(Params);
  2672. }
  2673. #endif // HLSL Change Ends
  2674. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2675. }
  2676. #if 0 // HLSL Change Starts - commenting this out rather than fixing for inout semantics - N/A for HLSL
  2677. // GNU C permits a K&R definition to follow a prototype declaration
  2678. // if the declared types of the parameters in the K&R definition
  2679. // match the types in the prototype declaration, even when the
  2680. // promoted types of the parameters from the K&R definition differ
  2681. // from the types in the prototype. GCC then keeps the types from
  2682. // the prototype.
  2683. //
  2684. // If a variadic prototype is followed by a non-variadic K&R definition,
  2685. // the K&R definition becomes variadic. This is sort of an edge case, but
  2686. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2687. // C99 6.9.1p8.
  2688. if (!getLangOpts().CPlusPlus &&
  2689. Old->hasPrototype() && !New->hasPrototype() &&
  2690. New->getType()->getAs<FunctionProtoType>() &&
  2691. Old->getNumParams() == New->getNumParams()) {
  2692. SmallVector<QualType, 16> ArgTypes;
  2693. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2694. const FunctionProtoType *OldProto
  2695. = Old->getType()->getAs<FunctionProtoType>();
  2696. const FunctionProtoType *NewProto
  2697. = New->getType()->getAs<FunctionProtoType>();
  2698. // Determine whether this is the GNU C extension.
  2699. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  2700. NewProto->getReturnType());
  2701. bool LooseCompatible = !MergedReturn.isNull();
  2702. for (unsigned Idx = 0, End = Old->getNumParams();
  2703. LooseCompatible && Idx != End; ++Idx) {
  2704. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2705. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2706. if (Context.typesAreCompatible(OldParm->getType(),
  2707. NewProto->getParamType(Idx))) {
  2708. ArgTypes.push_back(NewParm->getType());
  2709. } else if (Context.typesAreCompatible(OldParm->getType(),
  2710. NewParm->getType(),
  2711. /*CompareUnqualified=*/true)) {
  2712. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  2713. NewProto->getParamType(Idx) };
  2714. Warnings.push_back(Warn);
  2715. ArgTypes.push_back(NewParm->getType());
  2716. } else
  2717. LooseCompatible = false;
  2718. }
  2719. if (LooseCompatible) {
  2720. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2721. Diag(Warnings[Warn].NewParm->getLocation(),
  2722. diag::ext_param_promoted_not_compatible_with_prototype)
  2723. << Warnings[Warn].PromotedType
  2724. << Warnings[Warn].OldParm->getType();
  2725. if (Warnings[Warn].OldParm->getLocation().isValid())
  2726. Diag(Warnings[Warn].OldParm->getLocation(),
  2727. diag::note_previous_declaration);
  2728. }
  2729. if (MergeTypeWithOld)
  2730. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  2731. OldProto->getExtProtoInfo()));
  2732. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2733. }
  2734. // Fall through to diagnose conflicting types.
  2735. }
  2736. #endif // HLSL Change Ends
  2737. // A function that has already been declared has been redeclared or
  2738. // defined with a different type; show an appropriate diagnostic.
  2739. // If the previous declaration was an implicitly-generated builtin
  2740. // declaration, then at the very least we should use a specialized note.
  2741. unsigned BuiltinID;
  2742. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  2743. // If it's actually a library-defined builtin function like 'malloc'
  2744. // or 'printf', just warn about the incompatible redeclaration.
  2745. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2746. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2747. Diag(OldLocation, diag::note_previous_builtin_declaration)
  2748. << Old << Old->getType();
  2749. // If this is a global redeclaration, just forget hereafter
  2750. // about the "builtin-ness" of the function.
  2751. //
  2752. // Doing this for local extern declarations is problematic. If
  2753. // the builtin declaration remains visible, a second invalid
  2754. // local declaration will produce a hard error; if it doesn't
  2755. // remain visible, a single bogus local redeclaration (which is
  2756. // actually only a warning) could break all the downstream code.
  2757. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  2758. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  2759. return false;
  2760. }
  2761. PrevDiag = diag::note_previous_builtin_declaration;
  2762. }
  2763. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2764. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2765. return true;
  2766. }
  2767. /// \brief Completes the merge of two function declarations that are
  2768. /// known to be compatible.
  2769. ///
  2770. /// This routine handles the merging of attributes and other
  2771. /// properties of function declarations from the old declaration to
  2772. /// the new declaration, once we know that New is in fact a
  2773. /// redeclaration of Old.
  2774. ///
  2775. /// \returns false
  2776. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2777. Scope *S, bool MergeTypeWithOld) {
  2778. // Merge the attributes
  2779. mergeDeclAttributes(New, Old);
  2780. // Merge "pure" flag.
  2781. if (Old->isPure())
  2782. New->setPure();
  2783. // Merge "used" flag.
  2784. if (Old->getMostRecentDecl()->isUsed(false))
  2785. New->setIsUsed();
  2786. // Merge attributes from the parameters. These can mismatch with K&R
  2787. // declarations.
  2788. if (New->getNumParams() == Old->getNumParams())
  2789. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  2790. ParmVarDecl *NewParam = New->getParamDecl(i);
  2791. ParmVarDecl *OldParam = Old->getParamDecl(i);
  2792. mergeParamDeclAttributes(NewParam, OldParam, *this);
  2793. mergeParamDeclTypes(NewParam, OldParam, *this);
  2794. }
  2795. if (getLangOpts().CPlusPlus)
  2796. return MergeCXXFunctionDecl(New, Old, S);
  2797. // Merge the function types so the we get the composite types for the return
  2798. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  2799. // was visible.
  2800. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  2801. if (!Merged.isNull() && MergeTypeWithOld)
  2802. New->setType(Merged);
  2803. return false;
  2804. }
  2805. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2806. ObjCMethodDecl *oldMethod) {
  2807. // Merge the attributes, including deprecated/unavailable
  2808. AvailabilityMergeKind MergeKind =
  2809. isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  2810. : AMK_Override;
  2811. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  2812. // Merge attributes from the parameters.
  2813. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2814. oe = oldMethod->param_end();
  2815. for (ObjCMethodDecl::param_iterator
  2816. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2817. ni != ne && oi != oe; ++ni, ++oi)
  2818. mergeParamDeclAttributes(*ni, *oi, *this);
  2819. CheckObjCMethodOverride(newMethod, oldMethod);
  2820. }
  2821. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2822. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2823. /// emitting diagnostics as appropriate.
  2824. ///
  2825. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2826. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2827. /// is attached.
  2828. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  2829. bool MergeTypeWithOld, ShadowMergeState& MergeState) { // HLSL Change - add merge state
  2830. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2831. return;
  2832. QualType MergedT;
  2833. if (getLangOpts().CPlusPlus) {
  2834. if (New->getType()->isUndeducedType()) {
  2835. // We don't know what the new type is until the initializer is attached.
  2836. return;
  2837. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2838. // These could still be something that needs exception specs checked.
  2839. return MergeVarDeclExceptionSpecs(New, Old);
  2840. }
  2841. // C++ [basic.link]p10:
  2842. // [...] the types specified by all declarations referring to a given
  2843. // object or function shall be identical, except that declarations for an
  2844. // array object can specify array types that differ by the presence or
  2845. // absence of a major array bound (8.3.4).
  2846. else if (Old->getType()->isIncompleteArrayType() &&
  2847. New->getType()->isArrayType()) {
  2848. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2849. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2850. if (Context.hasSameType(OldArray->getElementType(),
  2851. NewArray->getElementType()))
  2852. MergedT = New->getType();
  2853. } else if (Old->getType()->isArrayType() &&
  2854. New->getType()->isIncompleteArrayType()) {
  2855. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2856. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2857. if (Context.hasSameType(OldArray->getElementType(),
  2858. NewArray->getElementType()))
  2859. MergedT = Old->getType();
  2860. } else if (New->getType()->isObjCObjectPointerType() &&
  2861. Old->getType()->isObjCObjectPointerType()) {
  2862. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  2863. Old->getType());
  2864. }
  2865. } else {
  2866. // C 6.2.7p2:
  2867. // All declarations that refer to the same object or function shall have
  2868. // compatible type.
  2869. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  2870. }
  2871. if (MergedT.isNull()) {
  2872. // It's OK if we couldn't merge types if either type is dependent, for a
  2873. // block-scope variable. In other cases (static data members of class
  2874. // templates, variable templates, ...), we require the types to be
  2875. // equivalent.
  2876. // FIXME: The C++ standard doesn't say anything about this.
  2877. if ((New->getType()->isDependentType() ||
  2878. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  2879. // If the old type was dependent, we can't merge with it, so the new type
  2880. // becomes dependent for now. We'll reproduce the original type when we
  2881. // instantiate the TypeSourceInfo for the variable.
  2882. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  2883. New->setType(Context.DependentTy);
  2884. return;
  2885. }
  2886. // FIXME: Even if this merging succeeds, some other non-visible declaration
  2887. // of this variable might have an incompatible type. For instance:
  2888. //
  2889. // extern int arr[];
  2890. // void f() { extern int arr[2]; }
  2891. // void g() { extern int arr[3]; }
  2892. //
  2893. // Neither C nor C++ requires a diagnostic for this, but we should still try
  2894. // to diagnose it.
  2895. // HLSL Change Starts
  2896. if (MergeState == ShadowMergeState_Disallowed) {
  2897. Diag(New->getLocation(), New->isThisDeclarationADefinition()
  2898. ? diag::err_redefinition_different_type
  2899. : diag::err_redeclaration_different_type)
  2900. << New->getDeclName() << New->getType() << Old->getType();
  2901. diag::kind PrevDiag;
  2902. SourceLocation OldLocation;
  2903. std::tie(PrevDiag, OldLocation) =
  2904. getNoteDiagForInvalidRedeclaration(Old, New);
  2905. Diag(OldLocation, PrevDiag);
  2906. return New->setInvalidDecl();
  2907. }
  2908. else if (MergeState == ShadowMergeState_Possible) {
  2909. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition_different_type)
  2910. << New->getDeclName() << New->getType() << Old->getType();
  2911. Diag(Old->getLocation(), diag::note_previous_definition);
  2912. MergeState = ShadowMergeState_Effective;
  2913. MergeTypeWithOld = false;
  2914. }
  2915. // HLSL Change Ends
  2916. }
  2917. // Don't actually update the type on the new declaration if the old
  2918. // declaration was an extern declaration in a different scope.
  2919. if (MergeTypeWithOld)
  2920. New->setType(MergedT);
  2921. }
  2922. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  2923. LookupResult &Previous) {
  2924. // C11 6.2.7p4:
  2925. // For an identifier with internal or external linkage declared
  2926. // in a scope in which a prior declaration of that identifier is
  2927. // visible, if the prior declaration specifies internal or
  2928. // external linkage, the type of the identifier at the later
  2929. // declaration becomes the composite type.
  2930. //
  2931. // If the variable isn't visible, we do not merge with its type.
  2932. if (Previous.isShadowed())
  2933. return false;
  2934. if (S.getLangOpts().CPlusPlus) {
  2935. // C++11 [dcl.array]p3:
  2936. // If there is a preceding declaration of the entity in the same
  2937. // scope in which the bound was specified, an omitted array bound
  2938. // is taken to be the same as in that earlier declaration.
  2939. return NewVD->isPreviousDeclInSameBlockScope() ||
  2940. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  2941. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  2942. } else {
  2943. // If the old declaration was function-local, don't merge with its
  2944. // type unless we're in the same function.
  2945. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  2946. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  2947. }
  2948. }
  2949. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  2950. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  2951. /// situation, merging decls or emitting diagnostics as appropriate.
  2952. ///
  2953. /// Tentative definition rules (C99 6.9.2p2) are checked by
  2954. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  2955. /// definitions here, since the initializer hasn't been attached.
  2956. ///
  2957. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous, ShadowMergeState& MergeState) { // HLSL Change - add merge state
  2958. // If the new decl is already invalid, don't do any other checking.
  2959. if (New->isInvalidDecl())
  2960. return;
  2961. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  2962. // Verify the old decl was also a variable or variable template.
  2963. VarDecl *Old = nullptr;
  2964. VarTemplateDecl *OldTemplate = nullptr;
  2965. if (Previous.isSingleResult()) {
  2966. if (NewTemplate) {
  2967. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  2968. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  2969. if (auto *Shadow =
  2970. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  2971. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  2972. return New->setInvalidDecl();
  2973. } else {
  2974. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  2975. if (auto *Shadow =
  2976. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  2977. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  2978. return New->setInvalidDecl();
  2979. }
  2980. }
  2981. if (!Old) {
  2982. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2983. << New->getDeclName();
  2984. Diag(Previous.getRepresentativeDecl()->getLocation(),
  2985. diag::note_previous_definition);
  2986. return New->setInvalidDecl();
  2987. }
  2988. if (!shouldLinkPossiblyHiddenDecl(Old, New))
  2989. return;
  2990. // Ensure the template parameters are compatible.
  2991. if (NewTemplate &&
  2992. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  2993. OldTemplate->getTemplateParameters(),
  2994. /*Complain=*/true, TPL_TemplateMatch))
  2995. return;
  2996. // C++ [class.mem]p1:
  2997. // A member shall not be declared twice in the member-specification [...]
  2998. //
  2999. // Here, we need only consider static data members.
  3000. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3001. Diag(New->getLocation(), diag::err_duplicate_member)
  3002. << New->getIdentifier();
  3003. Diag(Old->getLocation(), diag::note_previous_declaration);
  3004. New->setInvalidDecl();
  3005. }
  3006. mergeDeclAttributes(New, Old);
  3007. // Warn if an already-declared variable is made a weak_import in a subsequent
  3008. // declaration
  3009. if (New->hasAttr<WeakImportAttr>() &&
  3010. Old->getStorageClass() == SC_None &&
  3011. !Old->hasAttr<WeakImportAttr>()) {
  3012. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3013. Diag(Old->getLocation(), diag::note_previous_definition);
  3014. // Remove weak_import attribute on new declaration.
  3015. New->dropAttr<WeakImportAttr>();
  3016. }
  3017. // Merge the types.
  3018. VarDecl *MostRecent = Old->getMostRecentDecl();
  3019. if (MostRecent != Old) {
  3020. MergeVarDeclTypes(New, MostRecent,
  3021. mergeTypeWithPrevious(*this, New, MostRecent, Previous), MergeState); // HLSL Change - add MergeState
  3022. if (New->isInvalidDecl())
  3023. return;
  3024. }
  3025. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous), MergeState); // HLSL Change - add MergeState
  3026. if (New->isInvalidDecl())
  3027. return;
  3028. diag::kind PrevDiag;
  3029. SourceLocation OldLocation;
  3030. std::tie(PrevDiag, OldLocation) =
  3031. getNoteDiagForInvalidRedeclaration(Old, New);
  3032. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3033. if (New->getStorageClass() == SC_Static &&
  3034. !New->isStaticDataMember() &&
  3035. Old->hasExternalFormalLinkage()) {
  3036. if (getLangOpts().MicrosoftExt) {
  3037. Diag(New->getLocation(), diag::ext_static_non_static)
  3038. << New->getDeclName();
  3039. Diag(OldLocation, PrevDiag);
  3040. } else {
  3041. Diag(New->getLocation(), diag::err_static_non_static)
  3042. << New->getDeclName();
  3043. Diag(OldLocation, PrevDiag);
  3044. return New->setInvalidDecl();
  3045. }
  3046. }
  3047. // C99 6.2.2p4:
  3048. // For an identifier declared with the storage-class specifier
  3049. // extern in a scope in which a prior declaration of that
  3050. // identifier is visible,23) if the prior declaration specifies
  3051. // internal or external linkage, the linkage of the identifier at
  3052. // the later declaration is the same as the linkage specified at
  3053. // the prior declaration. If no prior declaration is visible, or
  3054. // if the prior declaration specifies no linkage, then the
  3055. // identifier has external linkage.
  3056. if (New->hasExternalStorage() && Old->hasLinkage())
  3057. /* Okay */;
  3058. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3059. !New->isStaticDataMember() &&
  3060. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3061. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3062. Diag(OldLocation, PrevDiag);
  3063. return New->setInvalidDecl();
  3064. }
  3065. // Check if extern is followed by non-extern and vice-versa.
  3066. if (New->hasExternalStorage() &&
  3067. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3068. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3069. Diag(OldLocation, PrevDiag);
  3070. return New->setInvalidDecl();
  3071. }
  3072. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3073. !New->hasExternalStorage()) {
  3074. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3075. Diag(OldLocation, PrevDiag);
  3076. return New->setInvalidDecl();
  3077. }
  3078. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3079. // FIXME: The test for external storage here seems wrong? We still
  3080. // need to check for mismatches.
  3081. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3082. // Don't complain about out-of-line definitions of static members.
  3083. !(Old->getLexicalDeclContext()->isRecord() &&
  3084. !New->getLexicalDeclContext()->isRecord())) {
  3085. // HLSL Change Starts
  3086. if (MergeState == ShadowMergeState_Disallowed) {
  3087. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3088. Diag(OldLocation, PrevDiag);
  3089. return New->setInvalidDecl();
  3090. } else if (MergeState == ShadowMergeState_Possible) {
  3091. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition)
  3092. << New->getDeclName();
  3093. Diag(Old->getLocation(), diag::note_previous_definition);
  3094. MergeState = ShadowMergeState_Effective;
  3095. }
  3096. // HLSL Change Ends
  3097. }
  3098. if (New->getTLSKind() != Old->getTLSKind()) {
  3099. if (!Old->getTLSKind()) {
  3100. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3101. Diag(OldLocation, PrevDiag);
  3102. } else if (!New->getTLSKind()) {
  3103. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3104. Diag(OldLocation, PrevDiag);
  3105. } else {
  3106. // Do not allow redeclaration to change the variable between requiring
  3107. // static and dynamic initialization.
  3108. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3109. // declaration to determine the kind. Do we need to be compatible here?
  3110. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3111. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3112. Diag(OldLocation, PrevDiag);
  3113. }
  3114. }
  3115. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3116. VarDecl *Def;
  3117. if (getLangOpts().CPlusPlus &&
  3118. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  3119. (Def = Old->getDefinition())) {
  3120. NamedDecl *Hidden = nullptr;
  3121. if (!hasVisibleDefinition(Def, &Hidden) &&
  3122. (New->getFormalLinkage() == InternalLinkage ||
  3123. New->getDescribedVarTemplate() ||
  3124. New->getNumTemplateParameterLists() ||
  3125. New->getDeclContext()->isDependentContext())) {
  3126. // The previous definition is hidden, and multiple definitions are
  3127. // permitted (in separate TUs). Form another definition of it.
  3128. } else {
  3129. // HLSL Change Starts
  3130. if (MergeState == ShadowMergeState_Disallowed) {
  3131. Diag(New->getLocation(), diag::err_redefinition) << New;
  3132. Diag(Def->getLocation(), diag::note_previous_definition);
  3133. New->setInvalidDecl();
  3134. return;
  3135. }
  3136. else if (MergeState == ShadowMergeState_Possible) {
  3137. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition) << New->getDeclName();
  3138. Diag(Old->getLocation(), diag::note_previous_definition);
  3139. MergeState = ShadowMergeState_Effective;
  3140. }
  3141. // HLSL Change Ends
  3142. }
  3143. }
  3144. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3145. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3146. Diag(OldLocation, PrevDiag);
  3147. New->setInvalidDecl();
  3148. return;
  3149. }
  3150. if (MergeState != ShadowMergeState_Effective) { // HLSL Change - avoid merging when shadowing
  3151. // Merge "used" flag.
  3152. if (Old->getMostRecentDecl()->isUsed(false))
  3153. New->setIsUsed();
  3154. // Keep a chain of previous declarations.
  3155. New->setPreviousDecl(Old);
  3156. if (NewTemplate)
  3157. NewTemplate->setPreviousDecl(OldTemplate);
  3158. // Inherit access appropriately.
  3159. New->setAccess(Old->getAccess());
  3160. if (NewTemplate)
  3161. NewTemplate->setAccess(New->getAccess());
  3162. } // HLSL Change - close block conditional on shadow merge state
  3163. }
  3164. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3165. /// no declarator (e.g. "struct foo;") is parsed.
  3166. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  3167. DeclSpec &DS) {
  3168. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
  3169. }
  3170. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3171. // disambiguate entities defined in different scopes.
  3172. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3173. // compatibility.
  3174. // We will pick our mangling number depending on which version of MSVC is being
  3175. // targeted.
  3176. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3177. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3178. ? S->getMSCurManglingNumber()
  3179. : S->getMSLastManglingNumber();
  3180. }
  3181. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3182. if (!Context.getLangOpts().CPlusPlus)
  3183. return;
  3184. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3185. // If this tag is the direct child of a class, number it if
  3186. // it is anonymous.
  3187. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3188. return;
  3189. MangleNumberingContext &MCtx =
  3190. Context.getManglingNumberContext(Tag->getParent());
  3191. Context.setManglingNumber(
  3192. Tag, MCtx.getManglingNumber(
  3193. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3194. return;
  3195. }
  3196. // If this tag isn't a direct child of a class, number it if it is local.
  3197. Decl *ManglingContextDecl;
  3198. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3199. Tag->getDeclContext(), ManglingContextDecl)) {
  3200. Context.setManglingNumber(
  3201. Tag, MCtx->getManglingNumber(
  3202. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3203. }
  3204. }
  3205. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3206. TypedefNameDecl *NewTD) {
  3207. // Do nothing if the tag is not anonymous or already has an
  3208. // associated typedef (from an earlier typedef in this decl group).
  3209. if (TagFromDeclSpec->getIdentifier())
  3210. return;
  3211. if (TagFromDeclSpec->getTypedefNameForAnonDecl())
  3212. return;
  3213. // A well-formed anonymous tag must always be a TUK_Definition.
  3214. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3215. // The type must match the tag exactly; no qualifiers allowed.
  3216. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3217. Context.getTagDeclType(TagFromDeclSpec)))
  3218. return;
  3219. // If we've already computed linkage for the anonymous tag, then
  3220. // adding a typedef name for the anonymous decl can change that
  3221. // linkage, which might be a serious problem. Diagnose this as
  3222. // unsupported and ignore the typedef name. TODO: we should
  3223. // pursue this as a language defect and establish a formal rule
  3224. // for how to handle it.
  3225. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3226. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3227. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3228. tagLoc = getLocForEndOfToken(tagLoc);
  3229. llvm::SmallString<40> textToInsert;
  3230. textToInsert += ' ';
  3231. textToInsert += NewTD->getIdentifier()->getName();
  3232. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3233. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3234. return;
  3235. }
  3236. // Otherwise, set this is the anon-decl typedef for the tag.
  3237. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3238. }
  3239. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3240. switch (T) {
  3241. case DeclSpec::TST_class:
  3242. return 0;
  3243. case DeclSpec::TST_struct:
  3244. return 1;
  3245. case DeclSpec::TST_interface:
  3246. return 2;
  3247. case DeclSpec::TST_union:
  3248. return 3;
  3249. case DeclSpec::TST_enum:
  3250. return 4;
  3251. default:
  3252. llvm_unreachable("unexpected type specifier");
  3253. }
  3254. }
  3255. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3256. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3257. /// parameters to cope with template friend declarations.
  3258. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  3259. DeclSpec &DS,
  3260. MultiTemplateParamsArg TemplateParams,
  3261. bool IsExplicitInstantiation) {
  3262. Decl *TagD = nullptr;
  3263. TagDecl *Tag = nullptr;
  3264. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3265. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3266. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3267. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3268. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3269. TagD = DS.getRepAsDecl();
  3270. if (!TagD) // We probably had an error
  3271. return nullptr;
  3272. // Note that the above type specs guarantee that the
  3273. // type rep is a Decl, whereas in many of the others
  3274. // it's a Type.
  3275. if (isa<TagDecl>(TagD))
  3276. Tag = cast<TagDecl>(TagD);
  3277. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3278. Tag = CTD->getTemplatedDecl();
  3279. }
  3280. if (Tag) {
  3281. handleTagNumbering(Tag, S);
  3282. Tag->setFreeStanding();
  3283. if (Tag->isInvalidDecl())
  3284. return Tag;
  3285. }
  3286. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3287. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3288. // or incomplete types shall not be restrict-qualified."
  3289. if (TypeQuals & DeclSpec::TQ_restrict)
  3290. Diag(DS.getRestrictSpecLoc(),
  3291. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3292. << DS.getSourceRange();
  3293. }
  3294. if (DS.isConstexprSpecified()) {
  3295. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3296. // and definitions of functions and variables.
  3297. if (Tag)
  3298. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3299. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3300. else
  3301. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3302. // Don't emit warnings after this error.
  3303. return TagD;
  3304. }
  3305. DiagnoseFunctionSpecifiers(DS);
  3306. if (DS.isFriendSpecified()) {
  3307. // If we're dealing with a decl but not a TagDecl, assume that
  3308. // whatever routines created it handled the friendship aspect.
  3309. if (TagD && !Tag)
  3310. return nullptr;
  3311. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3312. }
  3313. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3314. bool IsExplicitSpecialization =
  3315. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3316. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3317. !IsExplicitInstantiation && !IsExplicitSpecialization) {
  3318. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3319. // nested-name-specifier unless it is an explicit instantiation
  3320. // or an explicit specialization.
  3321. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3322. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3323. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3324. return nullptr;
  3325. }
  3326. // Track whether this decl-specifier declares anything.
  3327. bool DeclaresAnything = true;
  3328. // Handle anonymous struct definitions.
  3329. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3330. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3331. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3332. if (getLangOpts().CPlusPlus ||
  3333. Record->getDeclContext()->isRecord())
  3334. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3335. Context.getPrintingPolicy());
  3336. DeclaresAnything = false;
  3337. }
  3338. }
  3339. // C11 6.7.2.1p2:
  3340. // A struct-declaration that does not declare an anonymous structure or
  3341. // anonymous union shall contain a struct-declarator-list.
  3342. //
  3343. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3344. // did not permit a struct-declaration without a struct-declarator-list.
  3345. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3346. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3347. // Check for Microsoft C extension: anonymous struct/union member.
  3348. // Handle 2 kinds of anonymous struct/union:
  3349. // struct STRUCT;
  3350. // union UNION;
  3351. // and
  3352. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3353. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3354. if ((Tag && Tag->getDeclName()) ||
  3355. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3356. RecordDecl *Record = nullptr;
  3357. if (Tag)
  3358. Record = dyn_cast<RecordDecl>(Tag);
  3359. else if (const RecordType *RT =
  3360. DS.getRepAsType().get()->getAsStructureType())
  3361. Record = RT->getDecl();
  3362. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3363. Record = UT->getDecl();
  3364. if (Record && getLangOpts().MicrosoftExt) {
  3365. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3366. << Record->isUnion() << DS.getSourceRange();
  3367. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3368. }
  3369. DeclaresAnything = false;
  3370. }
  3371. }
  3372. // Skip all the checks below if we have a type error.
  3373. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3374. (TagD && TagD->isInvalidDecl()))
  3375. return TagD;
  3376. if (getLangOpts().CPlusPlus &&
  3377. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3378. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3379. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3380. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3381. DeclaresAnything = false;
  3382. if (!DS.isMissingDeclaratorOk()) {
  3383. // Customize diagnostic for a typedef missing a name.
  3384. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3385. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3386. << DS.getSourceRange();
  3387. else
  3388. DeclaresAnything = false;
  3389. }
  3390. if (DS.isModulePrivateSpecified() &&
  3391. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3392. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3393. << Tag->getTagKind()
  3394. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3395. ActOnDocumentableDecl(TagD);
  3396. // C 6.7/2:
  3397. // A declaration [...] shall declare at least a declarator [...], a tag,
  3398. // or the members of an enumeration.
  3399. // C++ [dcl.dcl]p3:
  3400. // [If there are no declarators], and except for the declaration of an
  3401. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3402. // names into the program, or shall redeclare a name introduced by a
  3403. // previous declaration.
  3404. if (!DeclaresAnything) {
  3405. // In C, we allow this as a (popular) extension / bug. Don't bother
  3406. // producing further diagnostics for redundant qualifiers after this.
  3407. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3408. return TagD;
  3409. }
  3410. // C++ [dcl.stc]p1:
  3411. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3412. // init-declarator-list of the declaration shall not be empty.
  3413. // C++ [dcl.fct.spec]p1:
  3414. // If a cv-qualifier appears in a decl-specifier-seq, the
  3415. // init-declarator-list of the declaration shall not be empty.
  3416. //
  3417. // Spurious qualifiers here appear to be valid in C.
  3418. unsigned DiagID = diag::warn_standalone_specifier;
  3419. if (getLangOpts().CPlusPlus)
  3420. DiagID = diag::ext_standalone_specifier;
  3421. // Note that a linkage-specification sets a storage class, but
  3422. // 'extern "C" struct foo;' is actually valid and not theoretically
  3423. // useless.
  3424. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3425. if (SCS == DeclSpec::SCS_mutable)
  3426. // Since mutable is not a viable storage class specifier in C, there is
  3427. // no reason to treat it as an extension. Instead, diagnose as an error.
  3428. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3429. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3430. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3431. << DeclSpec::getSpecifierName(SCS);
  3432. }
  3433. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3434. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3435. << DeclSpec::getSpecifierName(TSCS);
  3436. if (DS.getTypeQualifiers()) {
  3437. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3438. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3439. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3440. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3441. // Restrict is covered above.
  3442. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3443. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3444. }
  3445. // Warn about ignored type attributes, for example:
  3446. // __attribute__((aligned)) struct A;
  3447. // Attributes should be placed after tag to apply to type declaration.
  3448. if (!DS.getAttributes().empty()) {
  3449. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3450. if (TypeSpecType == DeclSpec::TST_class ||
  3451. TypeSpecType == DeclSpec::TST_struct ||
  3452. TypeSpecType == DeclSpec::TST_interface ||
  3453. TypeSpecType == DeclSpec::TST_union ||
  3454. TypeSpecType == DeclSpec::TST_enum) {
  3455. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3456. attrs = attrs->getNext())
  3457. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3458. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3459. }
  3460. }
  3461. return TagD;
  3462. }
  3463. /// We are trying to inject an anonymous member into the given scope;
  3464. /// check if there's an existing declaration that can't be overloaded.
  3465. ///
  3466. /// \return true if this is a forbidden redeclaration
  3467. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3468. Scope *S,
  3469. DeclContext *Owner,
  3470. DeclarationName Name,
  3471. SourceLocation NameLoc,
  3472. unsigned diagnostic) {
  3473. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3474. Sema::ForRedeclaration);
  3475. if (!SemaRef.LookupName(R, S)) return false;
  3476. if (R.getAsSingle<TagDecl>())
  3477. return false;
  3478. // Pick a representative declaration.
  3479. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3480. assert(PrevDecl && "Expected a non-null Decl");
  3481. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3482. return false;
  3483. SemaRef.Diag(NameLoc, diagnostic) << Name;
  3484. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3485. return true;
  3486. }
  3487. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3488. /// anonymous struct or union AnonRecord into the owning context Owner
  3489. /// and scope S. This routine will be invoked just after we realize
  3490. /// that an unnamed union or struct is actually an anonymous union or
  3491. /// struct, e.g.,
  3492. ///
  3493. /// @code
  3494. /// union {
  3495. /// int i;
  3496. /// float f;
  3497. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3498. /// // f into the surrounding scope.x
  3499. /// @endcode
  3500. ///
  3501. /// This routine is recursive, injecting the names of nested anonymous
  3502. /// structs/unions into the owning context and scope as well.
  3503. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  3504. DeclContext *Owner,
  3505. RecordDecl *AnonRecord,
  3506. AccessSpecifier AS,
  3507. SmallVectorImpl<NamedDecl *> &Chaining,
  3508. bool MSAnonStruct) {
  3509. unsigned diagKind
  3510. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  3511. : diag::err_anonymous_struct_member_redecl;
  3512. bool Invalid = false;
  3513. // Look every FieldDecl and IndirectFieldDecl with a name.
  3514. for (auto *D : AnonRecord->decls()) {
  3515. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3516. cast<NamedDecl>(D)->getDeclName()) {
  3517. ValueDecl *VD = cast<ValueDecl>(D);
  3518. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3519. VD->getLocation(), diagKind)) {
  3520. // C++ [class.union]p2:
  3521. // The names of the members of an anonymous union shall be
  3522. // distinct from the names of any other entity in the
  3523. // scope in which the anonymous union is declared.
  3524. Invalid = true;
  3525. } else {
  3526. // C++ [class.union]p2:
  3527. // For the purpose of name lookup, after the anonymous union
  3528. // definition, the members of the anonymous union are
  3529. // considered to have been defined in the scope in which the
  3530. // anonymous union is declared.
  3531. unsigned OldChainingSize = Chaining.size();
  3532. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3533. Chaining.append(IF->chain_begin(), IF->chain_end());
  3534. else
  3535. Chaining.push_back(VD);
  3536. assert(Chaining.size() >= 2);
  3537. NamedDecl **NamedChain =
  3538. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3539. for (unsigned i = 0; i < Chaining.size(); i++)
  3540. NamedChain[i] = Chaining[i];
  3541. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  3542. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  3543. VD->getType(), NamedChain, Chaining.size());
  3544. for (const auto *Attr : VD->attrs())
  3545. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  3546. IndirectField->setAccess(AS);
  3547. IndirectField->setImplicit();
  3548. SemaRef.PushOnScopeChains(IndirectField, S);
  3549. // That includes picking up the appropriate access specifier.
  3550. if (AS != AS_none) IndirectField->setAccess(AS);
  3551. Chaining.resize(OldChainingSize);
  3552. }
  3553. }
  3554. }
  3555. return Invalid;
  3556. }
  3557. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  3558. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  3559. /// illegal input values are mapped to SC_None.
  3560. static StorageClass
  3561. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  3562. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  3563. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  3564. "Parser allowed 'typedef' as storage class VarDecl.");
  3565. switch (StorageClassSpec) {
  3566. case DeclSpec::SCS_unspecified: return SC_None;
  3567. case DeclSpec::SCS_extern:
  3568. if (DS.isExternInLinkageSpec())
  3569. return SC_None;
  3570. return SC_Extern;
  3571. case DeclSpec::SCS_static: return SC_Static;
  3572. case DeclSpec::SCS_auto: return SC_Auto;
  3573. case DeclSpec::SCS_register: return SC_Register;
  3574. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  3575. // Illegal SCSs map to None: error reporting is up to the caller.
  3576. case DeclSpec::SCS_mutable: // Fall through.
  3577. case DeclSpec::SCS_typedef: return SC_None;
  3578. }
  3579. llvm_unreachable("unknown storage class specifier");
  3580. }
  3581. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  3582. assert(Record->hasInClassInitializer());
  3583. for (const auto *I : Record->decls()) {
  3584. const auto *FD = dyn_cast<FieldDecl>(I);
  3585. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  3586. FD = IFD->getAnonField();
  3587. if (FD && FD->hasInClassInitializer())
  3588. return FD->getLocation();
  3589. }
  3590. llvm_unreachable("couldn't find in-class initializer");
  3591. }
  3592. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3593. SourceLocation DefaultInitLoc) {
  3594. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3595. return;
  3596. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  3597. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  3598. }
  3599. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3600. CXXRecordDecl *AnonUnion) {
  3601. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3602. return;
  3603. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  3604. }
  3605. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  3606. /// anonymous structure or union. Anonymous unions are a C++ feature
  3607. /// (C++ [class.union]) and a C11 feature; anonymous structures
  3608. /// are a C11 feature and GNU C++ extension.
  3609. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  3610. AccessSpecifier AS,
  3611. RecordDecl *Record,
  3612. const PrintingPolicy &Policy) {
  3613. DeclContext *Owner = Record->getDeclContext();
  3614. // Diagnose whether this anonymous struct/union is an extension.
  3615. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  3616. Diag(Record->getLocation(), diag::ext_anonymous_union);
  3617. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  3618. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  3619. else if (!Record->isUnion() && !getLangOpts().C11)
  3620. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  3621. // C and C++ require different kinds of checks for anonymous
  3622. // structs/unions.
  3623. bool Invalid = false;
  3624. if (getLangOpts().CPlusPlus) {
  3625. const char *PrevSpec = nullptr;
  3626. unsigned DiagID;
  3627. if (Record->isUnion()) {
  3628. // C++ [class.union]p6:
  3629. // Anonymous unions declared in a named namespace or in the
  3630. // global namespace shall be declared static.
  3631. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  3632. (isa<TranslationUnitDecl>(Owner) ||
  3633. (isa<NamespaceDecl>(Owner) &&
  3634. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  3635. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  3636. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  3637. // Recover by adding 'static'.
  3638. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  3639. PrevSpec, DiagID, Policy);
  3640. }
  3641. // C++ [class.union]p6:
  3642. // A storage class is not allowed in a declaration of an
  3643. // anonymous union in a class scope.
  3644. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  3645. isa<RecordDecl>(Owner)) {
  3646. Diag(DS.getStorageClassSpecLoc(),
  3647. diag::err_anonymous_union_with_storage_spec)
  3648. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  3649. // Recover by removing the storage specifier.
  3650. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  3651. SourceLocation(),
  3652. PrevSpec, DiagID, Context.getPrintingPolicy());
  3653. }
  3654. }
  3655. // Ignore const/volatile/restrict qualifiers.
  3656. if (DS.getTypeQualifiers()) {
  3657. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3658. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  3659. << Record->isUnion() << "const"
  3660. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  3661. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3662. Diag(DS.getVolatileSpecLoc(),
  3663. diag::ext_anonymous_struct_union_qualified)
  3664. << Record->isUnion() << "volatile"
  3665. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  3666. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  3667. Diag(DS.getRestrictSpecLoc(),
  3668. diag::ext_anonymous_struct_union_qualified)
  3669. << Record->isUnion() << "restrict"
  3670. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  3671. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3672. Diag(DS.getAtomicSpecLoc(),
  3673. diag::ext_anonymous_struct_union_qualified)
  3674. << Record->isUnion() << "_Atomic"
  3675. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  3676. DS.ClearTypeQualifiers();
  3677. }
  3678. // C++ [class.union]p2:
  3679. // The member-specification of an anonymous union shall only
  3680. // define non-static data members. [Note: nested types and
  3681. // functions cannot be declared within an anonymous union. ]
  3682. for (auto *Mem : Record->decls()) {
  3683. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  3684. // C++ [class.union]p3:
  3685. // An anonymous union shall not have private or protected
  3686. // members (clause 11).
  3687. assert(FD->getAccess() != AS_none);
  3688. if (FD->getAccess() != AS_public) {
  3689. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  3690. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  3691. Invalid = true;
  3692. }
  3693. // C++ [class.union]p1
  3694. // An object of a class with a non-trivial constructor, a non-trivial
  3695. // copy constructor, a non-trivial destructor, or a non-trivial copy
  3696. // assignment operator cannot be a member of a union, nor can an
  3697. // array of such objects.
  3698. if (CheckNontrivialField(FD))
  3699. Invalid = true;
  3700. } else if (Mem->isImplicit()) {
  3701. // Any implicit members are fine.
  3702. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  3703. // This is a type that showed up in an
  3704. // elaborated-type-specifier inside the anonymous struct or
  3705. // union, but which actually declares a type outside of the
  3706. // anonymous struct or union. It's okay.
  3707. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  3708. if (!MemRecord->isAnonymousStructOrUnion() &&
  3709. MemRecord->getDeclName()) {
  3710. // Visual C++ allows type definition in anonymous struct or union.
  3711. if (getLangOpts().MicrosoftExt)
  3712. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  3713. << (int)Record->isUnion();
  3714. else {
  3715. // This is a nested type declaration.
  3716. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  3717. << (int)Record->isUnion();
  3718. Invalid = true;
  3719. }
  3720. } else {
  3721. // This is an anonymous type definition within another anonymous type.
  3722. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  3723. // not part of standard C++.
  3724. Diag(MemRecord->getLocation(),
  3725. diag::ext_anonymous_record_with_anonymous_type)
  3726. << (int)Record->isUnion();
  3727. }
  3728. } else if (isa<AccessSpecDecl>(Mem)) {
  3729. // Any access specifier is fine.
  3730. } else if (isa<StaticAssertDecl>(Mem)) {
  3731. // In C++1z, static_assert declarations are also fine.
  3732. } else {
  3733. // We have something that isn't a non-static data
  3734. // member. Complain about it.
  3735. unsigned DK = diag::err_anonymous_record_bad_member;
  3736. if (isa<TypeDecl>(Mem))
  3737. DK = diag::err_anonymous_record_with_type;
  3738. else if (isa<FunctionDecl>(Mem))
  3739. DK = diag::err_anonymous_record_with_function;
  3740. else if (isa<VarDecl>(Mem))
  3741. DK = diag::err_anonymous_record_with_static;
  3742. // Visual C++ allows type definition in anonymous struct or union.
  3743. if (getLangOpts().MicrosoftExt &&
  3744. DK == diag::err_anonymous_record_with_type)
  3745. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  3746. << (int)Record->isUnion();
  3747. else {
  3748. Diag(Mem->getLocation(), DK)
  3749. << (int)Record->isUnion();
  3750. Invalid = true;
  3751. }
  3752. }
  3753. }
  3754. // C++11 [class.union]p8 (DR1460):
  3755. // At most one variant member of a union may have a
  3756. // brace-or-equal-initializer.
  3757. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  3758. Owner->isRecord())
  3759. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  3760. cast<CXXRecordDecl>(Record));
  3761. }
  3762. if (!Record->isUnion() && !Owner->isRecord()) {
  3763. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  3764. << (int)getLangOpts().CPlusPlus;
  3765. Invalid = true;
  3766. }
  3767. // Mock up a declarator.
  3768. Declarator Dc(DS, Declarator::MemberContext);
  3769. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3770. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  3771. // Create a declaration for this anonymous struct/union.
  3772. NamedDecl *Anon = nullptr;
  3773. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  3774. Anon = FieldDecl::Create(Context, OwningClass,
  3775. DS.getLocStart(),
  3776. Record->getLocation(),
  3777. /*IdentifierInfo=*/nullptr,
  3778. Context.getTypeDeclType(Record),
  3779. TInfo,
  3780. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3781. /*InitStyle=*/ICIS_NoInit);
  3782. Anon->setAccess(AS);
  3783. if (getLangOpts().CPlusPlus)
  3784. FieldCollector->Add(cast<FieldDecl>(Anon));
  3785. } else {
  3786. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  3787. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  3788. if (SCSpec == DeclSpec::SCS_mutable) {
  3789. // mutable can only appear on non-static class members, so it's always
  3790. // an error here
  3791. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  3792. Invalid = true;
  3793. SC = SC_None;
  3794. }
  3795. Anon = VarDecl::Create(Context, Owner,
  3796. DS.getLocStart(),
  3797. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  3798. Context.getTypeDeclType(Record),
  3799. TInfo, SC);
  3800. // Default-initialize the implicit variable. This initialization will be
  3801. // trivial in almost all cases, except if a union member has an in-class
  3802. // initializer:
  3803. // union { int n = 0; };
  3804. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  3805. }
  3806. Anon->setImplicit();
  3807. // Mark this as an anonymous struct/union type.
  3808. Record->setAnonymousStructOrUnion(true);
  3809. // Add the anonymous struct/union object to the current
  3810. // context. We'll be referencing this object when we refer to one of
  3811. // its members.
  3812. Owner->addDecl(Anon);
  3813. // Inject the members of the anonymous struct/union into the owning
  3814. // context and into the identifier resolver chain for name lookup
  3815. // purposes.
  3816. SmallVector<NamedDecl*, 2> Chain;
  3817. Chain.push_back(Anon);
  3818. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  3819. Chain, false))
  3820. Invalid = true;
  3821. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  3822. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  3823. Decl *ManglingContextDecl;
  3824. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3825. NewVD->getDeclContext(), ManglingContextDecl)) {
  3826. Context.setManglingNumber(
  3827. NewVD, MCtx->getManglingNumber(
  3828. NewVD, getMSManglingNumber(getLangOpts(), S)));
  3829. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  3830. }
  3831. }
  3832. }
  3833. if (Invalid)
  3834. Anon->setInvalidDecl();
  3835. return Anon;
  3836. }
  3837. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  3838. /// Microsoft C anonymous structure.
  3839. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  3840. /// Example:
  3841. ///
  3842. /// struct A { int a; };
  3843. /// struct B { struct A; int b; };
  3844. ///
  3845. /// void foo() {
  3846. /// B var;
  3847. /// var.a = 3;
  3848. /// }
  3849. ///
  3850. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  3851. RecordDecl *Record) {
  3852. assert(Record && "expected a record!");
  3853. // Mock up a declarator.
  3854. Declarator Dc(DS, Declarator::TypeNameContext);
  3855. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3856. assert(TInfo && "couldn't build declarator info for anonymous struct");
  3857. auto *ParentDecl = cast<RecordDecl>(CurContext);
  3858. QualType RecTy = Context.getTypeDeclType(Record);
  3859. // Create a declaration for this anonymous struct.
  3860. NamedDecl *Anon = FieldDecl::Create(Context,
  3861. ParentDecl,
  3862. DS.getLocStart(),
  3863. DS.getLocStart(),
  3864. /*IdentifierInfo=*/nullptr,
  3865. RecTy,
  3866. TInfo,
  3867. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3868. /*InitStyle=*/ICIS_NoInit);
  3869. Anon->setImplicit();
  3870. // Add the anonymous struct object to the current context.
  3871. CurContext->addDecl(Anon);
  3872. // Inject the members of the anonymous struct into the current
  3873. // context and into the identifier resolver chain for name lookup
  3874. // purposes.
  3875. SmallVector<NamedDecl*, 2> Chain;
  3876. Chain.push_back(Anon);
  3877. RecordDecl *RecordDef = Record->getDefinition();
  3878. if (RequireCompleteType(Anon->getLocation(), RecTy,
  3879. diag::err_field_incomplete) ||
  3880. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  3881. AS_none, Chain, true)) {
  3882. Anon->setInvalidDecl();
  3883. ParentDecl->setInvalidDecl();
  3884. }
  3885. return Anon;
  3886. }
  3887. /// GetNameForDeclarator - Determine the full declaration name for the
  3888. /// given Declarator.
  3889. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  3890. return GetNameFromUnqualifiedId(D.getName());
  3891. }
  3892. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  3893. DeclarationNameInfo
  3894. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  3895. DeclarationNameInfo NameInfo;
  3896. NameInfo.setLoc(Name.StartLocation);
  3897. switch (Name.getKind()) {
  3898. case UnqualifiedId::IK_ImplicitSelfParam:
  3899. case UnqualifiedId::IK_Identifier:
  3900. NameInfo.setName(Name.Identifier);
  3901. NameInfo.setLoc(Name.StartLocation);
  3902. return NameInfo;
  3903. case UnqualifiedId::IK_OperatorFunctionId:
  3904. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  3905. Name.OperatorFunctionId.Operator));
  3906. NameInfo.setLoc(Name.StartLocation);
  3907. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  3908. = Name.OperatorFunctionId.SymbolLocations[0];
  3909. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  3910. = Name.EndLocation.getRawEncoding();
  3911. return NameInfo;
  3912. case UnqualifiedId::IK_LiteralOperatorId:
  3913. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  3914. Name.Identifier));
  3915. NameInfo.setLoc(Name.StartLocation);
  3916. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  3917. return NameInfo;
  3918. case UnqualifiedId::IK_ConversionFunctionId: {
  3919. TypeSourceInfo *TInfo;
  3920. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  3921. if (Ty.isNull())
  3922. return DeclarationNameInfo();
  3923. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  3924. Context.getCanonicalType(Ty)));
  3925. NameInfo.setLoc(Name.StartLocation);
  3926. NameInfo.setNamedTypeInfo(TInfo);
  3927. return NameInfo;
  3928. }
  3929. case UnqualifiedId::IK_ConstructorName: {
  3930. TypeSourceInfo *TInfo;
  3931. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  3932. if (Ty.isNull())
  3933. return DeclarationNameInfo();
  3934. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3935. Context.getCanonicalType(Ty)));
  3936. NameInfo.setLoc(Name.StartLocation);
  3937. NameInfo.setNamedTypeInfo(TInfo);
  3938. return NameInfo;
  3939. }
  3940. case UnqualifiedId::IK_ConstructorTemplateId: {
  3941. // In well-formed code, we can only have a constructor
  3942. // template-id that refers to the current context, so go there
  3943. // to find the actual type being constructed.
  3944. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  3945. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  3946. return DeclarationNameInfo();
  3947. // Determine the type of the class being constructed.
  3948. QualType CurClassType = Context.getTypeDeclType(CurClass);
  3949. // FIXME: Check two things: that the template-id names the same type as
  3950. // CurClassType, and that the template-id does not occur when the name
  3951. // was qualified.
  3952. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3953. Context.getCanonicalType(CurClassType)));
  3954. NameInfo.setLoc(Name.StartLocation);
  3955. // FIXME: should we retrieve TypeSourceInfo?
  3956. NameInfo.setNamedTypeInfo(nullptr);
  3957. return NameInfo;
  3958. }
  3959. case UnqualifiedId::IK_DestructorName: {
  3960. TypeSourceInfo *TInfo;
  3961. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  3962. if (Ty.isNull())
  3963. return DeclarationNameInfo();
  3964. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  3965. Context.getCanonicalType(Ty)));
  3966. NameInfo.setLoc(Name.StartLocation);
  3967. NameInfo.setNamedTypeInfo(TInfo);
  3968. return NameInfo;
  3969. }
  3970. case UnqualifiedId::IK_TemplateId: {
  3971. TemplateName TName = Name.TemplateId->Template.get();
  3972. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  3973. return Context.getNameForTemplate(TName, TNameLoc);
  3974. }
  3975. } // switch (Name.getKind())
  3976. llvm_unreachable("Unknown name kind");
  3977. }
  3978. static QualType getCoreType(QualType Ty) {
  3979. do {
  3980. if (Ty->isPointerType() || Ty->isReferenceType())
  3981. Ty = Ty->getPointeeType();
  3982. else if (Ty->isArrayType())
  3983. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  3984. else
  3985. return Ty.withoutLocalFastQualifiers();
  3986. } while (true);
  3987. }
  3988. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  3989. /// and Definition have "nearly" matching parameters. This heuristic is
  3990. /// used to improve diagnostics in the case where an out-of-line function
  3991. /// definition doesn't match any declaration within the class or namespace.
  3992. /// Also sets Params to the list of indices to the parameters that differ
  3993. /// between the declaration and the definition. If hasSimilarParameters
  3994. /// returns true and Params is empty, then all of the parameters match.
  3995. static bool hasSimilarParameters(ASTContext &Context,
  3996. FunctionDecl *Declaration,
  3997. FunctionDecl *Definition,
  3998. SmallVectorImpl<unsigned> &Params) {
  3999. Params.clear();
  4000. if (Declaration->param_size() != Definition->param_size())
  4001. return false;
  4002. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4003. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4004. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4005. // The parameter types are identical
  4006. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4007. continue;
  4008. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4009. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4010. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4011. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4012. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4013. (DeclTyName && DeclTyName == DefTyName))
  4014. Params.push_back(Idx);
  4015. else // The two parameters aren't even close
  4016. return false;
  4017. }
  4018. return true;
  4019. }
  4020. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4021. /// declarator needs to be rebuilt in the current instantiation.
  4022. /// Any bits of declarator which appear before the name are valid for
  4023. /// consideration here. That's specifically the type in the decl spec
  4024. /// and the base type in any member-pointer chunks.
  4025. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4026. DeclarationName Name) {
  4027. // The types we specifically need to rebuild are:
  4028. // - typenames, typeofs, and decltypes
  4029. // - types which will become injected class names
  4030. // Of course, we also need to rebuild any type referencing such a
  4031. // type. It's safest to just say "dependent", but we call out a
  4032. // few cases here.
  4033. DeclSpec &DS = D.getMutableDeclSpec();
  4034. switch (DS.getTypeSpecType()) {
  4035. case DeclSpec::TST_typename:
  4036. case DeclSpec::TST_typeofType:
  4037. case DeclSpec::TST_underlyingType:
  4038. case DeclSpec::TST_atomic: {
  4039. // Grab the type from the parser.
  4040. TypeSourceInfo *TSI = nullptr;
  4041. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4042. if (T.isNull() || !T->isDependentType()) break;
  4043. // Make sure there's a type source info. This isn't really much
  4044. // of a waste; most dependent types should have type source info
  4045. // attached already.
  4046. if (!TSI)
  4047. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4048. // Rebuild the type in the current instantiation.
  4049. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4050. if (!TSI) return true;
  4051. // Store the new type back in the decl spec.
  4052. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4053. DS.UpdateTypeRep(LocType);
  4054. break;
  4055. }
  4056. case DeclSpec::TST_decltype:
  4057. case DeclSpec::TST_typeofExpr: {
  4058. Expr *E = DS.getRepAsExpr();
  4059. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4060. if (Result.isInvalid()) return true;
  4061. DS.UpdateExprRep(Result.get());
  4062. break;
  4063. }
  4064. default:
  4065. // Nothing to do for these decl specs.
  4066. break;
  4067. }
  4068. // It doesn't matter what order we do this in.
  4069. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4070. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4071. // The only type information in the declarator which can come
  4072. // before the declaration name is the base type of a member
  4073. // pointer.
  4074. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4075. continue;
  4076. // Rebuild the scope specifier in-place.
  4077. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4078. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4079. return true;
  4080. }
  4081. return false;
  4082. }
  4083. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4084. D.setFunctionDefinitionKind(FDK_Declaration);
  4085. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4086. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4087. Dcl && Dcl->getDeclContext()->isFileContext())
  4088. Dcl->setTopLevelDeclInObjCContainer();
  4089. return Dcl;
  4090. }
  4091. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4092. /// If T is the name of a class, then each of the following shall have a
  4093. /// name different from T:
  4094. /// - every static data member of class T;
  4095. /// - every member function of class T
  4096. /// - every member of class T that is itself a type;
  4097. /// \returns true if the declaration name violates these rules.
  4098. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4099. DeclarationNameInfo NameInfo) {
  4100. DeclarationName Name = NameInfo.getName();
  4101. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  4102. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  4103. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4104. return true;
  4105. }
  4106. return false;
  4107. }
  4108. /// \brief Diagnose a declaration whose declarator-id has the given
  4109. /// nested-name-specifier.
  4110. ///
  4111. /// \param SS The nested-name-specifier of the declarator-id.
  4112. ///
  4113. /// \param DC The declaration context to which the nested-name-specifier
  4114. /// resolves.
  4115. ///
  4116. /// \param Name The name of the entity being declared.
  4117. ///
  4118. /// \param Loc The location of the name of the entity being declared.
  4119. ///
  4120. /// \returns true if we cannot safely recover from this error, false otherwise.
  4121. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4122. DeclarationName Name,
  4123. SourceLocation Loc) {
  4124. DeclContext *Cur = CurContext;
  4125. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4126. Cur = Cur->getParent();
  4127. // If the user provided a superfluous scope specifier that refers back to the
  4128. // class in which the entity is already declared, diagnose and ignore it.
  4129. //
  4130. // class X {
  4131. // void X::f();
  4132. // };
  4133. //
  4134. // Note, it was once ill-formed to give redundant qualification in all
  4135. // contexts, but that rule was removed by DR482.
  4136. if (Cur->Equals(DC)) {
  4137. if (Cur->isRecord()) {
  4138. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4139. : diag::err_member_extra_qualification)
  4140. << Name << FixItHint::CreateRemoval(SS.getRange());
  4141. SS.clear();
  4142. } else {
  4143. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4144. }
  4145. return false;
  4146. }
  4147. // Check whether the qualifying scope encloses the scope of the original
  4148. // declaration.
  4149. if (!Cur->Encloses(DC)) {
  4150. if (Cur->isRecord())
  4151. Diag(Loc, diag::err_member_qualification)
  4152. << Name << SS.getRange();
  4153. else if (isa<TranslationUnitDecl>(DC))
  4154. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4155. << Name << SS.getRange();
  4156. else if (isa<FunctionDecl>(Cur))
  4157. Diag(Loc, diag::err_invalid_declarator_in_function)
  4158. << Name << SS.getRange();
  4159. else if (isa<BlockDecl>(Cur))
  4160. Diag(Loc, diag::err_invalid_declarator_in_block)
  4161. << Name << SS.getRange();
  4162. else
  4163. Diag(Loc, diag::err_invalid_declarator_scope)
  4164. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4165. return true;
  4166. }
  4167. if (Cur->isRecord()) {
  4168. // Cannot qualify members within a class.
  4169. Diag(Loc, diag::err_member_qualification)
  4170. << Name << SS.getRange();
  4171. SS.clear();
  4172. // C++ constructors and destructors with incorrect scopes can break
  4173. // our AST invariants by having the wrong underlying types. If
  4174. // that's the case, then drop this declaration entirely.
  4175. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4176. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4177. !Context.hasSameType(Name.getCXXNameType(),
  4178. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4179. return true;
  4180. return false;
  4181. }
  4182. // C++11 [dcl.meaning]p1:
  4183. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4184. // not begin with a decltype-specifer"
  4185. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4186. while (SpecLoc.getPrefix())
  4187. SpecLoc = SpecLoc.getPrefix();
  4188. if (dyn_cast_or_null<DecltypeType>(
  4189. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4190. Diag(Loc, diag::err_decltype_in_declarator)
  4191. << SpecLoc.getTypeLoc().getSourceRange();
  4192. return false;
  4193. }
  4194. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4195. MultiTemplateParamsArg TemplateParamLists) {
  4196. // TODO: consider using NameInfo for diagnostic.
  4197. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4198. DeclarationName Name = NameInfo.getName();
  4199. // All of these full declarators require an identifier. If it doesn't have
  4200. // one, the ParsedFreeStandingDeclSpec action should be used.
  4201. if (!Name) {
  4202. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4203. Diag(D.getDeclSpec().getLocStart(),
  4204. diag::err_declarator_need_ident)
  4205. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4206. return nullptr;
  4207. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4208. return nullptr;
  4209. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4210. // we find one that is.
  4211. ShadowMergeState MergeState = S->isForDeclScope() ?
  4212. ShadowMergeState_Possible : ShadowMergeState_Disallowed; // HLSL Change - check on original scope
  4213. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4214. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4215. S = S->getParent();
  4216. DeclContext *DC = CurContext;
  4217. if (D.getCXXScopeSpec().isInvalid())
  4218. D.setInvalidType();
  4219. else if (D.getCXXScopeSpec().isSet()) {
  4220. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4221. UPPC_DeclarationQualifier))
  4222. return nullptr;
  4223. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4224. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4225. if (!DC || isa<EnumDecl>(DC)) {
  4226. // If we could not compute the declaration context, it's because the
  4227. // declaration context is dependent but does not refer to a class,
  4228. // class template, or class template partial specialization. Complain
  4229. // and return early, to avoid the coming semantic disaster.
  4230. Diag(D.getIdentifierLoc(),
  4231. diag::err_template_qualified_declarator_no_match)
  4232. << D.getCXXScopeSpec().getScopeRep()
  4233. << D.getCXXScopeSpec().getRange();
  4234. return nullptr;
  4235. }
  4236. bool IsDependentContext = DC->isDependentContext();
  4237. if (!IsDependentContext &&
  4238. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4239. return nullptr;
  4240. // If a class is incomplete, do not parse entities inside it.
  4241. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4242. Diag(D.getIdentifierLoc(),
  4243. diag::err_member_def_undefined_record)
  4244. << Name << DC << D.getCXXScopeSpec().getRange();
  4245. return nullptr;
  4246. }
  4247. if (!D.getDeclSpec().isFriendSpecified()) {
  4248. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  4249. Name, D.getIdentifierLoc())) {
  4250. if (DC->isRecord())
  4251. return nullptr;
  4252. D.setInvalidType();
  4253. }
  4254. }
  4255. // Check whether we need to rebuild the type of the given
  4256. // declaration in the current instantiation.
  4257. if (EnteringContext && IsDependentContext &&
  4258. TemplateParamLists.size() != 0) {
  4259. ContextRAII SavedContext(*this, DC);
  4260. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4261. D.setInvalidType();
  4262. }
  4263. }
  4264. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4265. QualType R = TInfo->getType();
  4266. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4267. // If this is a typedef, we'll end up spewing multiple diagnostics.
  4268. // Just return early; it's safer. If this is a function, let the
  4269. // "constructor cannot have a return type" diagnostic handle it.
  4270. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4271. return nullptr;
  4272. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4273. UPPC_DeclarationType))
  4274. D.setInvalidType();
  4275. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4276. ForRedeclaration);
  4277. // See if this is a redefinition of a variable in the same scope.
  4278. if (!D.getCXXScopeSpec().isSet()) {
  4279. bool IsLinkageLookup = false;
  4280. bool CreateBuiltins = false;
  4281. // If the declaration we're planning to build will be a function
  4282. // or object with linkage, then look for another declaration with
  4283. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4284. //
  4285. // If the declaration we're planning to build will be declared with
  4286. // external linkage in the translation unit, create any builtin with
  4287. // the same name.
  4288. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4289. /* Do nothing*/;
  4290. else if (CurContext->isFunctionOrMethod() &&
  4291. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4292. R->isFunctionType())) {
  4293. IsLinkageLookup = true;
  4294. CreateBuiltins =
  4295. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4296. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4297. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4298. CreateBuiltins = true;
  4299. if (IsLinkageLookup)
  4300. Previous.clear(LookupRedeclarationWithLinkage);
  4301. LookupName(Previous, S, CreateBuiltins);
  4302. } else { // Something like "int foo::x;"
  4303. LookupQualifiedName(Previous, DC);
  4304. // C++ [dcl.meaning]p1:
  4305. // When the declarator-id is qualified, the declaration shall refer to a
  4306. // previously declared member of the class or namespace to which the
  4307. // qualifier refers (or, in the case of a namespace, of an element of the
  4308. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4309. // thereof; [...]
  4310. //
  4311. // Note that we already checked the context above, and that we do not have
  4312. // enough information to make sure that Previous contains the declaration
  4313. // we want to match. For example, given:
  4314. //
  4315. // class X {
  4316. // void f();
  4317. // void f(float);
  4318. // };
  4319. //
  4320. // void X::f(int) { } // ill-formed
  4321. //
  4322. // In this case, Previous will point to the overload set
  4323. // containing the two f's declared in X, but neither of them
  4324. // matches.
  4325. // C++ [dcl.meaning]p1:
  4326. // [...] the member shall not merely have been introduced by a
  4327. // using-declaration in the scope of the class or namespace nominated by
  4328. // the nested-name-specifier of the declarator-id.
  4329. RemoveUsingDecls(Previous);
  4330. }
  4331. if (Previous.isSingleResult() &&
  4332. Previous.getFoundDecl()->isTemplateParameter()) {
  4333. // Maybe we will complain about the shadowed template parameter.
  4334. if (!D.isInvalidType())
  4335. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4336. Previous.getFoundDecl());
  4337. // Just pretend that we didn't see the previous declaration.
  4338. Previous.clear();
  4339. }
  4340. // In C++, the previous declaration we find might be a tag type
  4341. // (class or enum). In this case, the new declaration will hide the
  4342. // tag type. Note that this does does not apply if we're declaring a
  4343. // typedef (C++ [dcl.typedef]p4).
  4344. if (Previous.isSingleTagDecl() &&
  4345. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  4346. Previous.clear();
  4347. // Check that there are no default arguments other than in the parameters
  4348. // of a function declaration (C++ only).
  4349. if (getLangOpts().CPlusPlus)
  4350. CheckExtraCXXDefaultArguments(D);
  4351. // HLSL Change Starts
  4352. if (getLangOpts().HLSL) {
  4353. const bool IsParameterFalse = false;
  4354. if (!DiagnoseHLSLDecl(D, DC, /*BitWidth*/ nullptr, TInfo, IsParameterFalse)) {
  4355. assert(D.isInvalidType() && "otherwise DiagnoseHLSLDecl failed but "
  4356. "didn't invalidate declaration");
  4357. return 0;
  4358. }
  4359. }
  4360. // HLSL Change Ends
  4361. NamedDecl *New;
  4362. bool AddToScope = true;
  4363. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4364. if (TemplateParamLists.size()) {
  4365. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4366. return nullptr;
  4367. }
  4368. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4369. } else if (R->isFunctionType()) {
  4370. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4371. TemplateParamLists,
  4372. AddToScope);
  4373. } else {
  4374. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4375. AddToScope, MergeState); // HLSL Change - add merge state
  4376. }
  4377. if (!New)
  4378. return nullptr;
  4379. TransferUnusualAttributes(D, New); // HLSL Change
  4380. // If this has an identifier and is not an invalid redeclaration or
  4381. // function template specialization, add it to the scope stack.
  4382. if (New->getDeclName() && AddToScope &&
  4383. !(D.isRedeclaration() && New->isInvalidDecl())) {
  4384. // Only make a locally-scoped extern declaration visible if it is the first
  4385. // declaration of this entity. Qualified lookup for such an entity should
  4386. // only find this declaration if there is no visible declaration of it.
  4387. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4388. PushOnScopeChains(New, S, AddToContext);
  4389. if (!AddToContext)
  4390. CurContext->addHiddenDecl(New);
  4391. }
  4392. return New;
  4393. }
  4394. /// Helper method to turn variable array types into constant array
  4395. /// types in certain situations which would otherwise be errors (for
  4396. /// GCC compatibility).
  4397. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4398. ASTContext &Context,
  4399. bool &SizeIsNegative,
  4400. llvm::APSInt &Oversized) {
  4401. // This method tries to turn a variable array into a constant
  4402. // array even when the size isn't an ICE. This is necessary
  4403. // for compatibility with code that depends on gcc's buggy
  4404. // constant expression folding, like struct {char x[(int)(char*)2];}
  4405. SizeIsNegative = false;
  4406. Oversized = 0;
  4407. if (T->isDependentType())
  4408. return QualType();
  4409. QualifierCollector Qs;
  4410. const Type *Ty = Qs.strip(T);
  4411. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4412. QualType Pointee = PTy->getPointeeType();
  4413. QualType FixedType =
  4414. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4415. Oversized);
  4416. if (FixedType.isNull()) return FixedType;
  4417. FixedType = Context.getPointerType(FixedType);
  4418. return Qs.apply(Context, FixedType);
  4419. }
  4420. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4421. QualType Inner = PTy->getInnerType();
  4422. QualType FixedType =
  4423. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4424. Oversized);
  4425. if (FixedType.isNull()) return FixedType;
  4426. FixedType = Context.getParenType(FixedType);
  4427. return Qs.apply(Context, FixedType);
  4428. }
  4429. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4430. if (!VLATy)
  4431. return QualType();
  4432. // FIXME: We should probably handle this case
  4433. if (VLATy->getElementType()->isVariablyModifiedType())
  4434. return QualType();
  4435. llvm::APSInt Res;
  4436. if (!VLATy->getSizeExpr() ||
  4437. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4438. return QualType();
  4439. // Check whether the array size is negative.
  4440. if (Res.isSigned() && Res.isNegative()) {
  4441. SizeIsNegative = true;
  4442. return QualType();
  4443. }
  4444. // Check whether the array is too large to be addressed.
  4445. unsigned ActiveSizeBits
  4446. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4447. Res);
  4448. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4449. Oversized = Res;
  4450. return QualType();
  4451. }
  4452. return Context.getConstantArrayType(VLATy->getElementType(),
  4453. Res, ArrayType::Normal, 0);
  4454. }
  4455. static void
  4456. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4457. SrcTL = SrcTL.getUnqualifiedLoc();
  4458. DstTL = DstTL.getUnqualifiedLoc();
  4459. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4460. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4461. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4462. DstPTL.getPointeeLoc());
  4463. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4464. return;
  4465. }
  4466. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4467. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4468. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4469. DstPTL.getInnerLoc());
  4470. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4471. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4472. return;
  4473. }
  4474. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4475. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4476. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4477. TypeLoc DstElemTL = DstATL.getElementLoc();
  4478. DstElemTL.initializeFullCopy(SrcElemTL);
  4479. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4480. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4481. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4482. }
  4483. /// Helper method to turn variable array types into constant array
  4484. /// types in certain situations which would otherwise be errors (for
  4485. /// GCC compatibility).
  4486. static TypeSourceInfo*
  4487. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4488. ASTContext &Context,
  4489. bool &SizeIsNegative,
  4490. llvm::APSInt &Oversized) {
  4491. QualType FixedTy
  4492. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4493. SizeIsNegative, Oversized);
  4494. if (FixedTy.isNull())
  4495. return nullptr;
  4496. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4497. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4498. FixedTInfo->getTypeLoc());
  4499. return FixedTInfo;
  4500. }
  4501. /// \brief Register the given locally-scoped extern "C" declaration so
  4502. /// that it can be found later for redeclarations. We include any extern "C"
  4503. /// declaration that is not visible in the translation unit here, not just
  4504. /// function-scope declarations.
  4505. void
  4506. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4507. if (!getLangOpts().CPlusPlus &&
  4508. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4509. // Don't need to track declarations in the TU in C.
  4510. return;
  4511. // Note that we have a locally-scoped external with this name.
  4512. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  4513. }
  4514. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4515. // FIXME: We can have multiple results via __attribute__((overloadable)).
  4516. auto Result = Context.getExternCContextDecl()->lookup(Name);
  4517. return Result.empty() ? nullptr : *Result.begin();
  4518. }
  4519. /// \brief Diagnose function specifiers on a declaration of an identifier that
  4520. /// does not identify a function.
  4521. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  4522. // FIXME: We should probably indicate the identifier in question to avoid
  4523. // confusion for constructs like "inline int a(), b;"
  4524. if (DS.isInlineSpecified())
  4525. Diag(DS.getInlineSpecLoc(),
  4526. diag::err_inline_non_function);
  4527. if (DS.isVirtualSpecified())
  4528. Diag(DS.getVirtualSpecLoc(),
  4529. diag::err_virtual_non_function);
  4530. if (DS.isExplicitSpecified())
  4531. Diag(DS.getExplicitSpecLoc(),
  4532. diag::err_explicit_non_function);
  4533. if (DS.isNoreturnSpecified())
  4534. Diag(DS.getNoreturnSpecLoc(),
  4535. diag::err_noreturn_non_function);
  4536. }
  4537. NamedDecl*
  4538. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  4539. TypeSourceInfo *TInfo, LookupResult &Previous) {
  4540. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  4541. if (D.getCXXScopeSpec().isSet()) {
  4542. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  4543. << D.getCXXScopeSpec().getRange();
  4544. D.setInvalidType();
  4545. // Pretend we didn't see the scope specifier.
  4546. DC = CurContext;
  4547. Previous.clear();
  4548. }
  4549. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4550. if (D.getDeclSpec().isConstexprSpecified())
  4551. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  4552. << 1;
  4553. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  4554. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  4555. << D.getName().getSourceRange();
  4556. return nullptr;
  4557. }
  4558. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  4559. if (!NewTD) return nullptr;
  4560. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4561. ProcessDeclAttributes(S, NewTD, D);
  4562. CheckTypedefForVariablyModifiedType(S, NewTD);
  4563. bool Redeclaration = D.isRedeclaration();
  4564. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  4565. D.setRedeclaration(Redeclaration);
  4566. return ND;
  4567. }
  4568. void
  4569. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  4570. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  4571. // then it shall have block scope.
  4572. // Note that variably modified types must be fixed before merging the decl so
  4573. // that redeclarations will match.
  4574. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  4575. QualType T = TInfo->getType();
  4576. if (T->isVariablyModifiedType()) {
  4577. getCurFunction()->setHasBranchProtectedScope();
  4578. if (S->getFnParent() == nullptr) {
  4579. bool SizeIsNegative;
  4580. llvm::APSInt Oversized;
  4581. TypeSourceInfo *FixedTInfo =
  4582. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  4583. SizeIsNegative,
  4584. Oversized);
  4585. if (FixedTInfo) {
  4586. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  4587. NewTD->setTypeSourceInfo(FixedTInfo);
  4588. } else {
  4589. if (SizeIsNegative)
  4590. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  4591. else if (T->isVariableArrayType())
  4592. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  4593. else if (Oversized.getBoolValue())
  4594. Diag(NewTD->getLocation(), diag::err_array_too_large)
  4595. << Oversized.toString(10);
  4596. else
  4597. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  4598. NewTD->setInvalidDecl();
  4599. }
  4600. }
  4601. }
  4602. }
  4603. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  4604. /// declares a typedef-name, either using the 'typedef' type specifier or via
  4605. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  4606. NamedDecl*
  4607. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  4608. LookupResult &Previous, bool &Redeclaration) {
  4609. // Merge the decl with the existing one if appropriate. If the decl is
  4610. // in an outer scope, it isn't the same thing.
  4611. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  4612. /*AllowInlineNamespace*/false);
  4613. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  4614. if (!Previous.empty()) {
  4615. Redeclaration = true;
  4616. MergeTypedefNameDecl(NewTD, Previous);
  4617. }
  4618. // If this is the C FILE type, notify the AST context.
  4619. if (IdentifierInfo *II = NewTD->getIdentifier())
  4620. if (!NewTD->isInvalidDecl() &&
  4621. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4622. if (II->isStr("FILE"))
  4623. Context.setFILEDecl(NewTD);
  4624. else if (II->isStr("jmp_buf"))
  4625. Context.setjmp_bufDecl(NewTD);
  4626. else if (II->isStr("sigjmp_buf"))
  4627. Context.setsigjmp_bufDecl(NewTD);
  4628. else if (II->isStr("ucontext_t"))
  4629. Context.setucontext_tDecl(NewTD);
  4630. }
  4631. return NewTD;
  4632. }
  4633. /// \brief Determines whether the given declaration is an out-of-scope
  4634. /// previous declaration.
  4635. ///
  4636. /// This routine should be invoked when name lookup has found a
  4637. /// previous declaration (PrevDecl) that is not in the scope where a
  4638. /// new declaration by the same name is being introduced. If the new
  4639. /// declaration occurs in a local scope, previous declarations with
  4640. /// linkage may still be considered previous declarations (C99
  4641. /// 6.2.2p4-5, C++ [basic.link]p6).
  4642. ///
  4643. /// \param PrevDecl the previous declaration found by name
  4644. /// lookup
  4645. ///
  4646. /// \param DC the context in which the new declaration is being
  4647. /// declared.
  4648. ///
  4649. /// \returns true if PrevDecl is an out-of-scope previous declaration
  4650. /// for a new delcaration with the same name.
  4651. static bool
  4652. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  4653. ASTContext &Context) {
  4654. if (!PrevDecl)
  4655. return false;
  4656. if (!PrevDecl->hasLinkage())
  4657. return false;
  4658. if (Context.getLangOpts().CPlusPlus) {
  4659. // C++ [basic.link]p6:
  4660. // If there is a visible declaration of an entity with linkage
  4661. // having the same name and type, ignoring entities declared
  4662. // outside the innermost enclosing namespace scope, the block
  4663. // scope declaration declares that same entity and receives the
  4664. // linkage of the previous declaration.
  4665. DeclContext *OuterContext = DC->getRedeclContext();
  4666. if (!OuterContext->isFunctionOrMethod())
  4667. // This rule only applies to block-scope declarations.
  4668. return false;
  4669. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  4670. if (PrevOuterContext->isRecord())
  4671. // We found a member function: ignore it.
  4672. return false;
  4673. // Find the innermost enclosing namespace for the new and
  4674. // previous declarations.
  4675. OuterContext = OuterContext->getEnclosingNamespaceContext();
  4676. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  4677. // The previous declaration is in a different namespace, so it
  4678. // isn't the same function.
  4679. if (!OuterContext->Equals(PrevOuterContext))
  4680. return false;
  4681. }
  4682. return true;
  4683. }
  4684. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  4685. CXXScopeSpec &SS = D.getCXXScopeSpec();
  4686. if (!SS.isSet()) return;
  4687. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  4688. }
  4689. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  4690. QualType type = decl->getType();
  4691. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  4692. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  4693. // Various kinds of declaration aren't allowed to be __autoreleasing.
  4694. unsigned kind = -1U;
  4695. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4696. if (var->hasAttr<BlocksAttr>())
  4697. kind = 0; // __block
  4698. else if (!var->hasLocalStorage())
  4699. kind = 1; // global
  4700. } else if (isa<ObjCIvarDecl>(decl)) {
  4701. kind = 3; // ivar
  4702. } else if (isa<FieldDecl>(decl)) {
  4703. kind = 2; // field
  4704. }
  4705. if (kind != -1U) {
  4706. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  4707. << kind;
  4708. }
  4709. } else if (lifetime == Qualifiers::OCL_None) {
  4710. // Try to infer lifetime.
  4711. if (!type->isObjCLifetimeType())
  4712. return false;
  4713. lifetime = type->getObjCARCImplicitLifetime();
  4714. type = Context.getLifetimeQualifiedType(type, lifetime);
  4715. decl->setType(type);
  4716. }
  4717. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4718. // Thread-local variables cannot have lifetime.
  4719. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  4720. var->getTLSKind()) {
  4721. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  4722. << var->getType();
  4723. return true;
  4724. }
  4725. }
  4726. return false;
  4727. }
  4728. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  4729. // Ensure that an auto decl is deduced otherwise the checks below might cache
  4730. // the wrong linkage.
  4731. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  4732. // 'weak' only applies to declarations with external linkage.
  4733. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  4734. if (!ND.isExternallyVisible()) {
  4735. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  4736. ND.dropAttr<WeakAttr>();
  4737. }
  4738. }
  4739. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  4740. if (ND.isExternallyVisible()) {
  4741. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  4742. ND.dropAttr<WeakRefAttr>();
  4743. ND.dropAttr<AliasAttr>();
  4744. }
  4745. }
  4746. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  4747. if (VD->hasInit()) {
  4748. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  4749. assert(VD->isThisDeclarationADefinition() &&
  4750. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  4751. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
  4752. VD->dropAttr<AliasAttr>();
  4753. }
  4754. }
  4755. }
  4756. // 'selectany' only applies to externally visible variable declarations.
  4757. // It does not apply to functions.
  4758. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  4759. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  4760. S.Diag(Attr->getLocation(),
  4761. diag::err_attribute_selectany_non_extern_data);
  4762. ND.dropAttr<SelectAnyAttr>();
  4763. }
  4764. }
  4765. // dll attributes require external linkage.
  4766. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  4767. if (!ND.isExternallyVisible()) {
  4768. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  4769. << &ND << Attr;
  4770. ND.setInvalidDecl();
  4771. }
  4772. }
  4773. }
  4774. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  4775. NamedDecl *NewDecl,
  4776. bool IsSpecialization) {
  4777. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
  4778. OldDecl = OldTD->getTemplatedDecl();
  4779. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
  4780. NewDecl = NewTD->getTemplatedDecl();
  4781. if (!OldDecl || !NewDecl)
  4782. return;
  4783. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  4784. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  4785. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  4786. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  4787. // dllimport and dllexport are inheritable attributes so we have to exclude
  4788. // inherited attribute instances.
  4789. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  4790. (NewExportAttr && !NewExportAttr->isInherited());
  4791. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  4792. // the only exception being explicit specializations.
  4793. // Implicitly generated declarations are also excluded for now because there
  4794. // is no other way to switch these to use dllimport or dllexport.
  4795. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  4796. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  4797. // Allow with a warning for free functions and global variables.
  4798. bool JustWarn = false;
  4799. if (!OldDecl->isCXXClassMember()) {
  4800. auto *VD = dyn_cast<VarDecl>(OldDecl);
  4801. if (VD && !VD->getDescribedVarTemplate())
  4802. JustWarn = true;
  4803. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  4804. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  4805. JustWarn = true;
  4806. }
  4807. // We cannot change a declaration that's been used because IR has already
  4808. // been emitted. Dllimported functions will still work though (modulo
  4809. // address equality) as they can use the thunk.
  4810. if (OldDecl->isUsed())
  4811. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  4812. JustWarn = false;
  4813. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  4814. : diag::err_attribute_dll_redeclaration;
  4815. S.Diag(NewDecl->getLocation(), DiagID)
  4816. << NewDecl
  4817. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  4818. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4819. if (!JustWarn) {
  4820. NewDecl->setInvalidDecl();
  4821. return;
  4822. }
  4823. }
  4824. // A redeclaration is not allowed to drop a dllimport attribute, the only
  4825. // exceptions being inline function definitions, local extern declarations,
  4826. // and qualified friend declarations.
  4827. // NB: MSVC converts such a declaration to dllexport.
  4828. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  4829. if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
  4830. // Ignore static data because out-of-line definitions are diagnosed
  4831. // separately.
  4832. IsStaticDataMember = VD->isStaticDataMember();
  4833. else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  4834. IsInline = FD->isInlined();
  4835. IsQualifiedFriend = FD->getQualifier() &&
  4836. FD->getFriendObjectKind() == Decl::FOK_Declared;
  4837. }
  4838. if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
  4839. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  4840. S.Diag(NewDecl->getLocation(),
  4841. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  4842. << NewDecl << OldImportAttr;
  4843. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4844. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  4845. OldDecl->dropAttr<DLLImportAttr>();
  4846. NewDecl->dropAttr<DLLImportAttr>();
  4847. } else if (IsInline && OldImportAttr &&
  4848. !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  4849. // In MinGW, seeing a function declared inline drops the dllimport attribute.
  4850. OldDecl->dropAttr<DLLImportAttr>();
  4851. NewDecl->dropAttr<DLLImportAttr>();
  4852. S.Diag(NewDecl->getLocation(),
  4853. diag::warn_dllimport_dropped_from_inline_function)
  4854. << NewDecl << OldImportAttr;
  4855. }
  4856. }
  4857. /// Given that we are within the definition of the given function,
  4858. /// will that definition behave like C99's 'inline', where the
  4859. /// definition is discarded except for optimization purposes?
  4860. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  4861. // Try to avoid calling GetGVALinkageForFunction.
  4862. // All cases of this require the 'inline' keyword.
  4863. if (!FD->isInlined()) return false;
  4864. // This is only possible in C++ with the gnu_inline attribute.
  4865. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  4866. return false;
  4867. // Okay, go ahead and call the relatively-more-expensive function.
  4868. #ifndef NDEBUG
  4869. // AST quite reasonably asserts that it's working on a function
  4870. // definition. We don't really have a way to tell it that we're
  4871. // currently defining the function, so just lie to it in +Asserts
  4872. // builds. This is an awful hack.
  4873. FD->setLazyBody(1);
  4874. #endif
  4875. bool isC99Inline =
  4876. S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  4877. #ifndef NDEBUG
  4878. FD->setLazyBody(0);
  4879. #endif
  4880. return isC99Inline;
  4881. }
  4882. /// Determine whether a variable is extern "C" prior to attaching
  4883. /// an initializer. We can't just call isExternC() here, because that
  4884. /// will also compute and cache whether the declaration is externally
  4885. /// visible, which might change when we attach the initializer.
  4886. ///
  4887. /// This can only be used if the declaration is known to not be a
  4888. /// redeclaration of an internal linkage declaration.
  4889. ///
  4890. /// For instance:
  4891. ///
  4892. /// auto x = []{};
  4893. ///
  4894. /// Attaching the initializer here makes this declaration not externally
  4895. /// visible, because its type has internal linkage.
  4896. ///
  4897. /// FIXME: This is a hack.
  4898. template<typename T>
  4899. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  4900. if (S.getLangOpts().CPlusPlus) {
  4901. // In C++, the overloadable attribute negates the effects of extern "C".
  4902. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  4903. return false;
  4904. }
  4905. return D->isExternC();
  4906. }
  4907. static bool shouldConsiderLinkage(const VarDecl *VD) {
  4908. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  4909. if (DC->isFunctionOrMethod())
  4910. return VD->hasExternalStorage();
  4911. if (DC->isFileContext())
  4912. return true;
  4913. if (DC->isRecord())
  4914. return false;
  4915. llvm_unreachable("Unexpected context");
  4916. }
  4917. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  4918. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  4919. if (DC->isFileContext() || DC->isFunctionOrMethod())
  4920. return true;
  4921. if (DC->isRecord())
  4922. return false;
  4923. llvm_unreachable("Unexpected context");
  4924. }
  4925. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  4926. AttributeList::Kind Kind) {
  4927. for (const AttributeList *L = AttrList; L; L = L->getNext())
  4928. if (L->getKind() == Kind)
  4929. return true;
  4930. return false;
  4931. }
  4932. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  4933. AttributeList::Kind Kind) {
  4934. // Check decl attributes on the DeclSpec.
  4935. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  4936. return true;
  4937. // Walk the declarator structure, checking decl attributes that were in a type
  4938. // position to the decl itself.
  4939. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  4940. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  4941. return true;
  4942. }
  4943. // Finally, check attributes on the decl itself.
  4944. return hasParsedAttr(S, PD.getAttributes(), Kind);
  4945. }
  4946. /// Adjust the \c DeclContext for a function or variable that might be a
  4947. /// function-local external declaration.
  4948. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  4949. if (!DC->isFunctionOrMethod())
  4950. return false;
  4951. // If this is a local extern function or variable declared within a function
  4952. // template, don't add it into the enclosing namespace scope until it is
  4953. // instantiated; it might have a dependent type right now.
  4954. if (DC->isDependentContext())
  4955. return true;
  4956. // C++11 [basic.link]p7:
  4957. // When a block scope declaration of an entity with linkage is not found to
  4958. // refer to some other declaration, then that entity is a member of the
  4959. // innermost enclosing namespace.
  4960. //
  4961. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  4962. // semantically-enclosing namespace, not a lexically-enclosing one.
  4963. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  4964. DC = DC->getParent();
  4965. return true;
  4966. }
  4967. /// \brief Returns true if given declaration is TU-scoped and externally
  4968. /// visible.
  4969. static bool isDeclTUScopedExternallyVisible(const Decl *D) {
  4970. if (auto *FD = dyn_cast<FunctionDecl>(D))
  4971. return (FD->getDeclContext()->isTranslationUnit() || FD->isExternC()) &&
  4972. FD->hasExternalFormalLinkage();
  4973. else if (auto *VD = dyn_cast<VarDecl>(D))
  4974. return (VD->getDeclContext()->isTranslationUnit() || VD->isExternC()) &&
  4975. VD->hasExternalFormalLinkage();
  4976. llvm_unreachable("Unknown type of decl!");
  4977. }
  4978. NamedDecl *
  4979. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4980. TypeSourceInfo *TInfo, LookupResult &Previous,
  4981. MultiTemplateParamsArg TemplateParamLists,
  4982. bool &AddToScope, ShadowMergeState MergeState) { // HLSL Change - add merge state
  4983. QualType R = TInfo->getType();
  4984. DeclarationName Name = GetNameForDeclarator(D).getName();
  4985. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  4986. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  4987. // dllimport globals without explicit storage class are treated as extern. We
  4988. // have to change the storage class this early to get the right DeclContext.
  4989. if (SC == SC_None && !DC->isRecord() &&
  4990. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  4991. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  4992. SC = SC_Extern;
  4993. DeclContext *OriginalDC = DC;
  4994. bool IsLocalExternDecl = SC == SC_Extern &&
  4995. adjustContextForLocalExternDecl(DC);
  4996. if (getLangOpts().OpenCL) {
  4997. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  4998. QualType NR = R;
  4999. while (NR->isPointerType()) {
  5000. if (NR->isFunctionPointerType()) {
  5001. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
  5002. D.setInvalidType();
  5003. break;
  5004. }
  5005. NR = NR->getPointeeType();
  5006. }
  5007. if (!getOpenCLOptions().cl_khr_fp16) {
  5008. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5009. // half array type (unless the cl_khr_fp16 extension is enabled).
  5010. if (Context.getBaseElementType(R)->isHalfType()) {
  5011. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5012. D.setInvalidType();
  5013. }
  5014. }
  5015. }
  5016. if (SCSpec == DeclSpec::SCS_mutable) {
  5017. // mutable can only appear on non-static class members, so it's always
  5018. // an error here
  5019. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5020. D.setInvalidType();
  5021. SC = SC_None;
  5022. }
  5023. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5024. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5025. D.getDeclSpec().getStorageClassSpecLoc())) {
  5026. // In C++11, the 'register' storage class specifier is deprecated.
  5027. // Suppress the warning in system macros, it's used in macros in some
  5028. // popular C system headers, such as in glibc's htonl() macro.
  5029. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5030. diag::warn_deprecated_register)
  5031. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5032. }
  5033. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5034. if (!II) {
  5035. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  5036. << Name;
  5037. return nullptr;
  5038. }
  5039. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5040. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5041. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5042. // appear in the declaration specifiers in an external declaration.
  5043. // Global Register+Asm is a GNU extension we support.
  5044. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5045. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5046. D.setInvalidType();
  5047. }
  5048. }
  5049. if (getLangOpts().OpenCL) {
  5050. // Set up the special work-group-local storage class for variables in the
  5051. // OpenCL __local address space.
  5052. if (R.getAddressSpace() == LangAS::opencl_local) {
  5053. SC = SC_OpenCLWorkGroupLocal;
  5054. }
  5055. // OpenCL v1.2 s6.9.b p4:
  5056. // The sampler type cannot be used with the __local and __global address
  5057. // space qualifiers.
  5058. if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
  5059. R.getAddressSpace() == LangAS::opencl_global)) {
  5060. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5061. }
  5062. // OpenCL 1.2 spec, p6.9 r:
  5063. // The event type cannot be used to declare a program scope variable.
  5064. // The event type cannot be used with the __local, __constant and __global
  5065. // address space qualifiers.
  5066. if (R->isEventT()) {
  5067. if (S->getParent() == nullptr) {
  5068. Diag(D.getLocStart(), diag::err_event_t_global_var);
  5069. D.setInvalidType();
  5070. }
  5071. if (R.getAddressSpace()) {
  5072. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5073. D.setInvalidType();
  5074. }
  5075. }
  5076. }
  5077. bool IsExplicitSpecialization = false;
  5078. bool IsVariableTemplateSpecialization = false;
  5079. bool IsPartialSpecialization = false;
  5080. bool IsVariableTemplate = false;
  5081. VarDecl *NewVD = nullptr;
  5082. VarTemplateDecl *NewTemplate = nullptr;
  5083. TemplateParameterList *TemplateParams = nullptr;
  5084. if (!getLangOpts().CPlusPlus) {
  5085. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5086. D.getIdentifierLoc(), II,
  5087. R, TInfo, SC);
  5088. if (D.isInvalidType())
  5089. NewVD->setInvalidDecl();
  5090. } else {
  5091. bool Invalid = false;
  5092. if (DC->isRecord() && !CurContext->isRecord()) {
  5093. // This is an out-of-line definition of a static data member.
  5094. switch (SC) {
  5095. case SC_None:
  5096. break;
  5097. case SC_Static:
  5098. if (!getLangOpts().HLSL) // HLSL Change: We had to set SC_Static for
  5099. // static data member to distinguish it from
  5100. // global constant variable.
  5101. // So we ignore this warning.
  5102. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5103. diag::err_static_out_of_line)
  5104. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5105. break;
  5106. case SC_Auto:
  5107. case SC_Register:
  5108. case SC_Extern:
  5109. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5110. // to names of variables declared in a block or to function parameters.
  5111. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5112. // of class members
  5113. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5114. diag::err_storage_class_for_static_member)
  5115. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5116. break;
  5117. case SC_PrivateExtern:
  5118. llvm_unreachable("C storage class in c++!");
  5119. case SC_OpenCLWorkGroupLocal:
  5120. llvm_unreachable("OpenCL storage class in c++!");
  5121. }
  5122. }
  5123. if (SC == SC_Static && CurContext->isRecord()) {
  5124. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5125. if (RD->isLocalClass())
  5126. Diag(D.getIdentifierLoc(),
  5127. diag::err_static_data_member_not_allowed_in_local_class)
  5128. << Name << RD->getDeclName();
  5129. // C++98 [class.union]p1: If a union contains a static data member,
  5130. // the program is ill-formed. C++11 drops this restriction.
  5131. if (RD->isUnion())
  5132. Diag(D.getIdentifierLoc(),
  5133. getLangOpts().CPlusPlus11
  5134. ? diag::warn_cxx98_compat_static_data_member_in_union
  5135. : diag::ext_static_data_member_in_union) << Name;
  5136. // We conservatively disallow static data members in anonymous structs.
  5137. else if (!RD->getDeclName())
  5138. Diag(D.getIdentifierLoc(),
  5139. diag::err_static_data_member_not_allowed_in_anon_struct)
  5140. << Name << RD->isUnion();
  5141. }
  5142. }
  5143. // Match up the template parameter lists with the scope specifier, then
  5144. // determine whether we have a template or a template specialization.
  5145. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5146. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5147. D.getCXXScopeSpec(),
  5148. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5149. ? D.getName().TemplateId
  5150. : nullptr,
  5151. TemplateParamLists,
  5152. /*never a friend*/ false, IsExplicitSpecialization, Invalid);
  5153. if (TemplateParams) {
  5154. if (!TemplateParams->size() &&
  5155. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5156. // There is an extraneous 'template<>' for this variable. Complain
  5157. // about it, but allow the declaration of the variable.
  5158. Diag(TemplateParams->getTemplateLoc(),
  5159. diag::err_template_variable_noparams)
  5160. << II
  5161. << SourceRange(TemplateParams->getTemplateLoc(),
  5162. TemplateParams->getRAngleLoc());
  5163. TemplateParams = nullptr;
  5164. } else {
  5165. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5166. // This is an explicit specialization or a partial specialization.
  5167. // FIXME: Check that we can declare a specialization here.
  5168. IsVariableTemplateSpecialization = true;
  5169. IsPartialSpecialization = TemplateParams->size() > 0;
  5170. } else { // if (TemplateParams->size() > 0)
  5171. // This is a template declaration.
  5172. IsVariableTemplate = true;
  5173. // Check that we can declare a template here.
  5174. if (CheckTemplateDeclScope(S, TemplateParams))
  5175. return nullptr;
  5176. // Only C++1y supports variable templates (N3651).
  5177. Diag(D.getIdentifierLoc(),
  5178. getLangOpts().CPlusPlus14
  5179. ? diag::warn_cxx11_compat_variable_template
  5180. : diag::ext_variable_template);
  5181. }
  5182. }
  5183. } else {
  5184. assert(
  5185. (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
  5186. "should have a 'template<>' for this decl");
  5187. }
  5188. if (IsVariableTemplateSpecialization) {
  5189. SourceLocation TemplateKWLoc =
  5190. TemplateParamLists.size() > 0
  5191. ? TemplateParamLists[0]->getTemplateLoc()
  5192. : SourceLocation();
  5193. DeclResult Res = ActOnVarTemplateSpecialization(
  5194. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5195. IsPartialSpecialization);
  5196. if (Res.isInvalid())
  5197. return nullptr;
  5198. NewVD = cast<VarDecl>(Res.get());
  5199. AddToScope = false;
  5200. } else
  5201. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5202. D.getIdentifierLoc(), II, R, TInfo, SC);
  5203. // If this is supposed to be a variable template, create it as such.
  5204. if (IsVariableTemplate) {
  5205. NewTemplate =
  5206. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5207. TemplateParams, NewVD);
  5208. NewVD->setDescribedVarTemplate(NewTemplate);
  5209. }
  5210. // If this decl has an auto type in need of deduction, make a note of the
  5211. // Decl so we can diagnose uses of it in its own initializer.
  5212. if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
  5213. ParsingInitForAutoVars.insert(NewVD);
  5214. if (D.isInvalidType() || Invalid) {
  5215. NewVD->setInvalidDecl();
  5216. if (NewTemplate)
  5217. NewTemplate->setInvalidDecl();
  5218. }
  5219. SetNestedNameSpecifier(NewVD, D);
  5220. // If we have any template parameter lists that don't directly belong to
  5221. // the variable (matching the scope specifier), store them.
  5222. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5223. if (TemplateParamLists.size() > VDTemplateParamLists)
  5224. NewVD->setTemplateParameterListsInfo(
  5225. Context, TemplateParamLists.size() - VDTemplateParamLists,
  5226. TemplateParamLists.data());
  5227. if (D.getDeclSpec().isConstexprSpecified())
  5228. NewVD->setConstexpr(true);
  5229. }
  5230. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5231. // lexical context will be different from the semantic context.
  5232. NewVD->setLexicalDeclContext(CurContext);
  5233. if (NewTemplate)
  5234. NewTemplate->setLexicalDeclContext(CurContext);
  5235. if (IsLocalExternDecl)
  5236. NewVD->setLocalExternDecl();
  5237. bool EmitTLSUnsupportedError = false;
  5238. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5239. // C++11 [dcl.stc]p4:
  5240. // When thread_local is applied to a variable of block scope the
  5241. // storage-class-specifier static is implied if it does not appear
  5242. // explicitly.
  5243. // Core issue: 'static' is not implied if the variable is declared
  5244. // 'extern'.
  5245. if (NewVD->hasLocalStorage() &&
  5246. (SCSpec != DeclSpec::SCS_unspecified ||
  5247. TSCS != DeclSpec::TSCS_thread_local ||
  5248. !DC->isFunctionOrMethod()))
  5249. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5250. diag::err_thread_non_global)
  5251. << DeclSpec::getSpecifierName(TSCS);
  5252. else if (!Context.getTargetInfo().isTLSSupported()) {
  5253. if (getLangOpts().CUDA) {
  5254. // Postpone error emission until we've collected attributes required to
  5255. // figure out whether it's a host or device variable and whether the
  5256. // error should be ignored.
  5257. EmitTLSUnsupportedError = true;
  5258. // We still need to mark the variable as TLS so it shows up in AST with
  5259. // proper storage class for other tools to use even if we're not going
  5260. // to emit any code for it.
  5261. NewVD->setTSCSpec(TSCS);
  5262. } else
  5263. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5264. diag::err_thread_unsupported);
  5265. } else
  5266. NewVD->setTSCSpec(TSCS);
  5267. }
  5268. // C99 6.7.4p3
  5269. // An inline definition of a function with external linkage shall
  5270. // not contain a definition of a modifiable object with static or
  5271. // thread storage duration...
  5272. // We only apply this when the function is required to be defined
  5273. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5274. // that a local variable with thread storage duration still has to
  5275. // be marked 'static'. Also note that it's possible to get these
  5276. // semantics in C++ using __attribute__((gnu_inline)).
  5277. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5278. !NewVD->getType().isConstQualified()) {
  5279. FunctionDecl *CurFD = getCurFunctionDecl();
  5280. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5281. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5282. diag::warn_static_local_in_extern_inline);
  5283. MaybeSuggestAddingStaticToDecl(CurFD);
  5284. }
  5285. }
  5286. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5287. if (IsVariableTemplateSpecialization)
  5288. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5289. << (IsPartialSpecialization ? 1 : 0)
  5290. << FixItHint::CreateRemoval(
  5291. D.getDeclSpec().getModulePrivateSpecLoc());
  5292. else if (IsExplicitSpecialization)
  5293. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5294. << 2
  5295. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5296. else if (NewVD->hasLocalStorage())
  5297. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5298. << 0 << NewVD->getDeclName()
  5299. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5300. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5301. else {
  5302. NewVD->setModulePrivate();
  5303. if (NewTemplate)
  5304. NewTemplate->setModulePrivate();
  5305. }
  5306. }
  5307. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5308. ProcessDeclAttributes(S, NewVD, D);
  5309. if (getLangOpts().CUDA) {
  5310. if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
  5311. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5312. diag::err_thread_unsupported);
  5313. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5314. // storage [duration]."
  5315. if (SC == SC_None && S->getFnParent() != nullptr &&
  5316. (NewVD->hasAttr<CUDASharedAttr>() ||
  5317. NewVD->hasAttr<CUDAConstantAttr>())) {
  5318. NewVD->setStorageClass(SC_Static);
  5319. }
  5320. }
  5321. // Ensure that dllimport globals without explicit storage class are treated as
  5322. // extern. The storage class is set above using parsed attributes. Now we can
  5323. // check the VarDecl itself.
  5324. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5325. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5326. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5327. // In auto-retain/release, infer strong retension for variables of
  5328. // retainable type.
  5329. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5330. NewVD->setInvalidDecl();
  5331. // Handle GNU asm-label extension (encoded as an attribute).
  5332. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5333. // The parser guarantees this is a string.
  5334. StringLiteral *SE = cast<StringLiteral>(E);
  5335. StringRef Label = SE->getString();
  5336. if (S->getFnParent() != nullptr) {
  5337. switch (SC) {
  5338. case SC_None:
  5339. case SC_Auto:
  5340. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5341. break;
  5342. case SC_Register:
  5343. // Local Named register
  5344. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  5345. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5346. break;
  5347. case SC_Static:
  5348. case SC_Extern:
  5349. case SC_PrivateExtern:
  5350. case SC_OpenCLWorkGroupLocal:
  5351. break;
  5352. }
  5353. } else if (SC == SC_Register) {
  5354. // Global Named register
  5355. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  5356. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5357. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5358. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5359. NewVD->setInvalidDecl(true);
  5360. }
  5361. }
  5362. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  5363. Context, Label, 0));
  5364. } else if (!ExtnameUndeclaredIdentifiers.empty() &&
  5365. isDeclTUScopedExternallyVisible(NewVD)) {
  5366. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5367. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  5368. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5369. NewVD->addAttr(I->second);
  5370. ExtnameUndeclaredIdentifiers.erase(I);
  5371. }
  5372. }
  5373. // Diagnose shadowed variables before filtering for scope.
  5374. if (D.getCXXScopeSpec().isEmpty())
  5375. CheckShadow(S, NewVD, Previous);
  5376. // Don't consider existing declarations that are in a different
  5377. // scope and are out-of-semantic-context declarations (if the new
  5378. // declaration has linkage).
  5379. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  5380. D.getCXXScopeSpec().isNotEmpty() ||
  5381. IsExplicitSpecialization ||
  5382. IsVariableTemplateSpecialization);
  5383. // Check whether the previous declaration is in the same block scope. This
  5384. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  5385. if (getLangOpts().CPlusPlus &&
  5386. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  5387. NewVD->setPreviousDeclInSameBlockScope(
  5388. Previous.isSingleResult() && !Previous.isShadowed() &&
  5389. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  5390. if (!getLangOpts().CPlusPlus) {
  5391. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5392. } else {
  5393. // If this is an explicit specialization of a static data member, check it.
  5394. if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
  5395. CheckMemberSpecialization(NewVD, Previous))
  5396. NewVD->setInvalidDecl();
  5397. // Merge the decl with the existing one if appropriate.
  5398. if (!Previous.empty()) {
  5399. if (Previous.isSingleResult() &&
  5400. isa<FieldDecl>(Previous.getFoundDecl()) &&
  5401. D.getCXXScopeSpec().isSet()) {
  5402. // The user tried to define a non-static data member
  5403. // out-of-line (C++ [dcl.meaning]p1).
  5404. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  5405. << D.getCXXScopeSpec().getRange();
  5406. Previous.clear();
  5407. NewVD->setInvalidDecl();
  5408. }
  5409. } else if (D.getCXXScopeSpec().isSet()) {
  5410. // No previous declaration in the qualifying scope.
  5411. Diag(D.getIdentifierLoc(), diag::err_no_member)
  5412. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  5413. << D.getCXXScopeSpec().getRange();
  5414. NewVD->setInvalidDecl();
  5415. }
  5416. if (!IsVariableTemplateSpecialization)
  5417. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous, MergeState)); // HLSL Change - add merge state
  5418. if (NewTemplate) {
  5419. VarTemplateDecl *PrevVarTemplate =
  5420. NewVD->getPreviousDecl()
  5421. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  5422. : nullptr;
  5423. // Check the template parameter list of this declaration, possibly
  5424. // merging in the template parameter list from the previous variable
  5425. // template declaration.
  5426. if (CheckTemplateParameterList(
  5427. TemplateParams,
  5428. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  5429. : nullptr,
  5430. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  5431. DC->isDependentContext())
  5432. ? TPC_ClassTemplateMember
  5433. : TPC_VarTemplate))
  5434. NewVD->setInvalidDecl();
  5435. // If we are providing an explicit specialization of a static variable
  5436. // template, make a note of that.
  5437. if (PrevVarTemplate &&
  5438. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  5439. PrevVarTemplate->setMemberSpecialization();
  5440. }
  5441. }
  5442. ProcessPragmaWeak(S, NewVD);
  5443. // If this is the first declaration of an extern C variable, update
  5444. // the map of such variables.
  5445. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  5446. isIncompleteDeclExternC(*this, NewVD))
  5447. RegisterLocallyScopedExternCDecl(NewVD, S);
  5448. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  5449. Decl *ManglingContextDecl;
  5450. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  5451. NewVD->getDeclContext(), ManglingContextDecl)) {
  5452. Context.setManglingNumber(
  5453. NewVD, MCtx->getManglingNumber(
  5454. NewVD, getMSManglingNumber(getLangOpts(), S)));
  5455. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  5456. }
  5457. }
  5458. if (D.isRedeclaration() && !Previous.empty()) {
  5459. checkDLLAttributeRedeclaration(
  5460. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  5461. IsExplicitSpecialization);
  5462. }
  5463. if (NewTemplate) {
  5464. if (NewVD->isInvalidDecl())
  5465. NewTemplate->setInvalidDecl();
  5466. ActOnDocumentableDecl(NewTemplate);
  5467. return NewTemplate;
  5468. }
  5469. return NewVD;
  5470. }
  5471. /// \brief Diagnose variable or built-in function shadowing. Implements
  5472. /// -Wshadow.
  5473. ///
  5474. /// This method is called whenever a VarDecl is added to a "useful"
  5475. /// scope.
  5476. ///
  5477. /// \param S the scope in which the shadowing name is being declared
  5478. /// \param R the lookup of the name
  5479. ///
  5480. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  5481. // Return if warning is ignored.
  5482. if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
  5483. return;
  5484. // Don't diagnose declarations at file scope.
  5485. if (D->hasGlobalStorage())
  5486. return;
  5487. DeclContext *NewDC = D->getDeclContext();
  5488. // Only diagnose if we're shadowing an unambiguous field or variable.
  5489. if (R.getResultKind() != LookupResult::Found)
  5490. return;
  5491. NamedDecl* ShadowedDecl = R.getFoundDecl();
  5492. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  5493. return;
  5494. // Fields are not shadowed by variables in C++ static methods.
  5495. if (isa<FieldDecl>(ShadowedDecl))
  5496. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  5497. if (MD->isStatic())
  5498. return;
  5499. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  5500. if (shadowedVar->isExternC()) {
  5501. // For shadowing external vars, make sure that we point to the global
  5502. // declaration, not a locally scoped extern declaration.
  5503. for (auto I : shadowedVar->redecls())
  5504. if (I->isFileVarDecl()) {
  5505. ShadowedDecl = I;
  5506. break;
  5507. }
  5508. }
  5509. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  5510. // Only warn about certain kinds of shadowing for class members.
  5511. if (NewDC && NewDC->isRecord()) {
  5512. // In particular, don't warn about shadowing non-class members.
  5513. if (!OldDC->isRecord())
  5514. return;
  5515. // TODO: should we warn about static data members shadowing
  5516. // static data members from base classes?
  5517. // TODO: don't diagnose for inaccessible shadowed members.
  5518. // This is hard to do perfectly because we might friend the
  5519. // shadowing context, but that's just a false negative.
  5520. }
  5521. // Determine what kind of declaration we're shadowing.
  5522. unsigned Kind;
  5523. if (isa<RecordDecl>(OldDC)) {
  5524. if (isa<FieldDecl>(ShadowedDecl))
  5525. Kind = 3; // field
  5526. else
  5527. Kind = 2; // static data member
  5528. } else if (OldDC->isFileContext())
  5529. Kind = 1; // global
  5530. else
  5531. Kind = 0; // local
  5532. DeclarationName Name = R.getLookupName();
  5533. // Emit warning and note.
  5534. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  5535. return;
  5536. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  5537. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  5538. }
  5539. /// \brief Check -Wshadow without the advantage of a previous lookup.
  5540. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  5541. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  5542. return;
  5543. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  5544. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  5545. LookupName(R, S);
  5546. CheckShadow(S, D, R);
  5547. }
  5548. /// Check for conflict between this global or extern "C" declaration and
  5549. /// previous global or extern "C" declarations. This is only used in C++.
  5550. template<typename T>
  5551. static bool checkGlobalOrExternCConflict(
  5552. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  5553. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  5554. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  5555. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  5556. // The common case: this global doesn't conflict with any extern "C"
  5557. // declaration.
  5558. return false;
  5559. }
  5560. if (Prev) {
  5561. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  5562. // Both the old and new declarations have C language linkage. This is a
  5563. // redeclaration.
  5564. Previous.clear();
  5565. Previous.addDecl(Prev);
  5566. return true;
  5567. }
  5568. // This is a global, non-extern "C" declaration, and there is a previous
  5569. // non-global extern "C" declaration. Diagnose if this is a variable
  5570. // declaration.
  5571. if (!isa<VarDecl>(ND))
  5572. return false;
  5573. } else {
  5574. // The declaration is extern "C". Check for any declaration in the
  5575. // translation unit which might conflict.
  5576. if (IsGlobal) {
  5577. // We have already performed the lookup into the translation unit.
  5578. IsGlobal = false;
  5579. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  5580. I != E; ++I) {
  5581. if (isa<VarDecl>(*I)) {
  5582. Prev = *I;
  5583. break;
  5584. }
  5585. }
  5586. } else {
  5587. DeclContext::lookup_result R =
  5588. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  5589. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  5590. I != E; ++I) {
  5591. if (isa<VarDecl>(*I)) {
  5592. Prev = *I;
  5593. break;
  5594. }
  5595. // FIXME: If we have any other entity with this name in global scope,
  5596. // the declaration is ill-formed, but that is a defect: it breaks the
  5597. // 'stat' hack, for instance. Only variables can have mangled name
  5598. // clashes with extern "C" declarations, so only they deserve a
  5599. // diagnostic.
  5600. }
  5601. }
  5602. if (!Prev)
  5603. return false;
  5604. }
  5605. // Use the first declaration's location to ensure we point at something which
  5606. // is lexically inside an extern "C" linkage-spec.
  5607. assert(Prev && "should have found a previous declaration to diagnose");
  5608. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  5609. Prev = FD->getFirstDecl();
  5610. else
  5611. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  5612. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  5613. << IsGlobal << ND;
  5614. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  5615. << IsGlobal;
  5616. return false;
  5617. }
  5618. /// Apply special rules for handling extern "C" declarations. Returns \c true
  5619. /// if we have found that this is a redeclaration of some prior entity.
  5620. ///
  5621. /// Per C++ [dcl.link]p6:
  5622. /// Two declarations [for a function or variable] with C language linkage
  5623. /// with the same name that appear in different scopes refer to the same
  5624. /// [entity]. An entity with C language linkage shall not be declared with
  5625. /// the same name as an entity in global scope.
  5626. template<typename T>
  5627. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  5628. LookupResult &Previous) {
  5629. if (!S.getLangOpts().CPlusPlus) {
  5630. // In C, when declaring a global variable, look for a corresponding 'extern'
  5631. // variable declared in function scope. We don't need this in C++, because
  5632. // we find local extern decls in the surrounding file-scope DeclContext.
  5633. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5634. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  5635. Previous.clear();
  5636. Previous.addDecl(Prev);
  5637. return true;
  5638. }
  5639. }
  5640. return false;
  5641. }
  5642. // A declaration in the translation unit can conflict with an extern "C"
  5643. // declaration.
  5644. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  5645. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  5646. // An extern "C" declaration can conflict with a declaration in the
  5647. // translation unit or can be a redeclaration of an extern "C" declaration
  5648. // in another scope.
  5649. if (isIncompleteDeclExternC(S,ND))
  5650. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  5651. // Neither global nor extern "C": nothing to do.
  5652. return false;
  5653. }
  5654. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  5655. // If the decl is already known invalid, don't check it.
  5656. if (NewVD->isInvalidDecl())
  5657. return;
  5658. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  5659. QualType T = TInfo->getType();
  5660. // Defer checking an 'auto' type until its initializer is attached.
  5661. if (T->isUndeducedType())
  5662. return;
  5663. if (NewVD->hasAttrs())
  5664. CheckAlignasUnderalignment(NewVD);
  5665. if (T->isObjCObjectType()) {
  5666. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  5667. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  5668. T = Context.getObjCObjectPointerType(T);
  5669. NewVD->setType(T);
  5670. }
  5671. // Emit an error if an address space was applied to decl with local storage.
  5672. // This includes arrays of objects with address space qualifiers, but not
  5673. // automatic variables that point to other address spaces.
  5674. // ISO/IEC TR 18037 S5.1.2
  5675. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  5676. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  5677. NewVD->setInvalidDecl();
  5678. return;
  5679. }
  5680. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  5681. // __constant address space.
  5682. if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
  5683. && T.getAddressSpace() != LangAS::opencl_constant
  5684. && !T->isSamplerT()){
  5685. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
  5686. NewVD->setInvalidDecl();
  5687. return;
  5688. }
  5689. // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
  5690. // scope.
  5691. if ((getLangOpts().OpenCLVersion >= 120)
  5692. && NewVD->isStaticLocal()) {
  5693. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  5694. NewVD->setInvalidDecl();
  5695. return;
  5696. }
  5697. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  5698. && !NewVD->hasAttr<BlocksAttr>()) {
  5699. if (getLangOpts().getGC() != LangOptions::NonGC)
  5700. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  5701. else {
  5702. assert(!getLangOpts().ObjCAutoRefCount);
  5703. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  5704. }
  5705. }
  5706. bool isVM = T->isVariablyModifiedType();
  5707. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  5708. NewVD->hasAttr<BlocksAttr>())
  5709. getCurFunction()->setHasBranchProtectedScope();
  5710. if ((isVM && NewVD->hasLinkage()) ||
  5711. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  5712. bool SizeIsNegative;
  5713. llvm::APSInt Oversized;
  5714. TypeSourceInfo *FixedTInfo =
  5715. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5716. SizeIsNegative, Oversized);
  5717. if (!FixedTInfo && T->isVariableArrayType()) {
  5718. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  5719. // FIXME: This won't give the correct result for
  5720. // int a[10][n];
  5721. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  5722. if (NewVD->isFileVarDecl())
  5723. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  5724. << SizeRange;
  5725. else if (NewVD->isStaticLocal())
  5726. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  5727. << SizeRange;
  5728. else
  5729. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  5730. << SizeRange;
  5731. NewVD->setInvalidDecl();
  5732. return;
  5733. }
  5734. if (!FixedTInfo) {
  5735. if (NewVD->isFileVarDecl())
  5736. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  5737. else
  5738. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  5739. NewVD->setInvalidDecl();
  5740. return;
  5741. }
  5742. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  5743. NewVD->setType(FixedTInfo->getType());
  5744. NewVD->setTypeSourceInfo(FixedTInfo);
  5745. }
  5746. if (T->isVoidType()) {
  5747. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  5748. // of objects and functions.
  5749. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  5750. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  5751. << T;
  5752. NewVD->setInvalidDecl();
  5753. return;
  5754. }
  5755. }
  5756. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  5757. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  5758. NewVD->setInvalidDecl();
  5759. return;
  5760. }
  5761. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  5762. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  5763. NewVD->setInvalidDecl();
  5764. return;
  5765. }
  5766. if (NewVD->isConstexpr() && !T->isDependentType() &&
  5767. RequireLiteralType(NewVD->getLocation(), T,
  5768. diag::err_constexpr_var_non_literal)) {
  5769. NewVD->setInvalidDecl();
  5770. return;
  5771. }
  5772. }
  5773. /// \brief Perform semantic checking on a newly-created variable
  5774. /// declaration.
  5775. ///
  5776. /// This routine performs all of the type-checking required for a
  5777. /// variable declaration once it has been built. It is used both to
  5778. /// check variables after they have been parsed and their declarators
  5779. /// have been translated into a declaration, and to check variables
  5780. /// that have been instantiated from a template.
  5781. ///
  5782. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  5783. ///
  5784. /// Returns true if the variable declaration is a redeclaration.
  5785. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous, ShadowMergeState MergeState) { // HLSL Change - add merge state
  5786. CheckVariableDeclarationType(NewVD);
  5787. // If the decl is already known invalid, don't check it.
  5788. if (NewVD->isInvalidDecl())
  5789. return false;
  5790. // If we did not find anything by this name, look for a non-visible
  5791. // extern "C" declaration with the same name.
  5792. if (Previous.empty() &&
  5793. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  5794. Previous.setShadowed();
  5795. // Filter out any non-conflicting previous declarations.
  5796. filterNonConflictingPreviousDecls(*this, NewVD, Previous);
  5797. if (!Previous.empty()) {
  5798. MergeVarDecl(NewVD, Previous, MergeState); // HLSL Change - add merge state
  5799. return true;
  5800. }
  5801. return false;
  5802. }
  5803. /// \brief Data used with FindOverriddenMethod
  5804. struct FindOverriddenMethodData {
  5805. Sema *S;
  5806. CXXMethodDecl *Method;
  5807. };
  5808. /// \brief Member lookup function that determines whether a given C++
  5809. /// method overrides a method in a base class, to be used with
  5810. /// CXXRecordDecl::lookupInBases().
  5811. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  5812. CXXBasePath &Path,
  5813. void *UserData) {
  5814. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  5815. FindOverriddenMethodData *Data
  5816. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  5817. DeclarationName Name = Data->Method->getDeclName();
  5818. // FIXME: Do we care about other names here too?
  5819. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  5820. // We really want to find the base class destructor here.
  5821. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  5822. CanQualType CT = Data->S->Context.getCanonicalType(T);
  5823. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  5824. }
  5825. for (Path.Decls = BaseRecord->lookup(Name);
  5826. !Path.Decls.empty();
  5827. Path.Decls = Path.Decls.slice(1)) {
  5828. NamedDecl *D = Path.Decls.front();
  5829. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  5830. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  5831. return true;
  5832. }
  5833. }
  5834. return false;
  5835. }
  5836. namespace {
  5837. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  5838. }
  5839. /// \brief Report an error regarding overriding, along with any relevant
  5840. /// overriden methods.
  5841. ///
  5842. /// \param DiagID the primary error to report.
  5843. /// \param MD the overriding method.
  5844. /// \param OEK which overrides to include as notes.
  5845. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  5846. OverrideErrorKind OEK = OEK_All) {
  5847. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  5848. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5849. E = MD->end_overridden_methods();
  5850. I != E; ++I) {
  5851. // This check (& the OEK parameter) could be replaced by a predicate, but
  5852. // without lambdas that would be overkill. This is still nicer than writing
  5853. // out the diag loop 3 times.
  5854. if ((OEK == OEK_All) ||
  5855. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  5856. (OEK == OEK_Deleted && (*I)->isDeleted()))
  5857. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  5858. }
  5859. }
  5860. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  5861. /// and if so, check that it's a valid override and remember it.
  5862. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  5863. // Look for methods in base classes that this method might override.
  5864. CXXBasePaths Paths;
  5865. FindOverriddenMethodData Data;
  5866. Data.Method = MD;
  5867. Data.S = this;
  5868. bool hasDeletedOverridenMethods = false;
  5869. bool hasNonDeletedOverridenMethods = false;
  5870. bool AddedAny = false;
  5871. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  5872. for (auto *I : Paths.found_decls()) {
  5873. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  5874. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  5875. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  5876. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  5877. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  5878. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  5879. hasDeletedOverridenMethods |= OldMD->isDeleted();
  5880. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  5881. AddedAny = true;
  5882. }
  5883. }
  5884. }
  5885. }
  5886. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  5887. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  5888. }
  5889. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  5890. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  5891. }
  5892. return AddedAny;
  5893. }
  5894. namespace {
  5895. // Struct for holding all of the extra arguments needed by
  5896. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  5897. struct ActOnFDArgs {
  5898. Scope *S;
  5899. Declarator &D;
  5900. MultiTemplateParamsArg TemplateParamLists;
  5901. bool AddToScope;
  5902. };
  5903. }
  5904. namespace {
  5905. // Callback to only accept typo corrections that have a non-zero edit distance.
  5906. // Also only accept corrections that have the same parent decl.
  5907. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  5908. public:
  5909. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  5910. CXXRecordDecl *Parent)
  5911. : Context(Context), OriginalFD(TypoFD),
  5912. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  5913. bool ValidateCandidate(const TypoCorrection &candidate) override {
  5914. if (candidate.getEditDistance() == 0)
  5915. return false;
  5916. SmallVector<unsigned, 1> MismatchedParams;
  5917. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  5918. CDeclEnd = candidate.end();
  5919. CDecl != CDeclEnd; ++CDecl) {
  5920. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  5921. if (FD && !FD->hasBody() &&
  5922. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  5923. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  5924. CXXRecordDecl *Parent = MD->getParent();
  5925. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  5926. return true;
  5927. } else if (!ExpectedParent) {
  5928. return true;
  5929. }
  5930. }
  5931. }
  5932. return false;
  5933. }
  5934. private:
  5935. ASTContext &Context;
  5936. FunctionDecl *OriginalFD;
  5937. CXXRecordDecl *ExpectedParent;
  5938. };
  5939. }
  5940. /// \brief Generate diagnostics for an invalid function redeclaration.
  5941. ///
  5942. /// This routine handles generating the diagnostic messages for an invalid
  5943. /// function redeclaration, including finding possible similar declarations
  5944. /// or performing typo correction if there are no previous declarations with
  5945. /// the same name.
  5946. ///
  5947. /// Returns a NamedDecl iff typo correction was performed and substituting in
  5948. /// the new declaration name does not cause new errors.
  5949. static NamedDecl *DiagnoseInvalidRedeclaration(
  5950. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  5951. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  5952. DeclarationName Name = NewFD->getDeclName();
  5953. DeclContext *NewDC = NewFD->getDeclContext();
  5954. SmallVector<unsigned, 1> MismatchedParams;
  5955. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  5956. TypoCorrection Correction;
  5957. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  5958. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  5959. : diag::err_member_decl_does_not_match;
  5960. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  5961. IsLocalFriend ? Sema::LookupLocalFriendName
  5962. : Sema::LookupOrdinaryName,
  5963. Sema::ForRedeclaration);
  5964. NewFD->setInvalidDecl();
  5965. if (IsLocalFriend)
  5966. SemaRef.LookupName(Prev, S);
  5967. else
  5968. SemaRef.LookupQualifiedName(Prev, NewDC);
  5969. assert(!Prev.isAmbiguous() &&
  5970. "Cannot have an ambiguity in previous-declaration lookup");
  5971. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  5972. if (!Prev.empty()) {
  5973. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  5974. Func != FuncEnd; ++Func) {
  5975. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  5976. if (FD &&
  5977. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  5978. // Add 1 to the index so that 0 can mean the mismatch didn't
  5979. // involve a parameter
  5980. unsigned ParamNum =
  5981. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  5982. NearMatches.push_back(std::make_pair(FD, ParamNum));
  5983. }
  5984. }
  5985. // If the qualified name lookup yielded nothing, try typo correction
  5986. } else if ((Correction = SemaRef.CorrectTypo(
  5987. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  5988. &ExtraArgs.D.getCXXScopeSpec(),
  5989. llvm::make_unique<DifferentNameValidatorCCC>(
  5990. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  5991. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  5992. // Set up everything for the call to ActOnFunctionDeclarator
  5993. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  5994. ExtraArgs.D.getIdentifierLoc());
  5995. Previous.clear();
  5996. Previous.setLookupName(Correction.getCorrection());
  5997. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  5998. CDeclEnd = Correction.end();
  5999. CDecl != CDeclEnd; ++CDecl) {
  6000. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6001. if (FD && !FD->hasBody() &&
  6002. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6003. Previous.addDecl(FD);
  6004. }
  6005. }
  6006. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6007. NamedDecl *Result;
  6008. // Retry building the function declaration with the new previous
  6009. // declarations, and with errors suppressed.
  6010. {
  6011. // Trap errors.
  6012. Sema::SFINAETrap Trap(SemaRef);
  6013. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6014. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6015. // eliminate the need for the parameter pack ExtraArgs.
  6016. Result = SemaRef.ActOnFunctionDeclarator(
  6017. ExtraArgs.S, ExtraArgs.D,
  6018. Correction.getCorrectionDecl()->getDeclContext(),
  6019. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6020. ExtraArgs.AddToScope);
  6021. if (Trap.hasErrorOccurred())
  6022. Result = nullptr;
  6023. }
  6024. if (Result) {
  6025. // Determine which correction we picked.
  6026. Decl *Canonical = Result->getCanonicalDecl();
  6027. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6028. I != E; ++I)
  6029. if ((*I)->getCanonicalDecl() == Canonical)
  6030. Correction.setCorrectionDecl(*I);
  6031. SemaRef.diagnoseTypo(
  6032. Correction,
  6033. SemaRef.PDiag(IsLocalFriend
  6034. ? diag::err_no_matching_local_friend_suggest
  6035. : diag::err_member_decl_does_not_match_suggest)
  6036. << Name << NewDC << IsDefinition);
  6037. return Result;
  6038. }
  6039. // Pretend the typo correction never occurred
  6040. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6041. ExtraArgs.D.getIdentifierLoc());
  6042. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6043. Previous.clear();
  6044. Previous.setLookupName(Name);
  6045. }
  6046. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6047. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6048. bool NewFDisConst = false;
  6049. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6050. NewFDisConst = NewMD->isConst();
  6051. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6052. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6053. NearMatch != NearMatchEnd; ++NearMatch) {
  6054. FunctionDecl *FD = NearMatch->first;
  6055. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6056. bool FDisConst = MD && MD->isConst();
  6057. bool IsMember = MD || !IsLocalFriend;
  6058. // FIXME: These notes are poorly worded for the local friend case.
  6059. if (unsigned Idx = NearMatch->second) {
  6060. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6061. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6062. if (Loc.isInvalid()) Loc = FD->getLocation();
  6063. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6064. : diag::note_local_decl_close_param_match)
  6065. << Idx << FDParam->getType()
  6066. << NewFD->getParamDecl(Idx - 1)->getType();
  6067. } else if (FDisConst != NewFDisConst) {
  6068. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6069. << NewFDisConst << FD->getSourceRange().getEnd();
  6070. } else
  6071. SemaRef.Diag(FD->getLocation(),
  6072. IsMember ? diag::note_member_def_close_match
  6073. : diag::note_local_decl_close_match);
  6074. }
  6075. return nullptr;
  6076. }
  6077. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6078. switch (D.getDeclSpec().getStorageClassSpec()) {
  6079. default: llvm_unreachable("Unknown storage class!");
  6080. case DeclSpec::SCS_auto:
  6081. case DeclSpec::SCS_register:
  6082. case DeclSpec::SCS_mutable:
  6083. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6084. diag::err_typecheck_sclass_func);
  6085. D.setInvalidType();
  6086. break;
  6087. case DeclSpec::SCS_unspecified: break;
  6088. case DeclSpec::SCS_extern:
  6089. if (D.getDeclSpec().isExternInLinkageSpec())
  6090. return SC_None;
  6091. return SC_Extern;
  6092. case DeclSpec::SCS_static: {
  6093. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6094. // C99 6.7.1p5:
  6095. // The declaration of an identifier for a function that has
  6096. // block scope shall have no explicit storage-class specifier
  6097. // other than extern
  6098. // See also (C++ [dcl.stc]p4).
  6099. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6100. diag::err_static_block_func);
  6101. break;
  6102. } else
  6103. return SC_Static;
  6104. }
  6105. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6106. }
  6107. // No explicit storage class has already been returned
  6108. return SC_None;
  6109. }
  6110. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6111. DeclContext *DC, QualType &R,
  6112. TypeSourceInfo *TInfo,
  6113. StorageClass SC,
  6114. bool &IsVirtualOkay) {
  6115. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6116. DeclarationName Name = NameInfo.getName();
  6117. FunctionDecl *NewFD = nullptr;
  6118. bool isInline = D.getDeclSpec().isInlineSpecified();
  6119. if (!SemaRef.getLangOpts().CPlusPlus) {
  6120. // Determine whether the function was written with a
  6121. // prototype. This true when:
  6122. // - there is a prototype in the declarator, or
  6123. // - the type R of the function is some kind of typedef or other reference
  6124. // to a type name (which eventually refers to a function type).
  6125. bool HasPrototype =
  6126. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  6127. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  6128. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  6129. D.getLocStart(), NameInfo, R,
  6130. TInfo, SC, isInline,
  6131. HasPrototype, false);
  6132. if (D.isInvalidType())
  6133. NewFD->setInvalidDecl();
  6134. return NewFD;
  6135. }
  6136. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6137. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6138. // Check that the return type is not an abstract class type.
  6139. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6140. // the class has been completely parsed.
  6141. if (!DC->isRecord() &&
  6142. SemaRef.RequireNonAbstractType(
  6143. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  6144. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  6145. D.setInvalidType();
  6146. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  6147. // This is a C++ constructor declaration.
  6148. assert(DC->isRecord() &&
  6149. "Constructors can only be declared in a member context");
  6150. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  6151. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6152. D.getLocStart(), NameInfo,
  6153. R, TInfo, isExplicit, isInline,
  6154. /*isImplicitlyDeclared=*/false,
  6155. isConstexpr);
  6156. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6157. // This is a C++ destructor declaration.
  6158. if (DC->isRecord()) {
  6159. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  6160. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  6161. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  6162. SemaRef.Context, Record,
  6163. D.getLocStart(),
  6164. NameInfo, R, TInfo, isInline,
  6165. /*isImplicitlyDeclared=*/false);
  6166. // If the class is complete, then we now create the implicit exception
  6167. // specification. If the class is incomplete or dependent, we can't do
  6168. // it yet.
  6169. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  6170. Record->getDefinition() && !Record->isBeingDefined() &&
  6171. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  6172. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  6173. }
  6174. IsVirtualOkay = true;
  6175. return NewDD;
  6176. } else {
  6177. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  6178. D.setInvalidType();
  6179. // Create a FunctionDecl to satisfy the function definition parsing
  6180. // code path.
  6181. return FunctionDecl::Create(SemaRef.Context, DC,
  6182. D.getLocStart(),
  6183. D.getIdentifierLoc(), Name, R, TInfo,
  6184. SC, isInline,
  6185. /*hasPrototype=*/true, isConstexpr);
  6186. }
  6187. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  6188. if (!DC->isRecord()) {
  6189. SemaRef.Diag(D.getIdentifierLoc(),
  6190. diag::err_conv_function_not_member);
  6191. return nullptr;
  6192. }
  6193. SemaRef.CheckConversionDeclarator(D, R, SC);
  6194. IsVirtualOkay = true;
  6195. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6196. D.getLocStart(), NameInfo,
  6197. R, TInfo, isInline, isExplicit,
  6198. isConstexpr, SourceLocation());
  6199. } else if (DC->isRecord()) {
  6200. // If the name of the function is the same as the name of the record,
  6201. // then this must be an invalid constructor that has a return type.
  6202. // (The parser checks for a return type and makes the declarator a
  6203. // constructor if it has no return type).
  6204. if (Name.getAsIdentifierInfo() &&
  6205. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  6206. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  6207. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6208. << SourceRange(D.getIdentifierLoc());
  6209. return nullptr;
  6210. }
  6211. // This is a C++ method declaration.
  6212. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  6213. cast<CXXRecordDecl>(DC),
  6214. D.getLocStart(), NameInfo, R,
  6215. TInfo, SC, isInline,
  6216. isConstexpr, SourceLocation());
  6217. IsVirtualOkay = !Ret->isStatic();
  6218. return Ret;
  6219. } else {
  6220. bool isFriend =
  6221. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  6222. if (!isFriend && SemaRef.CurContext->isRecord())
  6223. return nullptr;
  6224. // Determine whether the function was written with a
  6225. // prototype. This true when:
  6226. // - we're in C++ (where every function has a prototype),
  6227. return FunctionDecl::Create(SemaRef.Context, DC,
  6228. D.getLocStart(),
  6229. NameInfo, R, TInfo, SC, isInline,
  6230. true/*HasPrototype*/, isConstexpr);
  6231. }
  6232. }
  6233. enum OpenCLParamType {
  6234. ValidKernelParam,
  6235. PtrPtrKernelParam,
  6236. PtrKernelParam,
  6237. PrivatePtrKernelParam,
  6238. InvalidKernelParam,
  6239. RecordKernelParam
  6240. };
  6241. static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
  6242. if (PT->isPointerType()) {
  6243. QualType PointeeType = PT->getPointeeType();
  6244. if (PointeeType->isPointerType())
  6245. return PtrPtrKernelParam;
  6246. return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
  6247. : PtrKernelParam;
  6248. }
  6249. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  6250. // be used as builtin types.
  6251. if (PT->isImageType())
  6252. return PtrKernelParam;
  6253. if (PT->isBooleanType())
  6254. return InvalidKernelParam;
  6255. if (PT->isEventT())
  6256. return InvalidKernelParam;
  6257. if (PT->isHalfType())
  6258. return InvalidKernelParam;
  6259. if (PT->isRecordType())
  6260. return RecordKernelParam;
  6261. return ValidKernelParam;
  6262. }
  6263. static void checkIsValidOpenCLKernelParameter(
  6264. Sema &S,
  6265. Declarator &D,
  6266. ParmVarDecl *Param,
  6267. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  6268. QualType PT = Param->getType();
  6269. // Cache the valid types we encounter to avoid rechecking structs that are
  6270. // used again
  6271. if (ValidTypes.count(PT.getTypePtr()))
  6272. return;
  6273. switch (getOpenCLKernelParameterType(PT)) {
  6274. case PtrPtrKernelParam:
  6275. // OpenCL v1.2 s6.9.a:
  6276. // A kernel function argument cannot be declared as a
  6277. // pointer to a pointer type.
  6278. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  6279. D.setInvalidType();
  6280. return;
  6281. case PrivatePtrKernelParam:
  6282. // OpenCL v1.2 s6.9.a:
  6283. // A kernel function argument cannot be declared as a
  6284. // pointer to the private address space.
  6285. S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
  6286. D.setInvalidType();
  6287. return;
  6288. // OpenCL v1.2 s6.9.k:
  6289. // Arguments to kernel functions in a program cannot be declared with the
  6290. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  6291. // uintptr_t or a struct and/or union that contain fields declared to be
  6292. // one of these built-in scalar types.
  6293. case InvalidKernelParam:
  6294. // OpenCL v1.2 s6.8 n:
  6295. // A kernel function argument cannot be declared
  6296. // of event_t type.
  6297. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6298. D.setInvalidType();
  6299. return;
  6300. case PtrKernelParam:
  6301. case ValidKernelParam:
  6302. ValidTypes.insert(PT.getTypePtr());
  6303. return;
  6304. case RecordKernelParam:
  6305. break;
  6306. }
  6307. // Track nested structs we will inspect
  6308. SmallVector<const Decl *, 4> VisitStack;
  6309. // Track where we are in the nested structs. Items will migrate from
  6310. // VisitStack to HistoryStack as we do the DFS for bad field.
  6311. SmallVector<const FieldDecl *, 4> HistoryStack;
  6312. HistoryStack.push_back(nullptr);
  6313. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  6314. VisitStack.push_back(PD);
  6315. assert(VisitStack.back() && "First decl null?");
  6316. do {
  6317. const Decl *Next = VisitStack.pop_back_val();
  6318. if (!Next) {
  6319. assert(!HistoryStack.empty());
  6320. // Found a marker, we have gone up a level
  6321. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  6322. ValidTypes.insert(Hist->getType().getTypePtr());
  6323. continue;
  6324. }
  6325. // Adds everything except the original parameter declaration (which is not a
  6326. // field itself) to the history stack.
  6327. const RecordDecl *RD;
  6328. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  6329. HistoryStack.push_back(Field);
  6330. RD = Field->getType()->castAs<RecordType>()->getDecl();
  6331. } else {
  6332. RD = cast<RecordDecl>(Next);
  6333. }
  6334. // Add a null marker so we know when we've gone back up a level
  6335. VisitStack.push_back(nullptr);
  6336. for (const auto *FD : RD->fields()) {
  6337. QualType QT = FD->getType();
  6338. if (ValidTypes.count(QT.getTypePtr()))
  6339. continue;
  6340. OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
  6341. if (ParamType == ValidKernelParam)
  6342. continue;
  6343. if (ParamType == RecordKernelParam) {
  6344. VisitStack.push_back(FD);
  6345. continue;
  6346. }
  6347. // OpenCL v1.2 s6.9.p:
  6348. // Arguments to kernel functions that are declared to be a struct or union
  6349. // do not allow OpenCL objects to be passed as elements of the struct or
  6350. // union.
  6351. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  6352. ParamType == PrivatePtrKernelParam) {
  6353. S.Diag(Param->getLocation(),
  6354. diag::err_record_with_pointers_kernel_param)
  6355. << PT->isUnionType()
  6356. << PT;
  6357. } else {
  6358. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6359. }
  6360. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  6361. << PD->getDeclName();
  6362. // We have an error, now let's go back up through history and show where
  6363. // the offending field came from
  6364. for (ArrayRef<const FieldDecl *>::const_iterator
  6365. I = HistoryStack.begin() + 1,
  6366. E = HistoryStack.end();
  6367. I != E; ++I) {
  6368. const FieldDecl *OuterField = *I;
  6369. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  6370. << OuterField->getType();
  6371. }
  6372. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  6373. << QT->isPointerType()
  6374. << QT;
  6375. D.setInvalidType();
  6376. return;
  6377. }
  6378. } while (!VisitStack.empty());
  6379. }
  6380. NamedDecl*
  6381. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  6382. TypeSourceInfo *TInfo, LookupResult &Previous,
  6383. MultiTemplateParamsArg TemplateParamLists,
  6384. bool &AddToScope) {
  6385. QualType R = TInfo->getType();
  6386. assert(R.getTypePtr()->isFunctionType());
  6387. // TODO: consider using NameInfo for diagnostic.
  6388. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  6389. DeclarationName Name = NameInfo.getName();
  6390. StorageClass SC = getFunctionStorageClass(*this, D);
  6391. // HLSL Change - reject 'extern' functions
  6392. if (getLangOpts().HLSL && SC == SC_Extern) {
  6393. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'" << "function";
  6394. }
  6395. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  6396. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6397. diag::err_invalid_thread)
  6398. << DeclSpec::getSpecifierName(TSCS);
  6399. if (D.isFirstDeclarationOfMember())
  6400. adjustMemberFunctionCC(R, D.isStaticMember());
  6401. bool isFriend = false;
  6402. FunctionTemplateDecl *FunctionTemplate = nullptr;
  6403. bool isExplicitSpecialization = false;
  6404. bool isFunctionTemplateSpecialization = false;
  6405. bool isDependentClassScopeExplicitSpecialization = false;
  6406. bool HasExplicitTemplateArgs = false;
  6407. TemplateArgumentListInfo TemplateArgs;
  6408. bool isVirtualOkay = false;
  6409. DeclContext *OriginalDC = DC;
  6410. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  6411. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  6412. isVirtualOkay);
  6413. if (!NewFD) return nullptr;
  6414. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  6415. NewFD->setTopLevelDeclInObjCContainer();
  6416. // Set the lexical context. If this is a function-scope declaration, or has a
  6417. // C++ scope specifier, or is the object of a friend declaration, the lexical
  6418. // context will be different from the semantic context.
  6419. NewFD->setLexicalDeclContext(CurContext);
  6420. if (IsLocalExternDecl)
  6421. NewFD->setLocalExternDecl();
  6422. if (getLangOpts().CPlusPlus) {
  6423. bool isInline = D.getDeclSpec().isInlineSpecified();
  6424. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  6425. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6426. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6427. isFriend = D.getDeclSpec().isFriendSpecified();
  6428. if (isFriend && !isInline && D.isFunctionDefinition()) {
  6429. // C++ [class.friend]p5
  6430. // A function can be defined in a friend declaration of a
  6431. // class . . . . Such a function is implicitly inline.
  6432. NewFD->setImplicitlyInline();
  6433. }
  6434. // If this is a method defined in an __interface, and is not a constructor
  6435. // or an overloaded operator, then set the pure flag (isVirtual will already
  6436. // return true).
  6437. if (const CXXRecordDecl *Parent =
  6438. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  6439. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  6440. NewFD->setPure(true);
  6441. // C++ [class.union]p2
  6442. // A union can have member functions, but not virtual functions.
  6443. if (isVirtual && Parent->isUnion())
  6444. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  6445. }
  6446. SetNestedNameSpecifier(NewFD, D);
  6447. isExplicitSpecialization = false;
  6448. isFunctionTemplateSpecialization = false;
  6449. if (D.isInvalidType())
  6450. NewFD->setInvalidDecl();
  6451. // Match up the template parameter lists with the scope specifier, then
  6452. // determine whether we have a template or a template specialization.
  6453. bool Invalid = false;
  6454. if (TemplateParameterList *TemplateParams =
  6455. MatchTemplateParametersToScopeSpecifier(
  6456. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  6457. D.getCXXScopeSpec(),
  6458. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  6459. ? D.getName().TemplateId
  6460. : nullptr,
  6461. TemplateParamLists, isFriend, isExplicitSpecialization,
  6462. Invalid)) {
  6463. if (TemplateParams->size() > 0) {
  6464. // This is a function template
  6465. // Check that we can declare a template here.
  6466. if (CheckTemplateDeclScope(S, TemplateParams))
  6467. NewFD->setInvalidDecl();
  6468. // A destructor cannot be a template.
  6469. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6470. Diag(NewFD->getLocation(), diag::err_destructor_template);
  6471. NewFD->setInvalidDecl();
  6472. }
  6473. // If we're adding a template to a dependent context, we may need to
  6474. // rebuilding some of the types used within the template parameter list,
  6475. // now that we know what the current instantiation is.
  6476. if (DC->isDependentContext()) {
  6477. ContextRAII SavedContext(*this, DC);
  6478. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  6479. Invalid = true;
  6480. }
  6481. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  6482. NewFD->getLocation(),
  6483. Name, TemplateParams,
  6484. NewFD);
  6485. FunctionTemplate->setLexicalDeclContext(CurContext);
  6486. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  6487. // For source fidelity, store the other template param lists.
  6488. if (TemplateParamLists.size() > 1) {
  6489. NewFD->setTemplateParameterListsInfo(Context,
  6490. TemplateParamLists.size() - 1,
  6491. TemplateParamLists.data());
  6492. }
  6493. } else {
  6494. // This is a function template specialization.
  6495. isFunctionTemplateSpecialization = true;
  6496. // For source fidelity, store all the template param lists.
  6497. if (TemplateParamLists.size() > 0)
  6498. NewFD->setTemplateParameterListsInfo(Context,
  6499. TemplateParamLists.size(),
  6500. TemplateParamLists.data());
  6501. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  6502. if (isFriend) {
  6503. // We want to remove the "template<>", found here.
  6504. SourceRange RemoveRange = TemplateParams->getSourceRange();
  6505. // If we remove the template<> and the name is not a
  6506. // template-id, we're actually silently creating a problem:
  6507. // the friend declaration will refer to an untemplated decl,
  6508. // and clearly the user wants a template specialization. So
  6509. // we need to insert '<>' after the name.
  6510. SourceLocation InsertLoc;
  6511. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  6512. InsertLoc = D.getName().getSourceRange().getEnd();
  6513. InsertLoc = getLocForEndOfToken(InsertLoc);
  6514. }
  6515. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  6516. << Name << RemoveRange
  6517. << FixItHint::CreateRemoval(RemoveRange)
  6518. << FixItHint::CreateInsertion(InsertLoc, "<>");
  6519. }
  6520. }
  6521. }
  6522. else {
  6523. // All template param lists were matched against the scope specifier:
  6524. // this is NOT (an explicit specialization of) a template.
  6525. if (TemplateParamLists.size() > 0)
  6526. // For source fidelity, store all the template param lists.
  6527. NewFD->setTemplateParameterListsInfo(Context,
  6528. TemplateParamLists.size(),
  6529. TemplateParamLists.data());
  6530. }
  6531. if (Invalid) {
  6532. NewFD->setInvalidDecl();
  6533. if (FunctionTemplate)
  6534. FunctionTemplate->setInvalidDecl();
  6535. }
  6536. // C++ [dcl.fct.spec]p5:
  6537. // The virtual specifier shall only be used in declarations of
  6538. // nonstatic class member functions that appear within a
  6539. // member-specification of a class declaration; see 10.3.
  6540. //
  6541. if (isVirtual && !NewFD->isInvalidDecl()) {
  6542. if (!isVirtualOkay) {
  6543. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6544. diag::err_virtual_non_function);
  6545. } else if (!CurContext->isRecord()) {
  6546. // 'virtual' was specified outside of the class.
  6547. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6548. diag::err_virtual_out_of_class)
  6549. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  6550. } else if (NewFD->getDescribedFunctionTemplate()) {
  6551. // C++ [temp.mem]p3:
  6552. // A member function template shall not be virtual.
  6553. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6554. diag::err_virtual_member_function_template)
  6555. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  6556. } else {
  6557. // Okay: Add virtual to the method.
  6558. NewFD->setVirtualAsWritten(true);
  6559. }
  6560. if (getLangOpts().CPlusPlus14 &&
  6561. NewFD->getReturnType()->isUndeducedType())
  6562. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  6563. }
  6564. if (getLangOpts().CPlusPlus14 &&
  6565. (NewFD->isDependentContext() ||
  6566. (isFriend && CurContext->isDependentContext())) &&
  6567. NewFD->getReturnType()->isUndeducedType()) {
  6568. // If the function template is referenced directly (for instance, as a
  6569. // member of the current instantiation), pretend it has a dependent type.
  6570. // This is not really justified by the standard, but is the only sane
  6571. // thing to do.
  6572. // FIXME: For a friend function, we have not marked the function as being
  6573. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  6574. const FunctionProtoType *FPT =
  6575. NewFD->getType()->castAs<FunctionProtoType>();
  6576. QualType Result =
  6577. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  6578. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  6579. FPT->getExtProtoInfo(), FPT->getParamMods())); // HLSL Change - add param mods
  6580. }
  6581. // C++ [dcl.fct.spec]p3:
  6582. // The inline specifier shall not appear on a block scope function
  6583. // declaration.
  6584. if (isInline && !NewFD->isInvalidDecl()) {
  6585. if (CurContext->isFunctionOrMethod()) {
  6586. // 'inline' is not allowed on block scope function declaration.
  6587. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6588. diag::err_inline_declaration_block_scope) << Name
  6589. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6590. }
  6591. }
  6592. // C++ [dcl.fct.spec]p6:
  6593. // The explicit specifier shall be used only in the declaration of a
  6594. // constructor or conversion function within its class definition;
  6595. // see 12.3.1 and 12.3.2.
  6596. if (isExplicit && !NewFD->isInvalidDecl()) {
  6597. if (!CurContext->isRecord()) {
  6598. // 'explicit' was specified outside of the class.
  6599. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6600. diag::err_explicit_out_of_class)
  6601. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6602. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  6603. !isa<CXXConversionDecl>(NewFD)) {
  6604. // 'explicit' was specified on a function that wasn't a constructor
  6605. // or conversion function.
  6606. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6607. diag::err_explicit_non_ctor_or_conv_function)
  6608. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6609. }
  6610. }
  6611. if (isConstexpr) {
  6612. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  6613. // are implicitly inline.
  6614. NewFD->setImplicitlyInline();
  6615. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  6616. // be either constructors or to return a literal type. Therefore,
  6617. // destructors cannot be declared constexpr.
  6618. if (isa<CXXDestructorDecl>(NewFD))
  6619. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  6620. }
  6621. // If __module_private__ was specified, mark the function accordingly.
  6622. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6623. if (isFunctionTemplateSpecialization) {
  6624. SourceLocation ModulePrivateLoc
  6625. = D.getDeclSpec().getModulePrivateSpecLoc();
  6626. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  6627. << 0
  6628. << FixItHint::CreateRemoval(ModulePrivateLoc);
  6629. } else {
  6630. NewFD->setModulePrivate();
  6631. if (FunctionTemplate)
  6632. FunctionTemplate->setModulePrivate();
  6633. }
  6634. }
  6635. if (isFriend) {
  6636. if (FunctionTemplate) {
  6637. FunctionTemplate->setObjectOfFriendDecl();
  6638. FunctionTemplate->setAccess(AS_public);
  6639. }
  6640. NewFD->setObjectOfFriendDecl();
  6641. NewFD->setAccess(AS_public);
  6642. }
  6643. // If a function is defined as defaulted or deleted, mark it as such now.
  6644. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  6645. // definition kind to FDK_Definition.
  6646. switch (D.getFunctionDefinitionKind()) {
  6647. case FDK_Declaration:
  6648. case FDK_Definition:
  6649. break;
  6650. case FDK_Defaulted:
  6651. NewFD->setDefaulted();
  6652. break;
  6653. case FDK_Deleted:
  6654. NewFD->setDeletedAsWritten();
  6655. break;
  6656. }
  6657. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  6658. D.isFunctionDefinition()) {
  6659. // C++ [class.mfct]p2:
  6660. // A member function may be defined (8.4) in its class definition, in
  6661. // which case it is an inline member function (7.1.2)
  6662. NewFD->setImplicitlyInline();
  6663. }
  6664. // HLSL Change: We had to set SC_Static for static data member to
  6665. // distinguish it from global constant variable.
  6666. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  6667. !CurContext->isRecord() && !getLangOpts().HLSL) {
  6668. // C++ [class.static]p1:
  6669. // A data or function member of a class may be declared static
  6670. // in a class definition, in which case it is a static member of
  6671. // the class.
  6672. // Complain about the 'static' specifier if it's on an out-of-line
  6673. // member function definition.
  6674. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6675. diag::err_static_out_of_line)
  6676. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6677. }
  6678. // C++11 [except.spec]p15:
  6679. // A deallocation function with no exception-specification is treated
  6680. // as if it were specified with noexcept(true).
  6681. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  6682. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  6683. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  6684. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  6685. NewFD->setType(Context.getFunctionType(
  6686. FPT->getReturnType(), FPT->getParamTypes(),
  6687. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept),
  6688. FPT->getParamMods())); // HLSL Change - get param mods
  6689. }
  6690. // Filter out previous declarations that don't match the scope.
  6691. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  6692. D.getCXXScopeSpec().isNotEmpty() ||
  6693. isExplicitSpecialization ||
  6694. isFunctionTemplateSpecialization);
  6695. // Handle GNU asm-label extension (encoded as an attribute).
  6696. if (Expr *E = (Expr*) D.getAsmLabel()) {
  6697. // The parser guarantees this is a string.
  6698. StringLiteral *SE = cast<StringLiteral>(E);
  6699. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  6700. SE->getString(), 0));
  6701. } else if (!ExtnameUndeclaredIdentifiers.empty() &&
  6702. isDeclTUScopedExternallyVisible(NewFD)) {
  6703. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6704. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  6705. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6706. NewFD->addAttr(I->second);
  6707. ExtnameUndeclaredIdentifiers.erase(I);
  6708. }
  6709. }
  6710. // Copy the parameter declarations from the declarator D to the function
  6711. // declaration NewFD, if they are available. First scavenge them into Params.
  6712. SmallVector<ParmVarDecl*, 16> Params;
  6713. if (D.isFunctionDeclarator()) {
  6714. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6715. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  6716. // function that takes no arguments, not a function that takes a
  6717. // single void argument.
  6718. // We let through "const void" here because Sema::GetTypeForDeclarator
  6719. // already checks for that case.
  6720. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  6721. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  6722. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  6723. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  6724. Param->setDeclContext(NewFD);
  6725. Params.push_back(Param);
  6726. if (Param->isInvalidDecl())
  6727. NewFD->setInvalidDecl();
  6728. }
  6729. }
  6730. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  6731. // When we're declaring a function with a typedef, typeof, etc as in the
  6732. // following example, we'll need to synthesize (unnamed)
  6733. // parameters for use in the declaration.
  6734. //
  6735. // @code
  6736. // typedef void fn(int);
  6737. // fn f;
  6738. // @endcode
  6739. // Synthesize a parameter for each argument type.
  6740. for (const auto &AI : FT->param_types()) {
  6741. ParmVarDecl *Param =
  6742. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  6743. Param->setScopeInfo(0, Params.size());
  6744. Params.push_back(Param);
  6745. }
  6746. } else {
  6747. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  6748. "Should not need args for typedef of non-prototype fn");
  6749. }
  6750. // Finally, we know we have the right number of parameters, install them.
  6751. NewFD->setParams(Params);
  6752. // Find all anonymous symbols defined during the declaration of this function
  6753. // and add to NewFD. This lets us track decls such 'enum Y' in:
  6754. //
  6755. // void f(enum Y {AA} x) {}
  6756. //
  6757. // which would otherwise incorrectly end up in the translation unit scope.
  6758. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  6759. DeclsInPrototypeScope.clear();
  6760. if (D.getDeclSpec().isNoreturnSpecified())
  6761. NewFD->addAttr(
  6762. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  6763. Context, 0));
  6764. // Functions returning a variably modified type violate C99 6.7.5.2p2
  6765. // because all functions have linkage.
  6766. if (!NewFD->isInvalidDecl() &&
  6767. NewFD->getReturnType()->isVariablyModifiedType()) {
  6768. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  6769. NewFD->setInvalidDecl();
  6770. }
  6771. // Apply an implicit SectionAttr if #pragma code_seg is active.
  6772. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  6773. !NewFD->hasAttr<SectionAttr>()) {
  6774. NewFD->addAttr(
  6775. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  6776. CodeSegStack.CurrentValue->getString(),
  6777. CodeSegStack.CurrentPragmaLocation));
  6778. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  6779. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  6780. ASTContext::PSF_Read,
  6781. NewFD))
  6782. NewFD->dropAttr<SectionAttr>();
  6783. }
  6784. // Handle attributes.
  6785. ProcessDeclAttributes(S, NewFD, D);
  6786. if (getLangOpts().OpenCL) {
  6787. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  6788. // type declaration will generate a compilation error.
  6789. unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
  6790. if (AddressSpace == LangAS::opencl_local ||
  6791. AddressSpace == LangAS::opencl_global ||
  6792. AddressSpace == LangAS::opencl_constant) {
  6793. Diag(NewFD->getLocation(),
  6794. diag::err_opencl_return_value_with_address_space);
  6795. NewFD->setInvalidDecl();
  6796. }
  6797. }
  6798. if (!getLangOpts().CPlusPlus) {
  6799. // Perform semantic checking on the function declaration.
  6800. bool isExplicitSpecialization=false;
  6801. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  6802. CheckMain(NewFD, D.getDeclSpec());
  6803. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  6804. CheckMSVCRTEntryPoint(NewFD);
  6805. if (!NewFD->isInvalidDecl())
  6806. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6807. isExplicitSpecialization));
  6808. else if (!Previous.empty())
  6809. // Recover gracefully from an invalid redeclaration.
  6810. D.setRedeclaration(true);
  6811. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6812. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6813. "previous declaration set still overloaded");
  6814. // Diagnose no-prototype function declarations with calling conventions that
  6815. // don't support variadic calls. Only do this in C and do it after merging
  6816. // possibly prototyped redeclarations.
  6817. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  6818. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  6819. CallingConv CC = FT->getExtInfo().getCC();
  6820. if (!supportsVariadicCall(CC)) {
  6821. // Windows system headers sometimes accidentally use stdcall without
  6822. // (void) parameters, so we relax this to a warning.
  6823. int DiagID =
  6824. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  6825. Diag(NewFD->getLocation(), DiagID)
  6826. << FunctionType::getNameForCallConv(CC);
  6827. }
  6828. }
  6829. } else {
  6830. // C++11 [replacement.functions]p3:
  6831. // The program's definitions shall not be specified as inline.
  6832. //
  6833. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  6834. //
  6835. // Suppress the diagnostic if the function is __attribute__((used)), since
  6836. // that forces an external definition to be emitted.
  6837. if (D.getDeclSpec().isInlineSpecified() &&
  6838. NewFD->isReplaceableGlobalAllocationFunction() &&
  6839. !NewFD->hasAttr<UsedAttr>())
  6840. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6841. diag::ext_operator_new_delete_declared_inline)
  6842. << NewFD->getDeclName();
  6843. // If the declarator is a template-id, translate the parser's template
  6844. // argument list into our AST format.
  6845. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  6846. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  6847. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  6848. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  6849. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6850. TemplateId->NumArgs);
  6851. translateTemplateArguments(TemplateArgsPtr,
  6852. TemplateArgs);
  6853. HasExplicitTemplateArgs = true;
  6854. if (NewFD->isInvalidDecl()) {
  6855. HasExplicitTemplateArgs = false;
  6856. } else if (FunctionTemplate) {
  6857. // Function template with explicit template arguments.
  6858. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  6859. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  6860. HasExplicitTemplateArgs = false;
  6861. } else {
  6862. assert((isFunctionTemplateSpecialization ||
  6863. D.getDeclSpec().isFriendSpecified()) &&
  6864. "should have a 'template<>' for this decl");
  6865. // "friend void foo<>(int);" is an implicit specialization decl.
  6866. isFunctionTemplateSpecialization = true;
  6867. }
  6868. } else if (isFriend && isFunctionTemplateSpecialization) {
  6869. // This combination is only possible in a recovery case; the user
  6870. // wrote something like:
  6871. // template <> friend void foo(int);
  6872. // which we're recovering from as if the user had written:
  6873. // friend void foo<>(int);
  6874. // Go ahead and fake up a template id.
  6875. HasExplicitTemplateArgs = true;
  6876. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  6877. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  6878. }
  6879. // If it's a friend (and only if it's a friend), it's possible
  6880. // that either the specialized function type or the specialized
  6881. // template is dependent, and therefore matching will fail. In
  6882. // this case, don't check the specialization yet.
  6883. bool InstantiationDependent = false;
  6884. if (isFunctionTemplateSpecialization && isFriend &&
  6885. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  6886. TemplateSpecializationType::anyDependentTemplateArguments(
  6887. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  6888. InstantiationDependent))) {
  6889. assert(HasExplicitTemplateArgs &&
  6890. "friend function specialization without template args");
  6891. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  6892. Previous))
  6893. NewFD->setInvalidDecl();
  6894. } else if (isFunctionTemplateSpecialization) {
  6895. if (CurContext->isDependentContext() && CurContext->isRecord()
  6896. && !isFriend) {
  6897. isDependentClassScopeExplicitSpecialization = true;
  6898. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  6899. diag::ext_function_specialization_in_class :
  6900. diag::err_function_specialization_in_class)
  6901. << NewFD->getDeclName();
  6902. } else if (CheckFunctionTemplateSpecialization(NewFD,
  6903. (HasExplicitTemplateArgs ? &TemplateArgs
  6904. : nullptr),
  6905. Previous))
  6906. NewFD->setInvalidDecl();
  6907. // C++ [dcl.stc]p1:
  6908. // A storage-class-specifier shall not be specified in an explicit
  6909. // specialization (14.7.3)
  6910. FunctionTemplateSpecializationInfo *Info =
  6911. NewFD->getTemplateSpecializationInfo();
  6912. if (Info && SC != SC_None) {
  6913. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  6914. Diag(NewFD->getLocation(),
  6915. diag::err_explicit_specialization_inconsistent_storage_class)
  6916. << SC
  6917. << FixItHint::CreateRemoval(
  6918. D.getDeclSpec().getStorageClassSpecLoc());
  6919. else
  6920. Diag(NewFD->getLocation(),
  6921. diag::ext_explicit_specialization_storage_class)
  6922. << FixItHint::CreateRemoval(
  6923. D.getDeclSpec().getStorageClassSpecLoc());
  6924. }
  6925. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  6926. if (CheckMemberSpecialization(NewFD, Previous))
  6927. NewFD->setInvalidDecl();
  6928. }
  6929. // Perform semantic checking on the function declaration.
  6930. if (!isDependentClassScopeExplicitSpecialization) {
  6931. if (!getLangOpts().HLSL && !NewFD->isInvalidDecl() && NewFD->isMain()) // HLSL Change: no main() checks in HLSL
  6932. CheckMain(NewFD, D.getDeclSpec());
  6933. if (!getLangOpts().HLSL && !NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) // HLSL Change: no entry point checks in HLSL
  6934. CheckMSVCRTEntryPoint(NewFD);
  6935. if (!NewFD->isInvalidDecl())
  6936. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6937. isExplicitSpecialization));
  6938. else if (!Previous.empty())
  6939. // Recover gracefully from an invalid redeclaration.
  6940. D.setRedeclaration(true);
  6941. }
  6942. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6943. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6944. "previous declaration set still overloaded");
  6945. NamedDecl *PrincipalDecl = (FunctionTemplate
  6946. ? cast<NamedDecl>(FunctionTemplate)
  6947. : NewFD);
  6948. if (isFriend && D.isRedeclaration()) {
  6949. AccessSpecifier Access = AS_public;
  6950. if (!NewFD->isInvalidDecl())
  6951. Access = NewFD->getPreviousDecl()->getAccess();
  6952. NewFD->setAccess(Access);
  6953. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  6954. }
  6955. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  6956. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  6957. PrincipalDecl->setNonMemberOperator();
  6958. // If we have a function template, check the template parameter
  6959. // list. This will check and merge default template arguments.
  6960. if (FunctionTemplate) {
  6961. FunctionTemplateDecl *PrevTemplate =
  6962. FunctionTemplate->getPreviousDecl();
  6963. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  6964. PrevTemplate ? PrevTemplate->getTemplateParameters()
  6965. : nullptr,
  6966. D.getDeclSpec().isFriendSpecified()
  6967. ? (D.isFunctionDefinition()
  6968. ? TPC_FriendFunctionTemplateDefinition
  6969. : TPC_FriendFunctionTemplate)
  6970. : (D.getCXXScopeSpec().isSet() &&
  6971. DC && DC->isRecord() &&
  6972. DC->isDependentContext())
  6973. ? TPC_ClassTemplateMember
  6974. : TPC_FunctionTemplate);
  6975. }
  6976. if (NewFD->isInvalidDecl()) {
  6977. // Ignore all the rest of this.
  6978. } else if (!D.isRedeclaration()) {
  6979. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  6980. AddToScope };
  6981. // Fake up an access specifier if it's supposed to be a class member.
  6982. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  6983. NewFD->setAccess(AS_public);
  6984. // Qualified decls generally require a previous declaration.
  6985. if (D.getCXXScopeSpec().isSet()) {
  6986. // ...with the major exception of templated-scope or
  6987. // dependent-scope friend declarations.
  6988. // TODO: we currently also suppress this check in dependent
  6989. // contexts because (1) the parameter depth will be off when
  6990. // matching friend templates and (2) we might actually be
  6991. // selecting a friend based on a dependent factor. But there
  6992. // are situations where these conditions don't apply and we
  6993. // can actually do this check immediately.
  6994. if (isFriend &&
  6995. (TemplateParamLists.size() ||
  6996. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  6997. CurContext->isDependentContext())) {
  6998. // ignore these
  6999. } else {
  7000. // The user tried to provide an out-of-line definition for a
  7001. // function that is a member of a class or namespace, but there
  7002. // was no such member function declared (C++ [class.mfct]p2,
  7003. // C++ [namespace.memdef]p2). For example:
  7004. //
  7005. // class X {
  7006. // void f() const;
  7007. // };
  7008. //
  7009. // void X::f() { } // ill-formed
  7010. //
  7011. // Complain about this problem, and attempt to suggest close
  7012. // matches (e.g., those that differ only in cv-qualifiers and
  7013. // whether the parameter types are references).
  7014. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7015. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7016. AddToScope = ExtraArgs.AddToScope;
  7017. return Result;
  7018. }
  7019. }
  7020. // Unqualified local friend declarations are required to resolve
  7021. // to something.
  7022. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7023. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7024. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7025. AddToScope = ExtraArgs.AddToScope;
  7026. return Result;
  7027. }
  7028. }
  7029. } else if (!D.isFunctionDefinition() &&
  7030. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7031. !isFriend && !isFunctionTemplateSpecialization &&
  7032. !isExplicitSpecialization) {
  7033. // An out-of-line member function declaration must also be a
  7034. // definition (C++ [class.mfct]p2).
  7035. // Note that this is not the case for explicit specializations of
  7036. // function templates or member functions of class templates, per
  7037. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7038. // extension for compatibility with old SWIG code which likes to
  7039. // generate them.
  7040. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7041. << D.getCXXScopeSpec().getRange();
  7042. }
  7043. }
  7044. ProcessPragmaWeak(S, NewFD);
  7045. checkAttributesAfterMerging(*this, *NewFD);
  7046. AddKnownFunctionAttributes(NewFD);
  7047. if (NewFD->hasAttr<OverloadableAttr>() &&
  7048. !NewFD->getType()->getAs<FunctionProtoType>()) {
  7049. Diag(NewFD->getLocation(),
  7050. diag::err_attribute_overloadable_no_prototype)
  7051. << NewFD;
  7052. // Turn this into a variadic function with no parameters.
  7053. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  7054. FunctionProtoType::ExtProtoInfo EPI(
  7055. Context.getDefaultCallingConvention(true, false));
  7056. EPI.Variadic = true;
  7057. EPI.ExtInfo = FT->getExtInfo();
  7058. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI, None); // HLSL Change - all defaults are in
  7059. NewFD->setType(R);
  7060. }
  7061. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7062. // member, set the visibility of this function.
  7063. if (!DC->isRecord() && NewFD->isExternallyVisible())
  7064. AddPushedVisibilityAttribute(NewFD);
  7065. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  7066. // marking the function.
  7067. AddCFAuditedAttribute(NewFD);
  7068. // If this is a function definition, check if we have to apply optnone due to
  7069. // a pragma.
  7070. if(D.isFunctionDefinition())
  7071. AddRangeBasedOptnone(NewFD);
  7072. // If this is the first declaration of an extern C variable, update
  7073. // the map of such variables.
  7074. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  7075. isIncompleteDeclExternC(*this, NewFD))
  7076. RegisterLocallyScopedExternCDecl(NewFD, S);
  7077. // Set this FunctionDecl's range up to the right paren.
  7078. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  7079. if (D.isRedeclaration() && !Previous.empty()) {
  7080. checkDLLAttributeRedeclaration(
  7081. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  7082. isExplicitSpecialization || isFunctionTemplateSpecialization);
  7083. }
  7084. if (getLangOpts().CPlusPlus) {
  7085. if (FunctionTemplate) {
  7086. if (NewFD->isInvalidDecl())
  7087. FunctionTemplate->setInvalidDecl();
  7088. return FunctionTemplate;
  7089. }
  7090. }
  7091. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  7092. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  7093. if ((getLangOpts().OpenCLVersion >= 120)
  7094. && (SC == SC_Static)) {
  7095. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  7096. D.setInvalidType();
  7097. }
  7098. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  7099. if (!NewFD->getReturnType()->isVoidType()) {
  7100. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  7101. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  7102. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  7103. : FixItHint());
  7104. D.setInvalidType();
  7105. }
  7106. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  7107. for (auto Param : NewFD->params())
  7108. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  7109. }
  7110. MarkUnusedFileScopedDecl(NewFD);
  7111. if (getLangOpts().CUDA)
  7112. if (IdentifierInfo *II = NewFD->getIdentifier())
  7113. if (!NewFD->isInvalidDecl() &&
  7114. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  7115. if (II->isStr("cudaConfigureCall")) {
  7116. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  7117. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  7118. Context.setcudaConfigureCallDecl(NewFD);
  7119. }
  7120. }
  7121. // Here we have an function template explicit specialization at class scope.
  7122. // The actually specialization will be postponed to template instatiation
  7123. // time via the ClassScopeFunctionSpecializationDecl node.
  7124. if (isDependentClassScopeExplicitSpecialization) {
  7125. ClassScopeFunctionSpecializationDecl *NewSpec =
  7126. ClassScopeFunctionSpecializationDecl::Create(
  7127. Context, CurContext, SourceLocation(),
  7128. cast<CXXMethodDecl>(NewFD),
  7129. HasExplicitTemplateArgs, TemplateArgs);
  7130. CurContext->addDecl(NewSpec);
  7131. AddToScope = false;
  7132. }
  7133. return NewFD;
  7134. }
  7135. /// \brief Perform semantic checking of a new function declaration.
  7136. ///
  7137. /// Performs semantic analysis of the new function declaration
  7138. /// NewFD. This routine performs all semantic checking that does not
  7139. /// require the actual declarator involved in the declaration, and is
  7140. /// used both for the declaration of functions as they are parsed
  7141. /// (called via ActOnDeclarator) and for the declaration of functions
  7142. /// that have been instantiated via C++ template instantiation (called
  7143. /// via InstantiateDecl).
  7144. ///
  7145. /// \param IsExplicitSpecialization whether this new function declaration is
  7146. /// an explicit specialization of the previous declaration.
  7147. ///
  7148. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  7149. ///
  7150. /// \returns true if the function declaration is a redeclaration.
  7151. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  7152. LookupResult &Previous,
  7153. bool IsExplicitSpecialization) {
  7154. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  7155. "Variably modified return types are not handled here");
  7156. // Determine whether the type of this function should be merged with
  7157. // a previous visible declaration. This never happens for functions in C++,
  7158. // and always happens in C if the previous declaration was visible.
  7159. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  7160. !Previous.isShadowed();
  7161. // Filter out any non-conflicting previous declarations.
  7162. filterNonConflictingPreviousDecls(*this, NewFD, Previous);
  7163. bool Redeclaration = false;
  7164. NamedDecl *OldDecl = nullptr;
  7165. // Merge or overload the declaration with an existing declaration of
  7166. // the same name, if appropriate.
  7167. if (!Previous.empty()) {
  7168. // Determine whether NewFD is an overload of PrevDecl or
  7169. // a declaration that requires merging. If it's an overload,
  7170. // there's no more work to do here; we'll just add the new
  7171. // function to the scope.
  7172. if (!AllowOverloadingOfFunction(Previous, Context)) {
  7173. NamedDecl *Candidate = Previous.getFoundDecl();
  7174. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  7175. Redeclaration = true;
  7176. OldDecl = Candidate;
  7177. }
  7178. } else {
  7179. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  7180. /*NewIsUsingDecl*/ false)) {
  7181. case Ovl_Match:
  7182. Redeclaration = true;
  7183. break;
  7184. case Ovl_NonFunction:
  7185. Redeclaration = true;
  7186. break;
  7187. case Ovl_Overload:
  7188. Redeclaration = false;
  7189. break;
  7190. }
  7191. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7192. // If a function name is overloadable in C, then every function
  7193. // with that name must be marked "overloadable".
  7194. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7195. << Redeclaration << NewFD;
  7196. NamedDecl *OverloadedDecl = nullptr;
  7197. if (Redeclaration)
  7198. OverloadedDecl = OldDecl;
  7199. else if (!Previous.empty())
  7200. OverloadedDecl = Previous.getRepresentativeDecl();
  7201. if (OverloadedDecl)
  7202. Diag(OverloadedDecl->getLocation(),
  7203. diag::note_attribute_overloadable_prev_overload);
  7204. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7205. }
  7206. }
  7207. }
  7208. // Check for a previous extern "C" declaration with this name.
  7209. if (!Redeclaration &&
  7210. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  7211. filterNonConflictingPreviousDecls(*this, NewFD, Previous);
  7212. if (!Previous.empty()) {
  7213. // This is an extern "C" declaration with the same name as a previous
  7214. // declaration, and thus redeclares that entity...
  7215. Redeclaration = true;
  7216. OldDecl = Previous.getFoundDecl();
  7217. MergeTypeWithPrevious = false;
  7218. // ... except in the presence of __attribute__((overloadable)).
  7219. if (OldDecl->hasAttr<OverloadableAttr>()) {
  7220. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7221. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7222. << Redeclaration << NewFD;
  7223. Diag(Previous.getFoundDecl()->getLocation(),
  7224. diag::note_attribute_overloadable_prev_overload);
  7225. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7226. }
  7227. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  7228. Redeclaration = false;
  7229. OldDecl = nullptr;
  7230. }
  7231. }
  7232. }
  7233. }
  7234. // HLSL Change Starts
  7235. // Rather than fix for inout parameters, comment out - this is N/A for HLSL
  7236. #if 0
  7237. // HLSL Change Ends
  7238. // C++11 [dcl.constexpr]p8:
  7239. // A constexpr specifier for a non-static member function that is not
  7240. // a constructor declares that member function to be const.
  7241. //
  7242. // This needs to be delayed until we know whether this is an out-of-line
  7243. // definition of a static member function.
  7244. //
  7245. // This rule is not present in C++1y, so we produce a backwards
  7246. // compatibility warning whenever it happens in C++11.
  7247. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7248. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  7249. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  7250. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  7251. CXXMethodDecl *OldMD = nullptr;
  7252. if (OldDecl)
  7253. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  7254. if (!OldMD || !OldMD->isStatic()) {
  7255. const FunctionProtoType *FPT =
  7256. MD->getType()->castAs<FunctionProtoType>();
  7257. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7258. EPI.TypeQuals |= Qualifiers::Const;
  7259. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  7260. FPT->getParamTypes(), EPI));
  7261. // Warn that we did this, if we're not performing template instantiation.
  7262. // In that case, we'll have warned already when the template was defined.
  7263. if (ActiveTemplateInstantiations.empty()) {
  7264. SourceLocation AddConstLoc;
  7265. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  7266. .IgnoreParens().getAs<FunctionTypeLoc>())
  7267. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  7268. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  7269. << FixItHint::CreateInsertion(AddConstLoc, " const");
  7270. }
  7271. }
  7272. }
  7273. #endif // HLSL Change Ends
  7274. if (Redeclaration) {
  7275. // NewFD and OldDecl represent declarations that need to be
  7276. // merged.
  7277. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  7278. NewFD->setInvalidDecl();
  7279. return Redeclaration;
  7280. }
  7281. Previous.clear();
  7282. Previous.addDecl(OldDecl);
  7283. if (FunctionTemplateDecl *OldTemplateDecl
  7284. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  7285. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  7286. FunctionTemplateDecl *NewTemplateDecl
  7287. = NewFD->getDescribedFunctionTemplate();
  7288. assert(NewTemplateDecl && "Template/non-template mismatch");
  7289. if (CXXMethodDecl *Method
  7290. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  7291. Method->setAccess(OldTemplateDecl->getAccess());
  7292. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  7293. }
  7294. // If this is an explicit specialization of a member that is a function
  7295. // template, mark it as a member specialization.
  7296. if (IsExplicitSpecialization &&
  7297. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  7298. NewTemplateDecl->setMemberSpecialization();
  7299. assert(OldTemplateDecl->isMemberSpecialization());
  7300. }
  7301. } else {
  7302. // This needs to happen first so that 'inline' propagates.
  7303. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  7304. if (isa<CXXMethodDecl>(NewFD))
  7305. NewFD->setAccess(OldDecl->getAccess());
  7306. }
  7307. }
  7308. // Semantic checking for this function declaration (in isolation).
  7309. if (getLangOpts().CPlusPlus) {
  7310. // C++-specific checks.
  7311. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  7312. CheckConstructor(Constructor);
  7313. } else if (CXXDestructorDecl *Destructor =
  7314. dyn_cast<CXXDestructorDecl>(NewFD)) {
  7315. CXXRecordDecl *Record = Destructor->getParent();
  7316. QualType ClassType = Context.getTypeDeclType(Record);
  7317. // FIXME: Shouldn't we be able to perform this check even when the class
  7318. // type is dependent? Both gcc and edg can handle that.
  7319. if (!ClassType->isDependentType()) {
  7320. DeclarationName Name
  7321. = Context.DeclarationNames.getCXXDestructorName(
  7322. Context.getCanonicalType(ClassType));
  7323. if (NewFD->getDeclName() != Name) {
  7324. Diag(NewFD->getLocation(), diag::err_destructor_name);
  7325. NewFD->setInvalidDecl();
  7326. return Redeclaration;
  7327. }
  7328. }
  7329. } else if (CXXConversionDecl *Conversion
  7330. = dyn_cast<CXXConversionDecl>(NewFD)) {
  7331. ActOnConversionDeclarator(Conversion);
  7332. }
  7333. // Find any virtual functions that this function overrides.
  7334. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  7335. if (!Method->isFunctionTemplateSpecialization() &&
  7336. !Method->getDescribedFunctionTemplate() &&
  7337. Method->isCanonicalDecl()) {
  7338. if (AddOverriddenMethods(Method->getParent(), Method)) {
  7339. // If the function was marked as "static", we have a problem.
  7340. if (NewFD->getStorageClass() == SC_Static) {
  7341. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  7342. }
  7343. }
  7344. }
  7345. if (Method->isStatic())
  7346. checkThisInStaticMemberFunctionType(Method);
  7347. }
  7348. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  7349. if (NewFD->isOverloadedOperator() &&
  7350. CheckOverloadedOperatorDeclaration(NewFD)) {
  7351. NewFD->setInvalidDecl();
  7352. return Redeclaration;
  7353. }
  7354. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  7355. if (NewFD->getLiteralIdentifier() &&
  7356. CheckLiteralOperatorDeclaration(NewFD)) {
  7357. NewFD->setInvalidDecl();
  7358. return Redeclaration;
  7359. }
  7360. // In C++, check default arguments now that we have merged decls. Unless
  7361. // the lexical context is the class, because in this case this is done
  7362. // during delayed parsing anyway.
  7363. if (!CurContext->isRecord())
  7364. CheckCXXDefaultArguments(NewFD);
  7365. // If this function declares a builtin function, check the type of this
  7366. // declaration against the expected type for the builtin.
  7367. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  7368. ASTContext::GetBuiltinTypeError Error;
  7369. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  7370. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  7371. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  7372. // The type of this function differs from the type of the builtin,
  7373. // so forget about the builtin entirely.
  7374. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  7375. }
  7376. }
  7377. // If this function is declared as being extern "C", then check to see if
  7378. // the function returns a UDT (class, struct, or union type) that is not C
  7379. // compatible, and if it does, warn the user.
  7380. // But, issue any diagnostic on the first declaration only.
  7381. if (Previous.empty() && NewFD->isExternC()) {
  7382. QualType R = NewFD->getReturnType();
  7383. if (R->isIncompleteType() && !R->isVoidType())
  7384. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  7385. << NewFD << R;
  7386. else if (!R.isPODType(Context) && !R->isVoidType() &&
  7387. !R->isObjCObjectPointerType())
  7388. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  7389. }
  7390. }
  7391. return Redeclaration;
  7392. }
  7393. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  7394. // C++11 [basic.start.main]p3:
  7395. // A program that [...] declares main to be inline, static or
  7396. // constexpr is ill-formed.
  7397. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  7398. // appear in a declaration of main.
  7399. // static main is not an error under C99, but we should warn about it.
  7400. // We accept _Noreturn main as an extension.
  7401. if (FD->getStorageClass() == SC_Static)
  7402. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  7403. ? diag::err_static_main : diag::warn_static_main)
  7404. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  7405. if (FD->isInlineSpecified())
  7406. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  7407. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  7408. if (DS.isNoreturnSpecified()) {
  7409. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  7410. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  7411. Diag(NoreturnLoc, diag::ext_noreturn_main);
  7412. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  7413. << FixItHint::CreateRemoval(NoreturnRange);
  7414. }
  7415. if (FD->isConstexpr()) {
  7416. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  7417. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  7418. FD->setConstexpr(false);
  7419. }
  7420. if (getLangOpts().OpenCL) {
  7421. Diag(FD->getLocation(), diag::err_opencl_no_main)
  7422. << FD->hasAttr<OpenCLKernelAttr>();
  7423. FD->setInvalidDecl();
  7424. return;
  7425. }
  7426. QualType T = FD->getType();
  7427. assert(T->isFunctionType() && "function decl is not of function type");
  7428. const FunctionType* FT = T->castAs<FunctionType>();
  7429. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  7430. // In C with GNU extensions we allow main() to have non-integer return
  7431. // type, but we should warn about the extension, and we disable the
  7432. // implicit-return-zero rule.
  7433. // GCC in C mode accepts qualified 'int'.
  7434. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  7435. FD->setHasImplicitReturnZero(true);
  7436. else {
  7437. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  7438. SourceRange RTRange = FD->getReturnTypeSourceRange();
  7439. if (RTRange.isValid())
  7440. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  7441. << FixItHint::CreateReplacement(RTRange, "int");
  7442. }
  7443. } else {
  7444. // In C and C++, main magically returns 0 if you fall off the end;
  7445. // set the flag which tells us that.
  7446. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  7447. // All the standards say that main() should return 'int'.
  7448. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  7449. FD->setHasImplicitReturnZero(true);
  7450. else {
  7451. // Otherwise, this is just a flat-out error.
  7452. SourceRange RTRange = FD->getReturnTypeSourceRange();
  7453. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  7454. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  7455. : FixItHint());
  7456. FD->setInvalidDecl(true);
  7457. }
  7458. }
  7459. // Treat protoless main() as nullary.
  7460. if (isa<FunctionNoProtoType>(FT)) return;
  7461. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  7462. unsigned nparams = FTP->getNumParams();
  7463. assert(FD->getNumParams() == nparams);
  7464. bool HasExtraParameters = (nparams > 3);
  7465. if (FTP->isVariadic()) {
  7466. Diag(FD->getLocation(), diag::ext_variadic_main);
  7467. // FIXME: if we had information about the location of the ellipsis, we
  7468. // could add a FixIt hint to remove it as a parameter.
  7469. }
  7470. // Darwin passes an undocumented fourth argument of type char**. If
  7471. // other platforms start sprouting these, the logic below will start
  7472. // getting shifty.
  7473. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  7474. HasExtraParameters = false;
  7475. if (HasExtraParameters) {
  7476. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  7477. FD->setInvalidDecl(true);
  7478. nparams = 3;
  7479. }
  7480. // FIXME: a lot of the following diagnostics would be improved
  7481. // if we had some location information about types.
  7482. QualType CharPP =
  7483. Context.getPointerType(Context.getPointerType(Context.CharTy));
  7484. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  7485. for (unsigned i = 0; i < nparams; ++i) {
  7486. QualType AT = FTP->getParamType(i);
  7487. bool mismatch = true;
  7488. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  7489. mismatch = false;
  7490. else if (Expected[i] == CharPP) {
  7491. // As an extension, the following forms are okay:
  7492. // char const **
  7493. // char const * const *
  7494. // char * const *
  7495. QualifierCollector qs;
  7496. const PointerType* PT;
  7497. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  7498. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  7499. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  7500. Context.CharTy)) {
  7501. qs.removeConst();
  7502. mismatch = !qs.empty();
  7503. }
  7504. }
  7505. if (mismatch) {
  7506. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  7507. // TODO: suggest replacing given type with expected type
  7508. FD->setInvalidDecl(true);
  7509. }
  7510. }
  7511. if (nparams == 1 && !FD->isInvalidDecl()) {
  7512. Diag(FD->getLocation(), diag::warn_main_one_arg);
  7513. }
  7514. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  7515. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  7516. FD->setInvalidDecl();
  7517. }
  7518. }
  7519. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  7520. QualType T = FD->getType();
  7521. assert(T->isFunctionType() && "function decl is not of function type");
  7522. const FunctionType *FT = T->castAs<FunctionType>();
  7523. // Set an implicit return of 'zero' if the function can return some integral,
  7524. // enumeration, pointer or nullptr type.
  7525. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  7526. FT->getReturnType()->isAnyPointerType() ||
  7527. FT->getReturnType()->isNullPtrType())
  7528. // DllMain is exempt because a return value of zero means it failed.
  7529. if (FD->getName() != "DllMain")
  7530. FD->setHasImplicitReturnZero(true);
  7531. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  7532. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  7533. FD->setInvalidDecl();
  7534. }
  7535. }
  7536. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  7537. // FIXME: Need strict checking. In C89, we need to check for
  7538. // any assignment, increment, decrement, function-calls, or
  7539. // commas outside of a sizeof. In C99, it's the same list,
  7540. // except that the aforementioned are allowed in unevaluated
  7541. // expressions. Everything else falls under the
  7542. // "may accept other forms of constant expressions" exception.
  7543. // (We never end up here for C++, so the constant expression
  7544. // rules there don't matter.)
  7545. const Expr *Culprit;
  7546. if (Init->isConstantInitializer(Context, false, &Culprit))
  7547. return false;
  7548. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  7549. << Culprit->getSourceRange();
  7550. return true;
  7551. }
  7552. namespace {
  7553. // Visits an initialization expression to see if OrigDecl is evaluated in
  7554. // its own initialization and throws a warning if it does.
  7555. class SelfReferenceChecker
  7556. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  7557. Sema &S;
  7558. Decl *OrigDecl;
  7559. bool isRecordType;
  7560. bool isPODType;
  7561. bool isReferenceType;
  7562. bool isInitList;
  7563. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  7564. public:
  7565. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  7566. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  7567. S(S), OrigDecl(OrigDecl) {
  7568. isPODType = false;
  7569. isRecordType = false;
  7570. isReferenceType = false;
  7571. isInitList = false;
  7572. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  7573. isPODType = VD->getType().isPODType(S.Context);
  7574. isRecordType = VD->getType()->isRecordType();
  7575. isReferenceType = VD->getType()->isReferenceType();
  7576. }
  7577. }
  7578. // For most expressions, just call the visitor. For initializer lists,
  7579. // track the index of the field being initialized since fields are
  7580. // initialized in order allowing use of previously initialized fields.
  7581. void CheckExpr(Expr *E) {
  7582. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  7583. if (!InitList) {
  7584. Visit(E);
  7585. return;
  7586. }
  7587. // Track and increment the index here.
  7588. isInitList = true;
  7589. InitFieldIndex.push_back(0);
  7590. for (auto Child : InitList->children()) {
  7591. CheckExpr(cast<Expr>(Child));
  7592. ++InitFieldIndex.back();
  7593. }
  7594. InitFieldIndex.pop_back();
  7595. }
  7596. // Returns true if MemberExpr is checked and no futher checking is needed.
  7597. // Returns false if additional checking is required.
  7598. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  7599. llvm::SmallVector<FieldDecl*, 4> Fields;
  7600. Expr *Base = E;
  7601. bool ReferenceField = false;
  7602. // Get the field memebers used.
  7603. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7604. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  7605. if (!FD)
  7606. return false;
  7607. Fields.push_back(FD);
  7608. if (FD->getType()->isReferenceType())
  7609. ReferenceField = true;
  7610. Base = ME->getBase()->IgnoreParenImpCasts();
  7611. }
  7612. // Keep checking only if the base Decl is the same.
  7613. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  7614. if (!DRE || DRE->getDecl() != OrigDecl)
  7615. return false;
  7616. // A reference field can be bound to an unininitialized field.
  7617. if (CheckReference && !ReferenceField)
  7618. return true;
  7619. // Convert FieldDecls to their index number.
  7620. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  7621. for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
  7622. UsedFieldIndex.push_back((*I)->getFieldIndex());
  7623. }
  7624. // See if a warning is needed by checking the first difference in index
  7625. // numbers. If field being used has index less than the field being
  7626. // initialized, then the use is safe.
  7627. for (auto UsedIter = UsedFieldIndex.begin(),
  7628. UsedEnd = UsedFieldIndex.end(),
  7629. OrigIter = InitFieldIndex.begin(),
  7630. OrigEnd = InitFieldIndex.end();
  7631. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  7632. if (*UsedIter < *OrigIter)
  7633. return true;
  7634. if (*UsedIter > *OrigIter)
  7635. break;
  7636. }
  7637. // TODO: Add a different warning which will print the field names.
  7638. HandleDeclRefExpr(DRE);
  7639. return true;
  7640. }
  7641. // For most expressions, the cast is directly above the DeclRefExpr.
  7642. // For conditional operators, the cast can be outside the conditional
  7643. // operator if both expressions are DeclRefExpr's.
  7644. void HandleValue(Expr *E) {
  7645. E = E->IgnoreParens();
  7646. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  7647. HandleDeclRefExpr(DRE);
  7648. return;
  7649. }
  7650. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7651. Visit(CO->getCond());
  7652. HandleValue(CO->getTrueExpr());
  7653. HandleValue(CO->getFalseExpr());
  7654. return;
  7655. }
  7656. if (BinaryConditionalOperator *BCO =
  7657. dyn_cast<BinaryConditionalOperator>(E)) {
  7658. Visit(BCO->getCond());
  7659. HandleValue(BCO->getFalseExpr());
  7660. return;
  7661. }
  7662. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  7663. HandleValue(OVE->getSourceExpr());
  7664. return;
  7665. }
  7666. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  7667. if (BO->getOpcode() == BO_Comma) {
  7668. Visit(BO->getLHS());
  7669. HandleValue(BO->getRHS());
  7670. return;
  7671. }
  7672. }
  7673. if (isa<MemberExpr>(E)) {
  7674. if (isInitList) {
  7675. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  7676. false /*CheckReference*/))
  7677. return;
  7678. }
  7679. Expr *Base = E->IgnoreParenImpCasts();
  7680. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7681. // Check for static member variables and don't warn on them.
  7682. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7683. return;
  7684. Base = ME->getBase()->IgnoreParenImpCasts();
  7685. }
  7686. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  7687. HandleDeclRefExpr(DRE);
  7688. return;
  7689. }
  7690. Visit(E);
  7691. }
  7692. // Reference types not handled in HandleValue are handled here since all
  7693. // uses of references are bad, not just r-value uses.
  7694. void VisitDeclRefExpr(DeclRefExpr *E) {
  7695. if (isReferenceType)
  7696. HandleDeclRefExpr(E);
  7697. }
  7698. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  7699. if (E->getCastKind() == CK_LValueToRValue) {
  7700. HandleValue(E->getSubExpr());
  7701. return;
  7702. }
  7703. Inherited::VisitImplicitCastExpr(E);
  7704. }
  7705. void VisitMemberExpr(MemberExpr *E) {
  7706. if (isInitList) {
  7707. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  7708. return;
  7709. }
  7710. // Don't warn on arrays since they can be treated as pointers.
  7711. if (E->getType()->canDecayToPointerType()) return;
  7712. // Warn when a non-static method call is followed by non-static member
  7713. // field accesses, which is followed by a DeclRefExpr.
  7714. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  7715. bool Warn = (MD && !MD->isStatic());
  7716. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  7717. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7718. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7719. Warn = false;
  7720. Base = ME->getBase()->IgnoreParenImpCasts();
  7721. }
  7722. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  7723. if (Warn)
  7724. HandleDeclRefExpr(DRE);
  7725. return;
  7726. }
  7727. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  7728. // Visit that expression.
  7729. Visit(Base);
  7730. }
  7731. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  7732. Expr *Callee = E->getCallee();
  7733. if (isa<UnresolvedLookupExpr>(Callee))
  7734. return Inherited::VisitCXXOperatorCallExpr(E);
  7735. Visit(Callee);
  7736. for (auto Arg: E->arguments())
  7737. HandleValue(Arg->IgnoreParenImpCasts());
  7738. }
  7739. void VisitUnaryOperator(UnaryOperator *E) {
  7740. // For POD record types, addresses of its own members are well-defined.
  7741. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  7742. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  7743. if (!isPODType)
  7744. HandleValue(E->getSubExpr());
  7745. return;
  7746. }
  7747. if (E->isIncrementDecrementOp()) {
  7748. HandleValue(E->getSubExpr());
  7749. return;
  7750. }
  7751. Inherited::VisitUnaryOperator(E);
  7752. }
  7753. void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
  7754. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  7755. if (E->getConstructor()->isCopyConstructor()) {
  7756. Expr *ArgExpr = E->getArg(0);
  7757. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  7758. if (ILE->getNumInits() == 1)
  7759. ArgExpr = ILE->getInit(0);
  7760. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  7761. if (ICE->getCastKind() == CK_NoOp)
  7762. ArgExpr = ICE->getSubExpr();
  7763. HandleValue(ArgExpr);
  7764. return;
  7765. }
  7766. Inherited::VisitCXXConstructExpr(E);
  7767. }
  7768. void VisitCallExpr(CallExpr *E) {
  7769. // Treat std::move as a use.
  7770. if (E->getNumArgs() == 1) {
  7771. if (FunctionDecl *FD = E->getDirectCallee()) {
  7772. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  7773. FD->getIdentifier()->isStr("move")) {
  7774. HandleValue(E->getArg(0));
  7775. return;
  7776. }
  7777. }
  7778. }
  7779. Inherited::VisitCallExpr(E);
  7780. }
  7781. void VisitBinaryOperator(BinaryOperator *E) {
  7782. if (E->isCompoundAssignmentOp()) {
  7783. HandleValue(E->getLHS());
  7784. Visit(E->getRHS());
  7785. return;
  7786. }
  7787. Inherited::VisitBinaryOperator(E);
  7788. }
  7789. // A custom visitor for BinaryConditionalOperator is needed because the
  7790. // regular visitor would check the condition and true expression separately
  7791. // but both point to the same place giving duplicate diagnostics.
  7792. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  7793. Visit(E->getCond());
  7794. Visit(E->getFalseExpr());
  7795. }
  7796. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  7797. Decl* ReferenceDecl = DRE->getDecl();
  7798. if (OrigDecl != ReferenceDecl) return;
  7799. unsigned diag;
  7800. if (isReferenceType) {
  7801. diag = diag::warn_uninit_self_reference_in_reference_init;
  7802. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  7803. diag = diag::warn_static_self_reference_in_init;
  7804. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  7805. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  7806. DRE->getDecl()->getType()->isRecordType()) {
  7807. diag = diag::warn_uninit_self_reference_in_init;
  7808. } else {
  7809. // Local variables will be handled by the CFG analysis.
  7810. return;
  7811. }
  7812. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  7813. S.PDiag(diag)
  7814. << DRE->getNameInfo().getName()
  7815. << OrigDecl->getLocation()
  7816. << DRE->getSourceRange());
  7817. }
  7818. };
  7819. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  7820. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  7821. bool DirectInit) {
  7822. // Parameters arguments are occassionially constructed with itself,
  7823. // for instance, in recursive functions. Skip them.
  7824. if (isa<ParmVarDecl>(OrigDecl))
  7825. return;
  7826. E = E->IgnoreParens();
  7827. // Skip checking T a = a where T is not a record or reference type.
  7828. // Doing so is a way to silence uninitialized warnings.
  7829. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  7830. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  7831. if (ICE->getCastKind() == CK_LValueToRValue)
  7832. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  7833. if (DRE->getDecl() == OrigDecl)
  7834. return;
  7835. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  7836. }
  7837. }
  7838. /// AddInitializerToDecl - Adds the initializer Init to the
  7839. /// declaration dcl. If DirectInit is true, this is C++ direct
  7840. /// initialization rather than copy initialization.
  7841. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  7842. bool DirectInit, bool TypeMayContainAuto) {
  7843. // If there is no declaration, there was an error parsing it. Just ignore
  7844. // the initializer.
  7845. if (!RealDecl || RealDecl->isInvalidDecl()) {
  7846. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  7847. return;
  7848. }
  7849. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  7850. // Pure-specifiers are handled in ActOnPureSpecifier.
  7851. Diag(Method->getLocation(), diag::err_member_function_initialization)
  7852. << Method->getDeclName() << Init->getSourceRange();
  7853. Method->setInvalidDecl();
  7854. return;
  7855. }
  7856. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  7857. if (!VDecl) {
  7858. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  7859. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  7860. RealDecl->setInvalidDecl();
  7861. return;
  7862. }
  7863. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7864. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  7865. if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
  7866. // Attempt typo correction early so that the type of the init expression can
  7867. // be deduced based on the chosen correction:if the original init contains a
  7868. // TypoExpr.
  7869. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  7870. if (!Res.isUsable()) {
  7871. RealDecl->setInvalidDecl();
  7872. return;
  7873. }
  7874. if (Res.get() != Init) {
  7875. Init = Res.get();
  7876. if (CXXDirectInit)
  7877. CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7878. }
  7879. Expr *DeduceInit = Init;
  7880. // Initializer could be a C++ direct-initializer. Deduction only works if it
  7881. // contains exactly one expression.
  7882. if (CXXDirectInit) {
  7883. if (CXXDirectInit->getNumExprs() == 0) {
  7884. // It isn't possible to write this directly, but it is possible to
  7885. // end up in this situation with "auto x(some_pack...);"
  7886. Diag(CXXDirectInit->getLocStart(),
  7887. VDecl->isInitCapture() ? diag::err_init_capture_no_expression
  7888. : diag::err_auto_var_init_no_expression)
  7889. << VDecl->getDeclName() << VDecl->getType()
  7890. << VDecl->getSourceRange();
  7891. RealDecl->setInvalidDecl();
  7892. return;
  7893. } else if (CXXDirectInit->getNumExprs() > 1) {
  7894. Diag(CXXDirectInit->getExpr(1)->getLocStart(),
  7895. VDecl->isInitCapture()
  7896. ? diag::err_init_capture_multiple_expressions
  7897. : diag::err_auto_var_init_multiple_expressions)
  7898. << VDecl->getDeclName() << VDecl->getType()
  7899. << VDecl->getSourceRange();
  7900. RealDecl->setInvalidDecl();
  7901. return;
  7902. } else {
  7903. DeduceInit = CXXDirectInit->getExpr(0);
  7904. if (isa<InitListExpr>(DeduceInit))
  7905. Diag(CXXDirectInit->getLocStart(),
  7906. diag::err_auto_var_init_paren_braces)
  7907. << VDecl->getDeclName() << VDecl->getType()
  7908. << VDecl->getSourceRange();
  7909. }
  7910. }
  7911. // Expressions default to 'id' when we're in a debugger.
  7912. bool DefaultedToAuto = false;
  7913. if (getLangOpts().DebuggerCastResultToId &&
  7914. Init->getType() == Context.UnknownAnyTy) {
  7915. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  7916. if (Result.isInvalid()) {
  7917. VDecl->setInvalidDecl();
  7918. return;
  7919. }
  7920. Init = Result.get();
  7921. DefaultedToAuto = true;
  7922. }
  7923. QualType DeducedType;
  7924. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  7925. DAR_Failed)
  7926. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  7927. if (DeducedType.isNull()) {
  7928. RealDecl->setInvalidDecl();
  7929. return;
  7930. }
  7931. VDecl->setType(DeducedType);
  7932. assert(VDecl->isLinkageValid());
  7933. // In ARC, infer lifetime.
  7934. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  7935. VDecl->setInvalidDecl();
  7936. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  7937. // 'id' instead of a specific object type prevents most of our usual checks.
  7938. // We only want to warn outside of template instantiations, though:
  7939. // inside a template, the 'id' could have come from a parameter.
  7940. if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
  7941. DeducedType->isObjCIdType()) {
  7942. SourceLocation Loc =
  7943. VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
  7944. Diag(Loc, diag::warn_auto_var_is_id)
  7945. << VDecl->getDeclName() << DeduceInit->getSourceRange();
  7946. }
  7947. // If this is a redeclaration, check that the type we just deduced matches
  7948. // the previously declared type.
  7949. assert(!getLangOpts().HLSL && "auto types are not supported - merge type below is inconsequential"); // HLSL Change
  7950. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  7951. // We never need to merge the type, because we cannot form an incomplete
  7952. // array of auto, nor deduce such a type.
  7953. ShadowMergeState MergeState = ShadowMergeState_Disallowed; // HLSL Change - add merge state
  7954. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false, MergeState); // HLSL Change - add merge state
  7955. }
  7956. // Check the deduced type is valid for a variable declaration.
  7957. CheckVariableDeclarationType(VDecl);
  7958. if (VDecl->isInvalidDecl())
  7959. return;
  7960. // If all looks well, warn if this is a case that will change meaning when
  7961. // we implement N3922.
  7962. if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
  7963. Diag(Init->getLocStart(),
  7964. diag::warn_auto_var_direct_list_init)
  7965. << FixItHint::CreateInsertion(Init->getLocStart(), "=");
  7966. }
  7967. }
  7968. // dllimport cannot be used on variable definitions.
  7969. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  7970. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  7971. VDecl->setInvalidDecl();
  7972. return;
  7973. }
  7974. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  7975. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  7976. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  7977. VDecl->setInvalidDecl();
  7978. return;
  7979. }
  7980. if (!VDecl->getType()->isDependentType()) {
  7981. // A definition must end up with a complete type, which means it must be
  7982. // complete with the restriction that an array type might be completed by
  7983. // the initializer; note that later code assumes this restriction.
  7984. QualType BaseDeclType = VDecl->getType();
  7985. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  7986. BaseDeclType = Array->getElementType();
  7987. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  7988. diag::err_typecheck_decl_incomplete_type)) {
  7989. RealDecl->setInvalidDecl();
  7990. return;
  7991. }
  7992. // The variable can not have an abstract class type.
  7993. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  7994. diag::err_abstract_type_in_decl,
  7995. AbstractVariableType))
  7996. VDecl->setInvalidDecl();
  7997. }
  7998. VarDecl *Def;
  7999. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  8000. NamedDecl *Hidden = nullptr;
  8001. if (!hasVisibleDefinition(Def, &Hidden) &&
  8002. (VDecl->getFormalLinkage() == InternalLinkage ||
  8003. VDecl->getDescribedVarTemplate() ||
  8004. VDecl->getNumTemplateParameterLists() ||
  8005. VDecl->getDeclContext()->isDependentContext())) {
  8006. // The previous definition is hidden, and multiple definitions are
  8007. // permitted (in separate TUs). Form another definition of it.
  8008. } else {
  8009. Diag(VDecl->getLocation(), diag::err_redefinition)
  8010. << VDecl->getDeclName();
  8011. Diag(Def->getLocation(), diag::note_previous_definition);
  8012. VDecl->setInvalidDecl();
  8013. return;
  8014. }
  8015. }
  8016. if (getLangOpts().CPlusPlus) {
  8017. // C++ [class.static.data]p4
  8018. // If a static data member is of const integral or const
  8019. // enumeration type, its declaration in the class definition can
  8020. // specify a constant-initializer which shall be an integral
  8021. // constant expression (5.19). In that case, the member can appear
  8022. // in integral constant expressions. The member shall still be
  8023. // defined in a namespace scope if it is used in the program and the
  8024. // namespace scope definition shall not contain an initializer.
  8025. //
  8026. // We already performed a redefinition check above, but for static
  8027. // data members we also need to check whether there was an in-class
  8028. // declaration with an initializer.
  8029. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  8030. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  8031. << VDecl->getDeclName();
  8032. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  8033. diag::note_previous_initializer)
  8034. << 0;
  8035. return;
  8036. }
  8037. if (VDecl->hasLocalStorage())
  8038. getCurFunction()->setHasBranchProtectedScope();
  8039. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  8040. VDecl->setInvalidDecl();
  8041. return;
  8042. }
  8043. }
  8044. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  8045. // a kernel function cannot be initialized."
  8046. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  8047. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  8048. VDecl->setInvalidDecl();
  8049. return;
  8050. }
  8051. // Get the decls type and save a reference for later, since
  8052. // CheckInitializerTypes may change it.
  8053. QualType DclT = VDecl->getType(), SavT = DclT;
  8054. // Expressions default to 'id' when we're in a debugger
  8055. // and we are assigning it to a variable of Objective-C pointer type.
  8056. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  8057. Init->getType() == Context.UnknownAnyTy) {
  8058. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8059. if (Result.isInvalid()) {
  8060. VDecl->setInvalidDecl();
  8061. return;
  8062. }
  8063. Init = Result.get();
  8064. }
  8065. // Perform the initialization.
  8066. if (!VDecl->isInvalidDecl()) {
  8067. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  8068. InitializationKind Kind
  8069. = DirectInit ?
  8070. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  8071. Init->getLocStart(),
  8072. Init->getLocEnd())
  8073. : InitializationKind::CreateDirectList(
  8074. VDecl->getLocation())
  8075. : InitializationKind::CreateCopy(VDecl->getLocation(),
  8076. Init->getLocStart());
  8077. MultiExprArg Args = Init;
  8078. if (CXXDirectInit)
  8079. Args = MultiExprArg(CXXDirectInit->getExprs(),
  8080. CXXDirectInit->getNumExprs());
  8081. // Try to correct any TypoExprs in the initialization arguments.
  8082. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  8083. ExprResult Res = CorrectDelayedTyposInExpr(
  8084. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  8085. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  8086. return Init.Failed() ? ExprError() : E;
  8087. });
  8088. if (Res.isInvalid()) {
  8089. VDecl->setInvalidDecl();
  8090. } else if (Res.get() != Args[Idx]) {
  8091. Args[Idx] = Res.get();
  8092. }
  8093. }
  8094. if (VDecl->isInvalidDecl())
  8095. return;
  8096. InitializationSequence InitSeq(*this, Entity, Kind, Args);
  8097. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  8098. if (Result.isInvalid()) {
  8099. VDecl->setInvalidDecl();
  8100. return;
  8101. }
  8102. Init = Result.getAs<Expr>();
  8103. assert(Init != nullptr && "otherwise result should be invalid"); // HLSL Change
  8104. }
  8105. // Check for self-references within variable initializers.
  8106. // Variables declared within a function/method body (except for references)
  8107. // are handled by a dataflow analysis.
  8108. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  8109. VDecl->getType()->isReferenceType()) {
  8110. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  8111. }
  8112. // If the type changed, it means we had an incomplete type that was
  8113. // completed by the initializer. For example:
  8114. // int ary[] = { 1, 3, 5 };
  8115. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  8116. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  8117. VDecl->setType(DclT);
  8118. #if 0 // HLSL Change Starts - no ObjC support
  8119. if (!VDecl->isInvalidDecl()) {
  8120. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  8121. if (VDecl->hasAttr<BlocksAttr>())
  8122. checkRetainCycles(VDecl, Init);
  8123. // It is safe to assign a weak reference into a strong variable.
  8124. // Although this code can still have problems:
  8125. // id x = self.weakProp;
  8126. // id y = self.weakProp;
  8127. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8128. // paths through the function. This should be revisited if
  8129. // -Wrepeated-use-of-weak is made flow-sensitive.
  8130. if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
  8131. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8132. Init->getLocStart()))
  8133. getCurFunction()->markSafeWeakUse(Init);
  8134. }
  8135. #endif // HLSL Change Ends - no ObjC support
  8136. // The initialization is usually a full-expression.
  8137. //
  8138. // FIXME: If this is a braced initialization of an aggregate, it is not
  8139. // an expression, and each individual field initializer is a separate
  8140. // full-expression. For instance, in:
  8141. //
  8142. // struct Temp { ~Temp(); };
  8143. // struct S { S(Temp); };
  8144. // struct T { S a, b; } t = { Temp(), Temp() }
  8145. //
  8146. // we should destroy the first Temp before constructing the second.
  8147. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  8148. false,
  8149. VDecl->isConstexpr());
  8150. if (Result.isInvalid()) {
  8151. VDecl->setInvalidDecl();
  8152. return;
  8153. }
  8154. Init = Result.get();
  8155. // Attach the initializer to the decl.
  8156. VDecl->setInit(Init);
  8157. if (VDecl->isLocalVarDecl()) {
  8158. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  8159. // static storage duration shall be constant expressions or string literals.
  8160. // C++ does not have this restriction.
  8161. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
  8162. const Expr *Culprit;
  8163. if (VDecl->getStorageClass() == SC_Static)
  8164. CheckForConstantInitializer(Init, DclT);
  8165. // C89 is stricter than C99 for non-static aggregate types.
  8166. // C89 6.5.7p3: All the expressions [...] in an initializer list
  8167. // for an object that has aggregate or union type shall be
  8168. // constant expressions.
  8169. else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  8170. isa<InitListExpr>(Init) &&
  8171. !Init->isConstantInitializer(Context, false, &Culprit))
  8172. Diag(Culprit->getExprLoc(),
  8173. diag::ext_aggregate_init_not_constant)
  8174. << Culprit->getSourceRange();
  8175. }
  8176. } else if (VDecl->isStaticDataMember() &&
  8177. VDecl->getLexicalDeclContext()->isRecord()) {
  8178. // This is an in-class initialization for a static data member, e.g.,
  8179. //
  8180. // struct S {
  8181. // static const int value = 17;
  8182. // };
  8183. // C++ [class.mem]p4:
  8184. // A member-declarator can contain a constant-initializer only
  8185. // if it declares a static member (9.4) of const integral or
  8186. // const enumeration type, see 9.4.2.
  8187. //
  8188. // C++11 [class.static.data]p3:
  8189. // If a non-volatile const static data member is of integral or
  8190. // enumeration type, its declaration in the class definition can
  8191. // specify a brace-or-equal-initializer in which every initalizer-clause
  8192. // that is an assignment-expression is a constant expression. A static
  8193. // data member of literal type can be declared in the class definition
  8194. // with the constexpr specifier; if so, its declaration shall specify a
  8195. // brace-or-equal-initializer in which every initializer-clause that is
  8196. // an assignment-expression is a constant expression.
  8197. // Do nothing on dependent types.
  8198. if (DclT->isDependentType()) {
  8199. // Allow any 'static constexpr' members, whether or not they are of literal
  8200. // type. We separately check that every constexpr variable is of literal
  8201. // type.
  8202. } else if (VDecl->isConstexpr()) {
  8203. // Require constness.
  8204. } else if (!DclT.isConstQualified()) {
  8205. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  8206. << Init->getSourceRange();
  8207. VDecl->setInvalidDecl();
  8208. // We allow integer constant expressions in all cases.
  8209. } else if (DclT->isIntegralOrEnumerationType()) {
  8210. // Check whether the expression is a constant expression.
  8211. SourceLocation Loc;
  8212. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  8213. // In C++11, a non-constexpr const static data member with an
  8214. // in-class initializer cannot be volatile.
  8215. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  8216. else if (Init->isValueDependent())
  8217. ; // Nothing to check.
  8218. else if (Init->isIntegerConstantExpr(Context, &Loc))
  8219. ; // Ok, it's an ICE!
  8220. else if (Init->isEvaluatable(Context)) {
  8221. // If we can constant fold the initializer through heroics, accept it,
  8222. // but report this as a use of an extension for -pedantic.
  8223. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  8224. << Init->getSourceRange();
  8225. } else {
  8226. // Otherwise, this is some crazy unknown case. Report the issue at the
  8227. // location provided by the isIntegerConstantExpr failed check.
  8228. Diag(Loc, diag::err_in_class_initializer_non_constant)
  8229. << Init->getSourceRange();
  8230. VDecl->setInvalidDecl();
  8231. }
  8232. // We allow foldable floating-point constants as an extension.
  8233. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  8234. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  8235. // it anyway and provide a fixit to add the 'constexpr'.
  8236. if (getLangOpts().CPlusPlus11) {
  8237. Diag(VDecl->getLocation(),
  8238. diag::ext_in_class_initializer_float_type_cxx11)
  8239. << DclT << Init->getSourceRange();
  8240. Diag(VDecl->getLocStart(),
  8241. diag::note_in_class_initializer_float_type_cxx11)
  8242. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8243. } else {
  8244. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  8245. << DclT << Init->getSourceRange();
  8246. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  8247. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  8248. << Init->getSourceRange();
  8249. VDecl->setInvalidDecl();
  8250. }
  8251. }
  8252. // Suggest adding 'constexpr' in C++11 for literal types.
  8253. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  8254. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  8255. << DclT << Init->getSourceRange()
  8256. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8257. VDecl->setConstexpr(true);
  8258. } else {
  8259. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  8260. << DclT << Init->getSourceRange();
  8261. VDecl->setInvalidDecl();
  8262. }
  8263. } else if (VDecl->isFileVarDecl()) {
  8264. if (VDecl->getStorageClass() == SC_Extern &&
  8265. (!getLangOpts().CPlusPlus ||
  8266. !VDecl->isExternC()) &&
  8267. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  8268. Diag(VDecl->getLocation(), diag::warn_extern_init);
  8269. // C99 6.7.8p4. All file scoped initializers need to be constant.
  8270. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  8271. CheckForConstantInitializer(Init, DclT);
  8272. }
  8273. // We will represent direct-initialization similarly to copy-initialization:
  8274. // int x(1); -as-> int x = 1;
  8275. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  8276. //
  8277. // Clients that want to distinguish between the two forms, can check for
  8278. // direct initializer using VarDecl::getInitStyle().
  8279. // A major benefit is that clients that don't particularly care about which
  8280. // exactly form was it (like the CodeGen) can handle both cases without
  8281. // special case code.
  8282. // C++ 8.5p11:
  8283. // The form of initialization (using parentheses or '=') is generally
  8284. // insignificant, but does matter when the entity being initialized has a
  8285. // class type.
  8286. if (CXXDirectInit) {
  8287. assert(DirectInit && "Call-style initializer must be direct init.");
  8288. VDecl->setInitStyle(VarDecl::CallInit);
  8289. } else if (DirectInit) {
  8290. // This must be list-initialization. No other way is direct-initialization.
  8291. VDecl->setInitStyle(VarDecl::ListInit);
  8292. }
  8293. CheckCompleteVariableDeclaration(VDecl);
  8294. }
  8295. /// ActOnInitializerError - Given that there was an error parsing an
  8296. /// initializer for the given declaration, try to return to some form
  8297. /// of sanity.
  8298. void Sema::ActOnInitializerError(Decl *D) {
  8299. // Our main concern here is re-establishing invariants like "a
  8300. // variable's type is either dependent or complete".
  8301. if (!D || D->isInvalidDecl()) return;
  8302. VarDecl *VD = dyn_cast<VarDecl>(D);
  8303. if (!VD) return;
  8304. // Auto types are meaningless if we can't make sense of the initializer.
  8305. if (ParsingInitForAutoVars.count(D)) {
  8306. D->setInvalidDecl();
  8307. return;
  8308. }
  8309. QualType Ty = VD->getType();
  8310. if (Ty->isDependentType()) return;
  8311. // Require a complete type.
  8312. if (RequireCompleteType(VD->getLocation(),
  8313. Context.getBaseElementType(Ty),
  8314. diag::err_typecheck_decl_incomplete_type)) {
  8315. VD->setInvalidDecl();
  8316. return;
  8317. }
  8318. // Require a non-abstract type.
  8319. if (RequireNonAbstractType(VD->getLocation(), Ty,
  8320. diag::err_abstract_type_in_decl,
  8321. AbstractVariableType)) {
  8322. VD->setInvalidDecl();
  8323. return;
  8324. }
  8325. // Don't bother complaining about constructors or destructors,
  8326. // though.
  8327. }
  8328. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  8329. bool TypeMayContainAuto) {
  8330. // If there is no declaration, there was an error parsing it. Just ignore it.
  8331. if (!RealDecl)
  8332. return;
  8333. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  8334. QualType Type = Var->getType();
  8335. // C++11 [dcl.spec.auto]p3
  8336. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  8337. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  8338. << Var->getDeclName() << Type;
  8339. Var->setInvalidDecl();
  8340. return;
  8341. }
  8342. // C++11 [class.static.data]p3: A static data member can be declared with
  8343. // the constexpr specifier; if so, its declaration shall specify
  8344. // a brace-or-equal-initializer.
  8345. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  8346. // the definition of a variable [...] or the declaration of a static data
  8347. // member.
  8348. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  8349. if (Var->isStaticDataMember())
  8350. Diag(Var->getLocation(),
  8351. diag::err_constexpr_static_mem_var_requires_init)
  8352. << Var->getDeclName();
  8353. else
  8354. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  8355. Var->setInvalidDecl();
  8356. return;
  8357. }
  8358. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  8359. // be initialized.
  8360. if (!Var->isInvalidDecl() &&
  8361. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  8362. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  8363. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  8364. Var->setInvalidDecl();
  8365. return;
  8366. }
  8367. switch (Var->isThisDeclarationADefinition()) {
  8368. case VarDecl::Definition:
  8369. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  8370. break;
  8371. // We have an out-of-line definition of a static data member
  8372. // that has an in-class initializer, so we type-check this like
  8373. // a declaration.
  8374. //
  8375. // Fall through
  8376. case VarDecl::DeclarationOnly:
  8377. // It's only a declaration.
  8378. // Block scope. C99 6.7p7: If an identifier for an object is
  8379. // declared with no linkage (C99 6.2.2p6), the type for the
  8380. // object shall be complete.
  8381. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  8382. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  8383. RequireCompleteType(Var->getLocation(), Type,
  8384. diag::err_typecheck_decl_incomplete_type))
  8385. Var->setInvalidDecl();
  8386. // Make sure that the type is not abstract.
  8387. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  8388. RequireNonAbstractType(Var->getLocation(), Type,
  8389. diag::err_abstract_type_in_decl,
  8390. AbstractVariableType))
  8391. Var->setInvalidDecl();
  8392. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  8393. Var->getStorageClass() == SC_PrivateExtern) {
  8394. Diag(Var->getLocation(), diag::warn_private_extern);
  8395. Diag(Var->getLocation(), diag::note_private_extern);
  8396. }
  8397. return;
  8398. case VarDecl::TentativeDefinition:
  8399. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  8400. // object that has file scope without an initializer, and without a
  8401. // storage-class specifier or with the storage-class specifier "static",
  8402. // constitutes a tentative definition. Note: A tentative definition with
  8403. // external linkage is valid (C99 6.2.2p5).
  8404. if (!Var->isInvalidDecl()) {
  8405. if (const IncompleteArrayType *ArrayT
  8406. = Context.getAsIncompleteArrayType(Type)) {
  8407. if (RequireCompleteType(Var->getLocation(),
  8408. ArrayT->getElementType(),
  8409. diag::err_illegal_decl_array_incomplete_type))
  8410. Var->setInvalidDecl();
  8411. } else if (Var->getStorageClass() == SC_Static) {
  8412. // C99 6.9.2p3: If the declaration of an identifier for an object is
  8413. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  8414. // declared type shall not be an incomplete type.
  8415. // NOTE: code such as the following
  8416. // static struct s;
  8417. // struct s { int a; };
  8418. // is accepted by gcc. Hence here we issue a warning instead of
  8419. // an error and we do not invalidate the static declaration.
  8420. // NOTE: to avoid multiple warnings, only check the first declaration.
  8421. if (Var->isFirstDecl())
  8422. RequireCompleteType(Var->getLocation(), Type,
  8423. diag::ext_typecheck_decl_incomplete_type);
  8424. }
  8425. }
  8426. // Record the tentative definition; we're done.
  8427. if (!Var->isInvalidDecl())
  8428. TentativeDefinitions.push_back(Var);
  8429. return;
  8430. }
  8431. // Provide a specific diagnostic for uninitialized variable
  8432. // definitions with incomplete array type.
  8433. if (Type->isIncompleteArrayType()
  8434. // HLSL Change Starts
  8435. // Allow incomplete resource array.
  8436. && !hlsl::IsIncompleteHLSLResourceArrayType(getASTContext(), Type)
  8437. // Allow incomplete ConstantBufferView array.
  8438. && !(IsOnHLSLBufferView())
  8439. // HLSL Change Ends
  8440. ) {
  8441. Diag(Var->getLocation(),
  8442. diag::err_typecheck_incomplete_array_needs_initializer);
  8443. Var->setInvalidDecl();
  8444. return;
  8445. }
  8446. // Provide a specific diagnostic for uninitialized variable
  8447. // definitions with reference type.
  8448. if (Type->isReferenceType()) {
  8449. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  8450. << Var->getDeclName()
  8451. << SourceRange(Var->getLocation(), Var->getLocation());
  8452. Var->setInvalidDecl();
  8453. return;
  8454. }
  8455. // Do not attempt to type-check the default initializer for a
  8456. // variable with dependent type.
  8457. if (Type->isDependentType())
  8458. return;
  8459. if (Var->isInvalidDecl())
  8460. return;
  8461. if (!Var->hasAttr<AliasAttr>()) {
  8462. if (RequireCompleteType(Var->getLocation(),
  8463. Context.getBaseElementType(Type),
  8464. diag::err_typecheck_decl_incomplete_type)) {
  8465. Var->setInvalidDecl();
  8466. return;
  8467. }
  8468. } else {
  8469. return;
  8470. }
  8471. // The variable can not have an abstract class type.
  8472. if (RequireNonAbstractType(Var->getLocation(), Type,
  8473. diag::err_abstract_type_in_decl,
  8474. AbstractVariableType)) {
  8475. Var->setInvalidDecl();
  8476. return;
  8477. }
  8478. // Check for jumps past the implicit initializer. C++0x
  8479. // clarifies that this applies to a "variable with automatic
  8480. // storage duration", not a "local variable".
  8481. // C++11 [stmt.dcl]p3
  8482. // A program that jumps from a point where a variable with automatic
  8483. // storage duration is not in scope to a point where it is in scope is
  8484. // ill-formed unless the variable has scalar type, class type with a
  8485. // trivial default constructor and a trivial destructor, a cv-qualified
  8486. // version of one of these types, or an array of one of the preceding
  8487. // types and is declared without an initializer.
  8488. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  8489. if (const RecordType *Record
  8490. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  8491. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  8492. // Mark the function for further checking even if the looser rules of
  8493. // C++11 do not require such checks, so that we can diagnose
  8494. // incompatibilities with C++98.
  8495. if (!CXXRecord->isPOD())
  8496. getCurFunction()->setHasBranchProtectedScope();
  8497. }
  8498. }
  8499. // C++03 [dcl.init]p9:
  8500. // If no initializer is specified for an object, and the
  8501. // object is of (possibly cv-qualified) non-POD class type (or
  8502. // array thereof), the object shall be default-initialized; if
  8503. // the object is of const-qualified type, the underlying class
  8504. // type shall have a user-declared default
  8505. // constructor. Otherwise, if no initializer is specified for
  8506. // a non- static object, the object and its subobjects, if
  8507. // any, have an indeterminate initial value); if the object
  8508. // or any of its subobjects are of const-qualified type, the
  8509. // program is ill-formed.
  8510. // C++0x [dcl.init]p11:
  8511. // If no initializer is specified for an object, the object is
  8512. // default-initialized; [...].
  8513. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  8514. InitializationKind Kind
  8515. = InitializationKind::CreateDefault(Var->getLocation());
  8516. InitializationSequence InitSeq(*this, Entity, Kind, None);
  8517. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  8518. if (Init.isInvalid())
  8519. Var->setInvalidDecl();
  8520. else if (Init.get()) {
  8521. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  8522. // This is important for template substitution.
  8523. Var->setInitStyle(VarDecl::CallInit);
  8524. }
  8525. CheckCompleteVariableDeclaration(Var);
  8526. }
  8527. }
  8528. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  8529. VarDecl *VD = dyn_cast<VarDecl>(D);
  8530. if (!VD) {
  8531. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  8532. D->setInvalidDecl();
  8533. return;
  8534. }
  8535. VD->setCXXForRangeDecl(true);
  8536. // for-range-declaration cannot be given a storage class specifier.
  8537. int Error = -1;
  8538. switch (VD->getStorageClass()) {
  8539. case SC_None:
  8540. break;
  8541. case SC_Extern:
  8542. Error = 0;
  8543. break;
  8544. case SC_Static:
  8545. Error = 1;
  8546. break;
  8547. case SC_PrivateExtern:
  8548. Error = 2;
  8549. break;
  8550. case SC_Auto:
  8551. Error = 3;
  8552. break;
  8553. case SC_Register:
  8554. Error = 4;
  8555. break;
  8556. case SC_OpenCLWorkGroupLocal:
  8557. llvm_unreachable("Unexpected storage class");
  8558. }
  8559. if (Error != -1) {
  8560. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  8561. << VD->getDeclName() << Error;
  8562. D->setInvalidDecl();
  8563. }
  8564. }
  8565. StmtResult
  8566. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  8567. IdentifierInfo *Ident,
  8568. ParsedAttributes &Attrs,
  8569. SourceLocation AttrEnd) {
  8570. // C++1y [stmt.iter]p1:
  8571. // A range-based for statement of the form
  8572. // for ( for-range-identifier : for-range-initializer ) statement
  8573. // is equivalent to
  8574. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  8575. DeclSpec DS(Attrs.getPool().getFactory());
  8576. const char *PrevSpec;
  8577. unsigned DiagID;
  8578. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  8579. getPrintingPolicy());
  8580. Declarator D(DS, Declarator::ForContext);
  8581. D.SetIdentifier(Ident, IdentLoc);
  8582. D.takeAttributes(Attrs, AttrEnd);
  8583. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  8584. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  8585. EmptyAttrs, IdentLoc);
  8586. Decl *Var = ActOnDeclarator(S, D);
  8587. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  8588. FinalizeDeclaration(Var);
  8589. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  8590. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  8591. }
  8592. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  8593. if (var->isInvalidDecl()) return;
  8594. // In ARC, don't allow jumps past the implicit initialization of a
  8595. // local retaining variable.
  8596. if (getLangOpts().ObjCAutoRefCount &&
  8597. var->hasLocalStorage()) {
  8598. switch (var->getType().getObjCLifetime()) {
  8599. case Qualifiers::OCL_None:
  8600. case Qualifiers::OCL_ExplicitNone:
  8601. case Qualifiers::OCL_Autoreleasing:
  8602. break;
  8603. case Qualifiers::OCL_Weak:
  8604. case Qualifiers::OCL_Strong:
  8605. getCurFunction()->setHasBranchProtectedScope();
  8606. break;
  8607. }
  8608. }
  8609. // Warn about externally-visible variables being defined without a
  8610. // prior declaration. We only want to do this for global
  8611. // declarations, but we also specifically need to avoid doing it for
  8612. // class members because the linkage of an anonymous class can
  8613. // change if it's later given a typedef name.
  8614. if (var->isThisDeclarationADefinition() &&
  8615. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  8616. var->isExternallyVisible() && var->hasLinkage() &&
  8617. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  8618. var->getLocation())) {
  8619. // Find a previous declaration that's not a definition.
  8620. VarDecl *prev = var->getPreviousDecl();
  8621. while (prev && prev->isThisDeclarationADefinition())
  8622. prev = prev->getPreviousDecl();
  8623. if (!prev)
  8624. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  8625. }
  8626. if (var->getTLSKind() == VarDecl::TLS_Static) {
  8627. const Expr *Culprit;
  8628. if (var->getType().isDestructedType()) {
  8629. // GNU C++98 edits for __thread, [basic.start.term]p3:
  8630. // The type of an object with thread storage duration shall not
  8631. // have a non-trivial destructor.
  8632. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  8633. if (getLangOpts().CPlusPlus11)
  8634. Diag(var->getLocation(), diag::note_use_thread_local);
  8635. } else if (getLangOpts().CPlusPlus && var->hasInit() &&
  8636. !var->getInit()->isConstantInitializer(
  8637. Context, var->getType()->isReferenceType(), &Culprit)) {
  8638. // GNU C++98 edits for __thread, [basic.start.init]p4:
  8639. // An object of thread storage duration shall not require dynamic
  8640. // initialization.
  8641. // FIXME: Need strict checking here.
  8642. Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
  8643. << Culprit->getSourceRange();
  8644. if (getLangOpts().CPlusPlus11)
  8645. Diag(var->getLocation(), diag::note_use_thread_local);
  8646. }
  8647. }
  8648. // Apply section attributes and pragmas to global variables.
  8649. bool GlobalStorage = var->hasGlobalStorage();
  8650. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  8651. ActiveTemplateInstantiations.empty()) {
  8652. PragmaStack<StringLiteral *> *Stack = nullptr;
  8653. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  8654. if (var->getType().isConstQualified()
  8655. // HLSL Change: for HLSL, const initialized isn't the same, unless static
  8656. && (!getLangOpts().HLSL ||
  8657. var->getTLSKind() == VarDecl::TLS_Static)
  8658. )
  8659. Stack = &ConstSegStack;
  8660. else if (!var->getInit()) {
  8661. Stack = &BSSSegStack;
  8662. SectionFlags |= ASTContext::PSF_Write;
  8663. } else {
  8664. Stack = &DataSegStack;
  8665. SectionFlags |= ASTContext::PSF_Write;
  8666. }
  8667. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  8668. var->addAttr(SectionAttr::CreateImplicit(
  8669. Context, SectionAttr::Declspec_allocate,
  8670. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  8671. }
  8672. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  8673. if (UnifySection(SA->getName(), SectionFlags, var))
  8674. var->dropAttr<SectionAttr>();
  8675. // Apply the init_seg attribute if this has an initializer. If the
  8676. // initializer turns out to not be dynamic, we'll end up ignoring this
  8677. // attribute.
  8678. if (CurInitSeg && var->getInit())
  8679. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  8680. CurInitSegLoc));
  8681. }
  8682. // All the following checks are C++ only.
  8683. if (!getLangOpts().CPlusPlus) return;
  8684. QualType type = var->getType();
  8685. if (type->isDependentType()) return;
  8686. // __block variables might require us to capture a copy-initializer.
  8687. if (var->hasAttr<BlocksAttr>()) {
  8688. // It's currently invalid to ever have a __block variable with an
  8689. // array type; should we diagnose that here?
  8690. // Regardless, we don't want to ignore array nesting when
  8691. // constructing this copy.
  8692. if (type->isStructureOrClassType()) {
  8693. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  8694. SourceLocation poi = var->getLocation();
  8695. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  8696. ExprResult result
  8697. = PerformMoveOrCopyInitialization(
  8698. InitializedEntity::InitializeBlock(poi, type, false),
  8699. var, var->getType(), varRef, /*AllowNRVO=*/true);
  8700. if (!result.isInvalid()) {
  8701. result = MaybeCreateExprWithCleanups(result);
  8702. Expr *init = result.getAs<Expr>();
  8703. Context.setBlockVarCopyInits(var, init);
  8704. }
  8705. }
  8706. }
  8707. Expr *Init = var->getInit();
  8708. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  8709. QualType baseType = Context.getBaseElementType(type);
  8710. if (!var->getDeclContext()->isDependentContext() &&
  8711. Init && !Init->isValueDependent()) {
  8712. if (IsGlobal && !var->isConstexpr() &&
  8713. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  8714. var->getLocation())) {
  8715. // Warn about globals which don't have a constant initializer. Don't
  8716. // warn about globals with a non-trivial destructor because we already
  8717. // warned about them.
  8718. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  8719. if (!(RD && !RD->hasTrivialDestructor()) &&
  8720. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  8721. Diag(var->getLocation(), diag::warn_global_constructor)
  8722. << Init->getSourceRange();
  8723. }
  8724. if (var->isConstexpr()) {
  8725. SmallVector<PartialDiagnosticAt, 8> Notes;
  8726. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  8727. SourceLocation DiagLoc = var->getLocation();
  8728. // If the note doesn't add any useful information other than a source
  8729. // location, fold it into the primary diagnostic.
  8730. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  8731. diag::note_invalid_subexpr_in_const_expr) {
  8732. DiagLoc = Notes[0].first;
  8733. Notes.clear();
  8734. }
  8735. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  8736. << var << Init->getSourceRange();
  8737. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  8738. Diag(Notes[I].first, Notes[I].second);
  8739. }
  8740. } else if (var->isUsableInConstantExpressions(Context)) {
  8741. // Check whether the initializer of a const variable of integral or
  8742. // enumeration type is an ICE now, since we can't tell whether it was
  8743. // initialized by a constant expression if we check later.
  8744. var->checkInitIsICE();
  8745. }
  8746. }
  8747. // Require the destructor.
  8748. if (const RecordType *recordType = baseType->getAs<RecordType>())
  8749. FinalizeVarWithDestructor(var, recordType);
  8750. }
  8751. /// \brief Determines if a variable's alignment is dependent.
  8752. static bool hasDependentAlignment(VarDecl *VD) {
  8753. if (VD->getType()->isDependentType())
  8754. return true;
  8755. for (auto *I : VD->specific_attrs<AlignedAttr>())
  8756. if (I->isAlignmentDependent())
  8757. return true;
  8758. return false;
  8759. }
  8760. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  8761. /// any semantic actions necessary after any initializer has been attached.
  8762. void
  8763. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  8764. // Note that we are no longer parsing the initializer for this declaration.
  8765. ParsingInitForAutoVars.erase(ThisDecl);
  8766. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  8767. if (!VD)
  8768. return;
  8769. checkAttributesAfterMerging(*this, *VD);
  8770. // Perform TLS alignment check here after attributes attached to the variable
  8771. // which may affect the alignment have been processed. Only perform the check
  8772. // if the target has a maximum TLS alignment (zero means no constraints).
  8773. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  8774. // Protect the check so that it's not performed on dependent types and
  8775. // dependent alignments (we can't determine the alignment in that case).
  8776. if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
  8777. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  8778. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  8779. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  8780. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  8781. << (unsigned)MaxAlignChars.getQuantity();
  8782. }
  8783. }
  8784. }
  8785. // Static locals inherit dll attributes from their function.
  8786. if (VD->isStaticLocal()) {
  8787. if (FunctionDecl *FD =
  8788. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  8789. if (Attr *A = getDLLAttr(FD)) {
  8790. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  8791. NewAttr->setInherited(true);
  8792. VD->addAttr(NewAttr);
  8793. }
  8794. }
  8795. }
  8796. // Grab the dllimport or dllexport attribute off of the VarDecl.
  8797. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  8798. // Imported static data members cannot be defined out-of-line.
  8799. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  8800. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  8801. VD->isThisDeclarationADefinition()) {
  8802. // We allow definitions of dllimport class template static data members
  8803. // with a warning.
  8804. CXXRecordDecl *Context =
  8805. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  8806. bool IsClassTemplateMember =
  8807. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  8808. Context->getDescribedClassTemplate();
  8809. Diag(VD->getLocation(),
  8810. IsClassTemplateMember
  8811. ? diag::warn_attribute_dllimport_static_field_definition
  8812. : diag::err_attribute_dllimport_static_field_definition);
  8813. Diag(IA->getLocation(), diag::note_attribute);
  8814. if (!IsClassTemplateMember)
  8815. VD->setInvalidDecl();
  8816. }
  8817. }
  8818. // dllimport/dllexport variables cannot be thread local, their TLS index
  8819. // isn't exported with the variable.
  8820. if (DLLAttr && VD->getTLSKind()) {
  8821. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  8822. << DLLAttr;
  8823. VD->setInvalidDecl();
  8824. }
  8825. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  8826. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  8827. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  8828. VD->dropAttr<UsedAttr>();
  8829. }
  8830. }
  8831. const DeclContext *DC = VD->getDeclContext();
  8832. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8833. // member, set the visibility of this variable.
  8834. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  8835. AddPushedVisibilityAttribute(VD);
  8836. // FIXME: Warn on unused templates.
  8837. if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
  8838. !isa<VarTemplatePartialSpecializationDecl>(VD))
  8839. MarkUnusedFileScopedDecl(VD);
  8840. // Now we have parsed the initializer and can update the table of magic
  8841. // tag values.
  8842. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  8843. !VD->getType()->isIntegralOrEnumerationType())
  8844. return;
  8845. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  8846. const Expr *MagicValueExpr = VD->getInit();
  8847. if (!MagicValueExpr) {
  8848. continue;
  8849. }
  8850. llvm::APSInt MagicValueInt;
  8851. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  8852. Diag(I->getRange().getBegin(),
  8853. diag::err_type_tag_for_datatype_not_ice)
  8854. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  8855. continue;
  8856. }
  8857. if (MagicValueInt.getActiveBits() > 64) {
  8858. Diag(I->getRange().getBegin(),
  8859. diag::err_type_tag_for_datatype_too_large)
  8860. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  8861. continue;
  8862. }
  8863. uint64_t MagicValue = MagicValueInt.getZExtValue();
  8864. RegisterTypeTagForDatatype(I->getArgumentKind(),
  8865. MagicValue,
  8866. I->getMatchingCType(),
  8867. I->getLayoutCompatible(),
  8868. I->getMustBeNull());
  8869. }
  8870. }
  8871. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  8872. ArrayRef<Decl *> Group) {
  8873. SmallVector<Decl*, 8> Decls;
  8874. if (DS.isTypeSpecOwned())
  8875. Decls.push_back(DS.getRepAsDecl());
  8876. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  8877. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8878. if (Decl *D = Group[i]) {
  8879. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
  8880. if (!FirstDeclaratorInGroup)
  8881. FirstDeclaratorInGroup = DD;
  8882. Decls.push_back(D);
  8883. }
  8884. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  8885. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  8886. handleTagNumbering(Tag, S);
  8887. if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
  8888. Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
  8889. }
  8890. }
  8891. return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
  8892. }
  8893. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  8894. /// group, performing any necessary semantic checking.
  8895. Sema::DeclGroupPtrTy
  8896. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
  8897. bool TypeMayContainAuto) {
  8898. // C++0x [dcl.spec.auto]p7:
  8899. // If the type deduced for the template parameter U is not the same in each
  8900. // deduction, the program is ill-formed.
  8901. // FIXME: When initializer-list support is added, a distinction is needed
  8902. // between the deduced type U and the deduced type which 'auto' stands for.
  8903. // auto a = 0, b = { 1, 2, 3 };
  8904. // is legal because the deduced type U is 'int' in both cases.
  8905. if (TypeMayContainAuto && Group.size() > 1) {
  8906. QualType Deduced;
  8907. CanQualType DeducedCanon;
  8908. VarDecl *DeducedDecl = nullptr;
  8909. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  8910. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  8911. AutoType *AT = D->getType()->getContainedAutoType();
  8912. // Don't reissue diagnostics when instantiating a template.
  8913. if (AT && D->isInvalidDecl())
  8914. break;
  8915. QualType U = AT ? AT->getDeducedType() : QualType();
  8916. if (!U.isNull()) {
  8917. CanQualType UCanon = Context.getCanonicalType(U);
  8918. if (Deduced.isNull()) {
  8919. Deduced = U;
  8920. DeducedCanon = UCanon;
  8921. DeducedDecl = D;
  8922. } else if (DeducedCanon != UCanon) {
  8923. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  8924. diag::err_auto_different_deductions)
  8925. << (AT->isDecltypeAuto() ? 1 : 0)
  8926. << Deduced << DeducedDecl->getDeclName()
  8927. << U << D->getDeclName()
  8928. << DeducedDecl->getInit()->getSourceRange()
  8929. << D->getInit()->getSourceRange();
  8930. D->setInvalidDecl();
  8931. break;
  8932. }
  8933. }
  8934. }
  8935. }
  8936. }
  8937. ActOnDocumentableDecls(Group);
  8938. return DeclGroupPtrTy::make(
  8939. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  8940. }
  8941. void Sema::ActOnDocumentableDecl(Decl *D) {
  8942. ActOnDocumentableDecls(D);
  8943. }
  8944. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  8945. // Don't parse the comment if Doxygen diagnostics are ignored.
  8946. if (Group.empty() || !Group[0])
  8947. return;
  8948. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  8949. Group[0]->getLocation()) &&
  8950. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  8951. Group[0]->getLocation()))
  8952. return;
  8953. if (Group.size() >= 2) {
  8954. // This is a decl group. Normally it will contain only declarations
  8955. // produced from declarator list. But in case we have any definitions or
  8956. // additional declaration references:
  8957. // 'typedef struct S {} S;'
  8958. // 'typedef struct S *S;'
  8959. // 'struct S *pS;'
  8960. // FinalizeDeclaratorGroup adds these as separate declarations.
  8961. Decl *MaybeTagDecl = Group[0];
  8962. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  8963. Group = Group.slice(1);
  8964. }
  8965. }
  8966. // See if there are any new comments that are not attached to a decl.
  8967. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  8968. if (!Comments.empty() &&
  8969. !Comments.back()->isAttached()) {
  8970. // There is at least one comment that not attached to a decl.
  8971. // Maybe it should be attached to one of these decls?
  8972. //
  8973. // Note that this way we pick up not only comments that precede the
  8974. // declaration, but also comments that *follow* the declaration -- thanks to
  8975. // the lookahead in the lexer: we've consumed the semicolon and looked
  8976. // ahead through comments.
  8977. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8978. Context.getCommentForDecl(Group[i], &PP);
  8979. }
  8980. }
  8981. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  8982. /// to introduce parameters into function prototype scope.
  8983. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  8984. const DeclSpec &DS = D.getDeclSpec();
  8985. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  8986. // C++03 [dcl.stc]p2 also permits 'auto'.
  8987. StorageClass SC = SC_None;
  8988. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  8989. SC = SC_Register;
  8990. } else if (getLangOpts().CPlusPlus &&
  8991. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  8992. SC = SC_Auto;
  8993. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  8994. Diag(DS.getStorageClassSpecLoc(),
  8995. diag::err_invalid_storage_class_in_func_decl);
  8996. D.getMutableDeclSpec().ClearStorageClassSpecs();
  8997. }
  8998. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  8999. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  9000. << DeclSpec::getSpecifierName(TSCS);
  9001. if (DS.isConstexprSpecified())
  9002. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  9003. << 0;
  9004. DiagnoseFunctionSpecifiers(DS);
  9005. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  9006. QualType parmDeclType = TInfo->getType();
  9007. if (getLangOpts().CPlusPlus) {
  9008. // Check that there are no default arguments inside the type of this
  9009. // parameter.
  9010. CheckExtraCXXDefaultArguments(D);
  9011. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  9012. if (D.getCXXScopeSpec().isSet()) {
  9013. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  9014. << D.getCXXScopeSpec().getRange();
  9015. D.getCXXScopeSpec().clear();
  9016. }
  9017. }
  9018. // Ensure we have a valid name
  9019. IdentifierInfo *II = nullptr;
  9020. if (D.hasName()) {
  9021. II = D.getIdentifier();
  9022. if (!II) {
  9023. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  9024. << GetNameForDeclarator(D).getName();
  9025. D.setInvalidType(true);
  9026. }
  9027. }
  9028. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  9029. if (II) {
  9030. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  9031. ForRedeclaration);
  9032. LookupName(R, S);
  9033. if (R.isSingleResult()) {
  9034. NamedDecl *PrevDecl = R.getFoundDecl();
  9035. if (PrevDecl->isTemplateParameter()) {
  9036. // Maybe we will complain about the shadowed template parameter.
  9037. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  9038. // Just pretend that we didn't see the previous declaration.
  9039. PrevDecl = nullptr;
  9040. } else if (S->isDeclScope(PrevDecl)) {
  9041. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  9042. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  9043. // Recover by removing the name
  9044. II = nullptr;
  9045. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  9046. D.setInvalidType(true);
  9047. }
  9048. }
  9049. }
  9050. // HLSL Change Starts
  9051. if (getLangOpts().HLSL) {
  9052. const bool IsParm = true;
  9053. if (hlsl::IsStringType(parmDeclType)) {
  9054. static const unsigned selectParamIdx = 1;
  9055. Diag(D.getLocStart(), diag::err_hlsl_unsupported_string_decl) << selectParamIdx;
  9056. D.setInvalidType();
  9057. }
  9058. if (!DiagnoseHLSLDecl(D, Context.getTranslationUnitDecl(), /*BitWidth*/ nullptr, TInfo, IsParm)) {
  9059. assert(D.isInvalidType() && "otherwise DiagnoseHLSLDecl failed but "
  9060. "didn't invalidate declaration");
  9061. }
  9062. }
  9063. // HLSL Change Ends
  9064. // Temporarily put parameter variables in the translation unit, not
  9065. // the enclosing context. This prevents them from accidentally
  9066. // looking like class members in C++.
  9067. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  9068. D.getLocStart(),
  9069. D.getIdentifierLoc(), II,
  9070. parmDeclType, TInfo,
  9071. SC, hlsl::ParamModFromAttributeList(DS.getAttributes().getList())); // HLSL Change
  9072. if (D.isInvalidType())
  9073. New->setInvalidDecl();
  9074. TransferUnusualAttributes(D, New); // HLSL Change
  9075. assert(S->isFunctionPrototypeScope());
  9076. assert(S->getFunctionPrototypeDepth() >= 1);
  9077. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  9078. S->getNextFunctionPrototypeIndex());
  9079. // Add the parameter declaration into this scope.
  9080. S->AddDecl(New);
  9081. if (II)
  9082. IdResolver.AddDecl(New);
  9083. ProcessDeclAttributes(S, New, D);
  9084. if (D.getDeclSpec().isModulePrivateSpecified())
  9085. Diag(New->getLocation(), diag::err_module_private_local)
  9086. << 1 << New->getDeclName()
  9087. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  9088. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  9089. if (New->hasAttr<BlocksAttr>()) {
  9090. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  9091. }
  9092. return New;
  9093. }
  9094. /// \brief Synthesizes a variable for a parameter arising from a
  9095. /// typedef.
  9096. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  9097. SourceLocation Loc,
  9098. QualType T) {
  9099. /* FIXME: setting StartLoc == Loc.
  9100. Would it be worth to modify callers so as to provide proper source
  9101. location for the unnamed parameters, embedding the parameter's type? */
  9102. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  9103. T, Context.getTrivialTypeSourceInfo(T, Loc),
  9104. SC_None, nullptr);
  9105. Param->setImplicit();
  9106. return Param;
  9107. }
  9108. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  9109. ParmVarDecl * const *ParamEnd) {
  9110. // Don't diagnose unused-parameter errors in template instantiations; we
  9111. // will already have done so in the template itself.
  9112. if (!ActiveTemplateInstantiations.empty())
  9113. return;
  9114. for (; Param != ParamEnd; ++Param) {
  9115. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  9116. !(*Param)->hasAttr<UnusedAttr>()) {
  9117. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  9118. << (*Param)->getDeclName();
  9119. }
  9120. }
  9121. }
  9122. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  9123. ParmVarDecl * const *ParamEnd,
  9124. QualType ReturnTy,
  9125. NamedDecl *D) {
  9126. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  9127. return;
  9128. // Warn if the return value is pass-by-value and larger than the specified
  9129. // threshold.
  9130. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  9131. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  9132. if (Size > LangOpts.NumLargeByValueCopy)
  9133. Diag(D->getLocation(), diag::warn_return_value_size)
  9134. << D->getDeclName() << Size;
  9135. }
  9136. // Warn if any parameter is pass-by-value and larger than the specified
  9137. // threshold.
  9138. for (; Param != ParamEnd; ++Param) {
  9139. QualType T = (*Param)->getType();
  9140. if (T->isDependentType() || !T.isPODType(Context))
  9141. continue;
  9142. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  9143. if (Size > LangOpts.NumLargeByValueCopy)
  9144. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  9145. << (*Param)->getDeclName() << Size;
  9146. }
  9147. }
  9148. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  9149. SourceLocation NameLoc, IdentifierInfo *Name,
  9150. QualType T, TypeSourceInfo *TSInfo,
  9151. StorageClass SC, hlsl::ParameterModifier ParamMod) { // HLSL Change - add param mod
  9152. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  9153. if (getLangOpts().ObjCAutoRefCount &&
  9154. T.getObjCLifetime() == Qualifiers::OCL_None &&
  9155. T->isObjCLifetimeType()) {
  9156. Qualifiers::ObjCLifetime lifetime;
  9157. // Special cases for arrays:
  9158. // - if it's const, use __unsafe_unretained
  9159. // - otherwise, it's an error
  9160. if (T->isArrayType()) {
  9161. if (!T.isConstQualified()) {
  9162. DelayedDiagnostics.add(
  9163. sema::DelayedDiagnostic::makeForbiddenType(
  9164. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  9165. }
  9166. lifetime = Qualifiers::OCL_ExplicitNone;
  9167. } else {
  9168. lifetime = T->getObjCARCImplicitLifetime();
  9169. }
  9170. T = Context.getLifetimeQualifiedType(T, lifetime);
  9171. }
  9172. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  9173. Context.getAdjustedParameterType(T),
  9174. TSInfo, SC, nullptr, ParamMod);
  9175. // Parameters can not be abstract class types.
  9176. // For record types, this is done by the AbstractClassUsageDiagnoser once
  9177. // the class has been completely parsed.
  9178. if (!CurContext->isRecord() &&
  9179. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  9180. AbstractParamType))
  9181. New->setInvalidDecl();
  9182. // Parameter declarators cannot be interface types. All ObjC objects are
  9183. // passed by reference.
  9184. if (T->isObjCObjectType()) {
  9185. SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
  9186. Diag(NameLoc,
  9187. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  9188. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  9189. T = Context.getObjCObjectPointerType(T);
  9190. New->setType(T);
  9191. }
  9192. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  9193. // duration shall not be qualified by an address-space qualifier."
  9194. // Since all parameters have automatic store duration, they can not have
  9195. // an address space.
  9196. if (T.getAddressSpace() != 0) {
  9197. // OpenCL allows function arguments declared to be an array of a type
  9198. // to be qualified with an address space.
  9199. if (!(getLangOpts().OpenCL && T->isArrayType())) {
  9200. Diag(NameLoc, diag::err_arg_with_address_space);
  9201. New->setInvalidDecl();
  9202. }
  9203. }
  9204. return New;
  9205. }
  9206. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  9207. SourceLocation LocAfterDecls) {
  9208. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9209. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  9210. // for a K&R function.
  9211. if (!FTI.hasPrototype) {
  9212. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  9213. --i;
  9214. if (FTI.Params[i].Param == nullptr) {
  9215. SmallString<256> Code;
  9216. llvm::raw_svector_ostream(Code)
  9217. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  9218. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  9219. << FTI.Params[i].Ident
  9220. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  9221. // Implicitly declare the argument as type 'int' for lack of a better
  9222. // type.
  9223. AttributeFactory attrs;
  9224. DeclSpec DS(attrs);
  9225. const char* PrevSpec; // unused
  9226. unsigned DiagID; // unused
  9227. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  9228. DiagID, Context.getPrintingPolicy());
  9229. // Use the identifier location for the type source range.
  9230. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  9231. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  9232. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  9233. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  9234. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  9235. }
  9236. }
  9237. }
  9238. }
  9239. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
  9240. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  9241. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  9242. Scope *ParentScope = FnBodyScope->getParent();
  9243. D.setFunctionDefinitionKind(FDK_Definition);
  9244. Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
  9245. return ActOnStartOfFunctionDef(FnBodyScope, DP);
  9246. }
  9247. void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
  9248. Consumer.HandleInlineMethodDefinition(D);
  9249. }
  9250. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  9251. const FunctionDecl*& PossibleZeroParamPrototype) {
  9252. // Don't warn about invalid declarations.
  9253. if (FD->isInvalidDecl())
  9254. return false;
  9255. // Or declarations that aren't global.
  9256. if (!FD->isGlobal())
  9257. return false;
  9258. // Don't warn about C++ member functions.
  9259. if (isa<CXXMethodDecl>(FD))
  9260. return false;
  9261. // Don't warn about 'main'.
  9262. if (FD->isMain())
  9263. return false;
  9264. // Don't warn about inline functions.
  9265. if (FD->isInlined())
  9266. return false;
  9267. // Don't warn about function templates.
  9268. if (FD->getDescribedFunctionTemplate())
  9269. return false;
  9270. // Don't warn about function template specializations.
  9271. if (FD->isFunctionTemplateSpecialization())
  9272. return false;
  9273. // Don't warn for OpenCL kernels.
  9274. if (FD->hasAttr<OpenCLKernelAttr>())
  9275. return false;
  9276. // Don't warn on explicitly deleted functions.
  9277. if (FD->isDeleted())
  9278. return false;
  9279. bool MissingPrototype = true;
  9280. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  9281. Prev; Prev = Prev->getPreviousDecl()) {
  9282. // Ignore any declarations that occur in function or method
  9283. // scope, because they aren't visible from the header.
  9284. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  9285. continue;
  9286. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  9287. if (FD->getNumParams() == 0)
  9288. PossibleZeroParamPrototype = Prev;
  9289. break;
  9290. }
  9291. return MissingPrototype;
  9292. }
  9293. void
  9294. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  9295. const FunctionDecl *EffectiveDefinition) {
  9296. // Don't complain if we're in GNU89 mode and the previous definition
  9297. // was an extern inline function.
  9298. const FunctionDecl *Definition = EffectiveDefinition;
  9299. if (!Definition)
  9300. if (!FD->isDefined(Definition))
  9301. return;
  9302. if (canRedefineFunction(Definition, getLangOpts()))
  9303. return;
  9304. // If we don't have a visible definition of the function, and it's inline or
  9305. // a template, it's OK to form another definition of it.
  9306. //
  9307. // FIXME: Should we skip the body of the function and use the old definition
  9308. // in this case? That may be necessary for functions that return local types
  9309. // through a deduced return type, or instantiate templates with local types.
  9310. if (!hasVisibleDefinition(Definition) &&
  9311. (Definition->getFormalLinkage() == InternalLinkage ||
  9312. Definition->isInlined() ||
  9313. Definition->getDescribedFunctionTemplate() ||
  9314. Definition->getNumTemplateParameterLists()))
  9315. return;
  9316. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  9317. Definition->getStorageClass() == SC_Extern)
  9318. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  9319. << FD->getDeclName() << getLangOpts().CPlusPlus;
  9320. else
  9321. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  9322. Diag(Definition->getLocation(), diag::note_previous_definition);
  9323. FD->setInvalidDecl();
  9324. }
  9325. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  9326. Sema &S) {
  9327. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  9328. LambdaScopeInfo *LSI = S.PushLambdaScope();
  9329. LSI->CallOperator = CallOperator;
  9330. LSI->Lambda = LambdaClass;
  9331. LSI->ReturnType = CallOperator->getReturnType();
  9332. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  9333. if (LCD == LCD_None)
  9334. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  9335. else if (LCD == LCD_ByCopy)
  9336. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  9337. else if (LCD == LCD_ByRef)
  9338. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  9339. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  9340. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  9341. LSI->Mutable = !CallOperator->isConst();
  9342. // Add the captures to the LSI so they can be noted as already
  9343. // captured within tryCaptureVar.
  9344. auto I = LambdaClass->field_begin();
  9345. for (const auto &C : LambdaClass->captures()) {
  9346. if (C.capturesVariable()) {
  9347. VarDecl *VD = C.getCapturedVar();
  9348. if (VD->isInitCapture())
  9349. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  9350. QualType CaptureType = VD->getType();
  9351. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  9352. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  9353. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  9354. /*EllipsisLoc*/C.isPackExpansion()
  9355. ? C.getEllipsisLoc() : SourceLocation(),
  9356. CaptureType, /*Expr*/ nullptr);
  9357. } else if (C.capturesThis()) {
  9358. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  9359. S.getCurrentThisType(), /*Expr*/ nullptr);
  9360. } else {
  9361. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  9362. }
  9363. ++I;
  9364. }
  9365. }
  9366. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
  9367. // Clear the last template instantiation error context.
  9368. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  9369. if (!D)
  9370. return D;
  9371. FunctionDecl *FD = nullptr;
  9372. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  9373. FD = FunTmpl->getTemplatedDecl();
  9374. else
  9375. FD = cast<FunctionDecl>(D);
  9376. // If we are instantiating a generic lambda call operator, push
  9377. // a LambdaScopeInfo onto the function stack. But use the information
  9378. // that's already been calculated (ActOnLambdaExpr) to prime the current
  9379. // LambdaScopeInfo.
  9380. // When the template operator is being specialized, the LambdaScopeInfo,
  9381. // has to be properly restored so that tryCaptureVariable doesn't try
  9382. // and capture any new variables. In addition when calculating potential
  9383. // captures during transformation of nested lambdas, it is necessary to
  9384. // have the LSI properly restored.
  9385. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  9386. assert(ActiveTemplateInstantiations.size() &&
  9387. "There should be an active template instantiation on the stack "
  9388. "when instantiating a generic lambda!");
  9389. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  9390. }
  9391. else
  9392. // Enter a new function scope
  9393. PushFunctionScope();
  9394. // See if this is a redefinition.
  9395. if (!FD->isLateTemplateParsed())
  9396. CheckForFunctionRedefinition(FD);
  9397. // Builtin functions cannot be defined.
  9398. if (unsigned BuiltinID = FD->getBuiltinID()) {
  9399. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  9400. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  9401. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  9402. FD->setInvalidDecl();
  9403. }
  9404. }
  9405. // The return type of a function definition must be complete
  9406. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  9407. QualType ResultType = FD->getReturnType();
  9408. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  9409. !FD->isInvalidDecl() &&
  9410. RequireCompleteType(FD->getLocation(), ResultType,
  9411. diag::err_func_def_incomplete_result))
  9412. FD->setInvalidDecl();
  9413. if (FnBodyScope)
  9414. PushDeclContext(FnBodyScope, FD);
  9415. // Check the validity of our function parameters
  9416. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  9417. /*CheckParameterNames=*/true);
  9418. // Introduce our parameters into the function scope
  9419. for (auto Param : FD->params()) {
  9420. Param->setOwningFunction(FD);
  9421. // If this has an identifier, add it to the scope stack.
  9422. if (Param->getIdentifier() && FnBodyScope) {
  9423. CheckShadow(FnBodyScope, Param);
  9424. PushOnScopeChains(Param, FnBodyScope);
  9425. }
  9426. }
  9427. // If we had any tags defined in the function prototype,
  9428. // introduce them into the function scope.
  9429. if (FnBodyScope) {
  9430. for (ArrayRef<NamedDecl *>::iterator
  9431. I = FD->getDeclsInPrototypeScope().begin(),
  9432. E = FD->getDeclsInPrototypeScope().end();
  9433. I != E; ++I) {
  9434. NamedDecl *D = *I;
  9435. // Some of these decls (like enums) may have been pinned to the
  9436. // translation unit for lack of a real context earlier. If so, remove
  9437. // from the translation unit and reattach to the current context.
  9438. if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
  9439. // Is the decl actually in the context?
  9440. for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
  9441. if (DI == D) {
  9442. Context.getTranslationUnitDecl()->removeDecl(D);
  9443. break;
  9444. }
  9445. }
  9446. // Either way, reassign the lexical decl context to our FunctionDecl.
  9447. D->setLexicalDeclContext(CurContext);
  9448. }
  9449. // If the decl has a non-null name, make accessible in the current scope.
  9450. if (!D->getName().empty())
  9451. PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
  9452. // Similarly, dive into enums and fish their constants out, making them
  9453. // accessible in this scope.
  9454. if (auto *ED = dyn_cast<EnumDecl>(D)) {
  9455. for (auto *EI : ED->enumerators())
  9456. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  9457. }
  9458. }
  9459. }
  9460. // Ensure that the function's exception specification is instantiated.
  9461. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  9462. ResolveExceptionSpec(D->getLocation(), FPT);
  9463. // dllimport cannot be applied to non-inline function definitions.
  9464. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  9465. !FD->isTemplateInstantiation()) {
  9466. assert(!FD->hasAttr<DLLExportAttr>());
  9467. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  9468. FD->setInvalidDecl();
  9469. return D;
  9470. }
  9471. // We want to attach documentation to original Decl (which might be
  9472. // a function template).
  9473. ActOnDocumentableDecl(D);
  9474. if (getCurLexicalContext()->isObjCContainer() &&
  9475. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  9476. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  9477. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  9478. return D;
  9479. }
  9480. /// \brief Given the set of return statements within a function body,
  9481. /// compute the variables that are subject to the named return value
  9482. /// optimization.
  9483. ///
  9484. /// Each of the variables that is subject to the named return value
  9485. /// optimization will be marked as NRVO variables in the AST, and any
  9486. /// return statement that has a marked NRVO variable as its NRVO candidate can
  9487. /// use the named return value optimization.
  9488. ///
  9489. /// This function applies a very simplistic algorithm for NRVO: if every return
  9490. /// statement in the scope of a variable has the same NRVO candidate, that
  9491. /// candidate is an NRVO variable.
  9492. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  9493. ReturnStmt **Returns = Scope->Returns.data();
  9494. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  9495. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  9496. if (!NRVOCandidate->isNRVOVariable())
  9497. Returns[I]->setNRVOCandidate(nullptr);
  9498. }
  9499. }
  9500. }
  9501. bool Sema::canDelayFunctionBody(const Declarator &D) {
  9502. // We can't delay parsing the body of a constexpr function template (yet).
  9503. if (D.getDeclSpec().isConstexprSpecified())
  9504. return false;
  9505. // We can't delay parsing the body of a function template with a deduced
  9506. // return type (yet).
  9507. if (D.getDeclSpec().containsPlaceholderType()) {
  9508. // If the placeholder introduces a non-deduced trailing return type,
  9509. // we can still delay parsing it.
  9510. if (D.getNumTypeObjects()) {
  9511. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  9512. if (Outer.Kind == DeclaratorChunk::Function &&
  9513. Outer.Fun.hasTrailingReturnType()) {
  9514. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  9515. return Ty.isNull() || !Ty->isUndeducedType();
  9516. }
  9517. }
  9518. return false;
  9519. }
  9520. return true;
  9521. }
  9522. bool Sema::canSkipFunctionBody(Decl *D) {
  9523. // We cannot skip the body of a function (or function template) which is
  9524. // constexpr, since we may need to evaluate its body in order to parse the
  9525. // rest of the file.
  9526. // We cannot skip the body of a function with an undeduced return type,
  9527. // because any callers of that function need to know the type.
  9528. if (const FunctionDecl *FD = D->getAsFunction())
  9529. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  9530. return false;
  9531. return Consumer.shouldSkipFunctionBody(D);
  9532. }
  9533. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  9534. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
  9535. FD->setHasSkippedBody();
  9536. else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
  9537. MD->setHasSkippedBody();
  9538. return ActOnFinishFunctionBody(Decl, nullptr);
  9539. }
  9540. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  9541. return ActOnFinishFunctionBody(D, BodyArg, false);
  9542. }
  9543. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  9544. bool IsInstantiation) {
  9545. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  9546. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  9547. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  9548. if (FD) {
  9549. FD->setBody(Body);
  9550. if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
  9551. !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
  9552. // If the function has a deduced result type but contains no 'return'
  9553. // statements, the result type as written must be exactly 'auto', and
  9554. // the deduced result type is 'void'.
  9555. if (!FD->getReturnType()->getAs<AutoType>()) {
  9556. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  9557. << FD->getReturnType();
  9558. FD->setInvalidDecl();
  9559. } else {
  9560. // Substitute 'void' for the 'auto' in the type.
  9561. TypeLoc ResultType = getReturnTypeLoc(FD);
  9562. Context.adjustDeducedFunctionResultType(
  9563. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  9564. }
  9565. }
  9566. #if 0 // HLSL Change Start - no lambda support
  9567. else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  9568. auto *LSI = getCurLambda();
  9569. if (LSI->HasImplicitReturnType) {
  9570. deduceClosureReturnType(*LSI);
  9571. // C++11 [expr.prim.lambda]p4:
  9572. // [...] if there are no return statements in the compound-statement
  9573. // [the deduced type is] the type void
  9574. QualType RetType =
  9575. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  9576. // Update the return type to the deduced type.
  9577. const FunctionProtoType *Proto =
  9578. FD->getType()->getAs<FunctionProtoType>();
  9579. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  9580. Proto->getExtProtoInfo()));
  9581. }
  9582. }
  9583. #endif // HLSL Change Start - no lambda support
  9584. // The only way to be included in UndefinedButUsed is if there is an
  9585. // ODR use before the definition. Avoid the expensive map lookup if this
  9586. // is the first declaration.
  9587. if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
  9588. if (!FD->isExternallyVisible())
  9589. UndefinedButUsed.erase(FD);
  9590. else if (FD->isInlined() &&
  9591. !LangOpts.GNUInline &&
  9592. (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
  9593. UndefinedButUsed.erase(FD);
  9594. }
  9595. // If the function implicitly returns zero (like 'main') or is naked,
  9596. // don't complain about missing return statements.
  9597. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  9598. WP.disableCheckFallThrough();
  9599. // MSVC permits the use of pure specifier (=0) on function definition,
  9600. // defined at class scope, warn about this non-standard construct.
  9601. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  9602. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  9603. if (!FD->isInvalidDecl()) {
  9604. // Don't diagnose unused parameters of defaulted or deleted functions.
  9605. if (!FD->isDeleted() && !FD->isDefaulted())
  9606. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  9607. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  9608. FD->getReturnType(), FD);
  9609. // If this is a structor, we need a vtable.
  9610. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  9611. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  9612. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  9613. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  9614. // Try to apply the named return value optimization. We have to check
  9615. // if we can do this here because lambdas keep return statements around
  9616. // to deduce an implicit return type.
  9617. if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
  9618. !FD->isDependentContext())
  9619. computeNRVO(Body, getCurFunction());
  9620. }
  9621. // GNU warning -Wmissing-prototypes:
  9622. // Warn if a global function is defined without a previous
  9623. // prototype declaration. This warning is issued even if the
  9624. // definition itself provides a prototype. The aim is to detect
  9625. // global functions that fail to be declared in header files.
  9626. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  9627. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  9628. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  9629. if (PossibleZeroParamPrototype) {
  9630. // We found a declaration that is not a prototype,
  9631. // but that could be a zero-parameter prototype
  9632. if (TypeSourceInfo *TI =
  9633. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  9634. TypeLoc TL = TI->getTypeLoc();
  9635. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  9636. Diag(PossibleZeroParamPrototype->getLocation(),
  9637. diag::note_declaration_not_a_prototype)
  9638. << PossibleZeroParamPrototype
  9639. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  9640. }
  9641. }
  9642. }
  9643. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  9644. const CXXMethodDecl *KeyFunction;
  9645. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  9646. MD->isVirtual() &&
  9647. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  9648. MD == KeyFunction->getCanonicalDecl()) {
  9649. // Update the key-function state if necessary for this ABI.
  9650. if (FD->isInlined() &&
  9651. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  9652. Context.setNonKeyFunction(MD);
  9653. // If the newly-chosen key function is already defined, then we
  9654. // need to mark the vtable as used retroactively.
  9655. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  9656. const FunctionDecl *Definition;
  9657. if (KeyFunction && KeyFunction->isDefined(Definition))
  9658. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  9659. } else {
  9660. // We just defined they key function; mark the vtable as used.
  9661. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  9662. }
  9663. }
  9664. }
  9665. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  9666. "Function parsing confused");
  9667. #if 0 // HLSL Change Starts
  9668. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  9669. assert(MD == getCurMethodDecl() && "Method parsing confused");
  9670. MD->setBody(Body);
  9671. if (!MD->isInvalidDecl()) {
  9672. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  9673. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  9674. MD->getReturnType(), MD);
  9675. if (Body)
  9676. computeNRVO(Body, getCurFunction());
  9677. }
  9678. if (getCurFunction()->ObjCShouldCallSuper) {
  9679. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  9680. << MD->getSelector().getAsString();
  9681. getCurFunction()->ObjCShouldCallSuper = false;
  9682. }
  9683. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  9684. const ObjCMethodDecl *InitMethod = nullptr;
  9685. bool isDesignated =
  9686. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  9687. assert(isDesignated && InitMethod);
  9688. (void)isDesignated;
  9689. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  9690. auto IFace = MD->getClassInterface();
  9691. if (!IFace)
  9692. return false;
  9693. auto SuperD = IFace->getSuperClass();
  9694. if (!SuperD)
  9695. return false;
  9696. return SuperD->getIdentifier() ==
  9697. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  9698. };
  9699. // Don't issue this warning for unavailable inits or direct subclasses
  9700. // of NSObject.
  9701. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  9702. Diag(MD->getLocation(),
  9703. diag::warn_objc_designated_init_missing_super_call);
  9704. Diag(InitMethod->getLocation(),
  9705. diag::note_objc_designated_init_marked_here);
  9706. }
  9707. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  9708. }
  9709. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  9710. // Don't issue this warning for unavaialable inits.
  9711. if (!MD->isUnavailable())
  9712. Diag(MD->getLocation(),
  9713. diag::warn_objc_secondary_init_missing_init_call);
  9714. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  9715. }
  9716. #endif // HLSL Change Ends
  9717. } else {
  9718. return nullptr;
  9719. }
  9720. assert(!getCurFunction()->ObjCShouldCallSuper &&
  9721. "This should only be set for ObjC methods, which should have been "
  9722. "handled in the block above.");
  9723. // Verify and clean out per-function state.
  9724. if (Body && (!FD || !FD->isDefaulted())) {
  9725. // C++ constructors that have function-try-blocks can't have return
  9726. // statements in the handlers of that block. (C++ [except.handle]p14)
  9727. // Verify this.
  9728. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  9729. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  9730. // Verify that gotos and switch cases don't jump into scopes illegally.
  9731. if (getCurFunction()->NeedsScopeChecking() &&
  9732. !PP.isCodeCompletionEnabled())
  9733. DiagnoseInvalidJumps(Body);
  9734. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  9735. if (!Destructor->getParent()->isDependentType())
  9736. CheckDestructor(Destructor);
  9737. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  9738. Destructor->getParent());
  9739. }
  9740. // If any errors have occurred, clear out any temporaries that may have
  9741. // been leftover. This ensures that these temporaries won't be picked up for
  9742. // deletion in some later function.
  9743. if (getDiagnostics().hasErrorOccurred() ||
  9744. getDiagnostics().getSuppressAllDiagnostics()) {
  9745. DiscardCleanupsInEvaluationContext();
  9746. }
  9747. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  9748. !isa<FunctionTemplateDecl>(dcl)) {
  9749. // Since the body is valid, issue any analysis-based warnings that are
  9750. // enabled.
  9751. ActivePolicy = &WP;
  9752. }
  9753. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  9754. (!CheckConstexprFunctionDecl(FD) ||
  9755. !CheckConstexprFunctionBody(FD, Body)))
  9756. FD->setInvalidDecl();
  9757. if (FD && FD->hasAttr<NakedAttr>()) {
  9758. for (const Stmt *S : Body->children()) {
  9759. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  9760. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  9761. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  9762. FD->setInvalidDecl();
  9763. break;
  9764. }
  9765. }
  9766. }
  9767. assert(ExprCleanupObjects.size() ==
  9768. ExprEvalContexts.back().NumCleanupObjects &&
  9769. "Leftover temporaries in function");
  9770. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  9771. assert(MaybeODRUseExprs.empty() &&
  9772. "Leftover expressions for odr-use checking");
  9773. }
  9774. if (!IsInstantiation)
  9775. PopDeclContext();
  9776. PopFunctionScopeInfo(ActivePolicy, dcl);
  9777. // If any errors have occurred, clear out any temporaries that may have
  9778. // been leftover. This ensures that these temporaries won't be picked up for
  9779. // deletion in some later function.
  9780. if (getDiagnostics().hasErrorOccurred()) {
  9781. DiscardCleanupsInEvaluationContext();
  9782. }
  9783. return dcl;
  9784. }
  9785. /// When we finish delayed parsing of an attribute, we must attach it to the
  9786. /// relevant Decl.
  9787. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  9788. ParsedAttributes &Attrs) {
  9789. // Always attach attributes to the underlying decl.
  9790. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  9791. D = TD->getTemplatedDecl();
  9792. ProcessDeclAttributeList(S, D, Attrs.getList());
  9793. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  9794. if (Method->isStatic())
  9795. checkThisInStaticMemberFunctionAttributes(Method);
  9796. }
  9797. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  9798. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  9799. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  9800. IdentifierInfo &II, Scope *S) {
  9801. // Before we produce a declaration for an implicitly defined
  9802. // function, see whether there was a locally-scoped declaration of
  9803. // this name as a function or variable. If so, use that
  9804. // (non-visible) declaration, and complain about it.
  9805. if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
  9806. Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
  9807. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  9808. return ExternCPrev;
  9809. }
  9810. // Extension in C99. Legal in C90, but warn about it.
  9811. unsigned diag_id;
  9812. if (II.getName().startswith("__builtin_"))
  9813. diag_id = diag::warn_builtin_unknown;
  9814. else if (getLangOpts().C99)
  9815. diag_id = diag::ext_implicit_function_decl;
  9816. else
  9817. diag_id = diag::warn_implicit_function_decl;
  9818. Diag(Loc, diag_id) << &II;
  9819. // Because typo correction is expensive, only do it if the implicit
  9820. // function declaration is going to be treated as an error.
  9821. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  9822. TypoCorrection Corrected;
  9823. if (S &&
  9824. (Corrected = CorrectTypo(
  9825. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  9826. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  9827. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  9828. /*ErrorRecovery*/false);
  9829. }
  9830. // Set a Declarator for the implicit definition: int foo();
  9831. const char *Dummy;
  9832. AttributeFactory attrFactory;
  9833. DeclSpec DS(attrFactory);
  9834. unsigned DiagID;
  9835. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  9836. Context.getPrintingPolicy());
  9837. (void)Error; // Silence warning.
  9838. assert(!Error && "Error setting up implicit decl!");
  9839. SourceLocation NoLoc;
  9840. Declarator D(DS, Declarator::BlockContext);
  9841. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  9842. /*IsAmbiguous=*/false,
  9843. /*LParenLoc=*/NoLoc,
  9844. /*Params=*/nullptr,
  9845. /*NumParams=*/0,
  9846. /*EllipsisLoc=*/NoLoc,
  9847. /*RParenLoc=*/NoLoc,
  9848. /*TypeQuals=*/0,
  9849. /*RefQualifierIsLvalueRef=*/true,
  9850. /*RefQualifierLoc=*/NoLoc,
  9851. /*ConstQualifierLoc=*/NoLoc,
  9852. /*VolatileQualifierLoc=*/NoLoc,
  9853. /*RestrictQualifierLoc=*/NoLoc,
  9854. /*MutableLoc=*/NoLoc,
  9855. EST_None,
  9856. /*ESpecLoc=*/NoLoc,
  9857. /*Exceptions=*/nullptr,
  9858. /*ExceptionRanges=*/nullptr,
  9859. /*NumExceptions=*/0,
  9860. /*NoexceptExpr=*/nullptr,
  9861. /*ExceptionSpecTokens=*/nullptr,
  9862. Loc, Loc, D),
  9863. DS.getAttributes(),
  9864. SourceLocation());
  9865. D.SetIdentifier(&II, Loc);
  9866. // Insert this function into translation-unit scope.
  9867. DeclContext *PrevDC = CurContext;
  9868. CurContext = Context.getTranslationUnitDecl();
  9869. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  9870. FD->setImplicit();
  9871. CurContext = PrevDC;
  9872. AddKnownFunctionAttributes(FD);
  9873. return FD;
  9874. }
  9875. /// \brief Adds any function attributes that we know a priori based on
  9876. /// the declaration of this function.
  9877. ///
  9878. /// These attributes can apply both to implicitly-declared builtins
  9879. /// (like __builtin___printf_chk) or to library-declared functions
  9880. /// like NSLog or printf.
  9881. ///
  9882. /// We need to check for duplicate attributes both here and where user-written
  9883. /// attributes are applied to declarations.
  9884. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  9885. if (FD->isInvalidDecl())
  9886. return;
  9887. // If this is a built-in function, map its builtin attributes to
  9888. // actual attributes.
  9889. if (unsigned BuiltinID = FD->getBuiltinID()) {
  9890. // Handle printf-formatting attributes.
  9891. unsigned FormatIdx;
  9892. bool HasVAListArg;
  9893. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  9894. if (!FD->hasAttr<FormatAttr>()) {
  9895. const char *fmt = "printf";
  9896. unsigned int NumParams = FD->getNumParams();
  9897. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  9898. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  9899. fmt = "NSString";
  9900. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9901. &Context.Idents.get(fmt),
  9902. FormatIdx+1,
  9903. HasVAListArg ? 0 : FormatIdx+2,
  9904. FD->getLocation()));
  9905. }
  9906. }
  9907. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  9908. HasVAListArg)) {
  9909. if (!FD->hasAttr<FormatAttr>())
  9910. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9911. &Context.Idents.get("scanf"),
  9912. FormatIdx+1,
  9913. HasVAListArg ? 0 : FormatIdx+2,
  9914. FD->getLocation()));
  9915. }
  9916. // Mark const if we don't care about errno and that is the only
  9917. // thing preventing the function from being const. This allows
  9918. // IRgen to use LLVM intrinsics for such functions.
  9919. if (!getLangOpts().MathErrno &&
  9920. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  9921. if (!FD->hasAttr<ConstAttr>())
  9922. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  9923. }
  9924. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  9925. !FD->hasAttr<ReturnsTwiceAttr>())
  9926. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  9927. FD->getLocation()));
  9928. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  9929. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  9930. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  9931. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  9932. }
  9933. IdentifierInfo *Name = FD->getIdentifier();
  9934. if (!Name)
  9935. return;
  9936. if ((!getLangOpts().CPlusPlus &&
  9937. FD->getDeclContext()->isTranslationUnit()) ||
  9938. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  9939. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  9940. LinkageSpecDecl::lang_c)) {
  9941. // Okay: this could be a libc/libm/Objective-C function we know
  9942. // about.
  9943. } else
  9944. return;
  9945. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  9946. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  9947. // target-specific builtins, perhaps?
  9948. if (!FD->hasAttr<FormatAttr>())
  9949. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9950. &Context.Idents.get("printf"), 2,
  9951. Name->isStr("vasprintf") ? 0 : 3,
  9952. FD->getLocation()));
  9953. }
  9954. if (Name->isStr("__CFStringMakeConstantString")) {
  9955. // We already have a __builtin___CFStringMakeConstantString,
  9956. // but builds that use -fno-constant-cfstrings don't go through that.
  9957. if (!FD->hasAttr<FormatArgAttr>())
  9958. FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
  9959. FD->getLocation()));
  9960. }
  9961. }
  9962. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  9963. TypeSourceInfo *TInfo) {
  9964. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  9965. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  9966. if (!TInfo) {
  9967. assert(D.isInvalidType() && "no declarator info for valid type");
  9968. TInfo = Context.getTrivialTypeSourceInfo(T);
  9969. }
  9970. // Scope manipulation handled by caller.
  9971. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  9972. D.getLocStart(),
  9973. D.getIdentifierLoc(),
  9974. D.getIdentifier(),
  9975. TInfo);
  9976. // Bail out immediately if we have an invalid declaration.
  9977. if (D.isInvalidType()) {
  9978. NewTD->setInvalidDecl();
  9979. return NewTD;
  9980. }
  9981. if (D.getDeclSpec().isModulePrivateSpecified()) {
  9982. if (CurContext->isFunctionOrMethod())
  9983. Diag(NewTD->getLocation(), diag::err_module_private_local)
  9984. << 2 << NewTD->getDeclName()
  9985. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  9986. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  9987. else
  9988. NewTD->setModulePrivate();
  9989. }
  9990. // C++ [dcl.typedef]p8:
  9991. // If the typedef declaration defines an unnamed class (or
  9992. // enum), the first typedef-name declared by the declaration
  9993. // to be that class type (or enum type) is used to denote the
  9994. // class type (or enum type) for linkage purposes only.
  9995. // We need to check whether the type was declared in the declaration.
  9996. switch (D.getDeclSpec().getTypeSpecType()) {
  9997. case TST_enum:
  9998. case TST_struct:
  9999. case TST_interface:
  10000. case TST_union:
  10001. case TST_class: {
  10002. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  10003. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  10004. break;
  10005. }
  10006. default:
  10007. break;
  10008. }
  10009. return NewTD;
  10010. }
  10011. /// \brief Check that this is a valid underlying type for an enum declaration.
  10012. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  10013. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  10014. QualType T = TI->getType();
  10015. if (T->isDependentType())
  10016. return false;
  10017. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  10018. if (BT->isInteger())
  10019. return false;
  10020. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  10021. return true;
  10022. }
  10023. /// Check whether this is a valid redeclaration of a previous enumeration.
  10024. /// \return true if the redeclaration was invalid.
  10025. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  10026. QualType EnumUnderlyingTy,
  10027. const EnumDecl *Prev) {
  10028. bool IsFixed = !EnumUnderlyingTy.isNull();
  10029. if (IsScoped != Prev->isScoped()) {
  10030. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  10031. << Prev->isScoped();
  10032. Diag(Prev->getLocation(), diag::note_previous_declaration);
  10033. return true;
  10034. }
  10035. if (IsFixed && Prev->isFixed()) {
  10036. if (!EnumUnderlyingTy->isDependentType() &&
  10037. !Prev->getIntegerType()->isDependentType() &&
  10038. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  10039. Prev->getIntegerType())) {
  10040. // TODO: Highlight the underlying type of the redeclaration.
  10041. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  10042. << EnumUnderlyingTy << Prev->getIntegerType();
  10043. Diag(Prev->getLocation(), diag::note_previous_declaration)
  10044. << Prev->getIntegerTypeRange();
  10045. return true;
  10046. }
  10047. } else if (IsFixed != Prev->isFixed()) {
  10048. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  10049. << Prev->isFixed();
  10050. Diag(Prev->getLocation(), diag::note_previous_declaration);
  10051. return true;
  10052. }
  10053. return false;
  10054. }
  10055. /// \brief Get diagnostic %select index for tag kind for
  10056. /// redeclaration diagnostic message.
  10057. /// WARNING: Indexes apply to particular diagnostics only!
  10058. ///
  10059. /// \returns diagnostic %select index.
  10060. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  10061. switch (Tag) {
  10062. case TTK_Struct: return 0;
  10063. case TTK_Interface: return 1;
  10064. case TTK_Class: return 2;
  10065. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  10066. }
  10067. }
  10068. /// \brief Determine if tag kind is a class-key compatible with
  10069. /// class for redeclaration (class, struct, or __interface).
  10070. ///
  10071. /// \returns true iff the tag kind is compatible.
  10072. static bool isClassCompatTagKind(TagTypeKind Tag)
  10073. {
  10074. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  10075. }
  10076. /// \brief Determine whether a tag with a given kind is acceptable
  10077. /// as a redeclaration of the given tag declaration.
  10078. ///
  10079. /// \returns true if the new tag kind is acceptable, false otherwise.
  10080. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  10081. TagTypeKind NewTag, bool isDefinition,
  10082. SourceLocation NewTagLoc,
  10083. const IdentifierInfo *Name) {
  10084. // C++ [dcl.type.elab]p3:
  10085. // The class-key or enum keyword present in the
  10086. // elaborated-type-specifier shall agree in kind with the
  10087. // declaration to which the name in the elaborated-type-specifier
  10088. // refers. This rule also applies to the form of
  10089. // elaborated-type-specifier that declares a class-name or
  10090. // friend class since it can be construed as referring to the
  10091. // definition of the class. Thus, in any
  10092. // elaborated-type-specifier, the enum keyword shall be used to
  10093. // refer to an enumeration (7.2), the union class-key shall be
  10094. // used to refer to a union (clause 9), and either the class or
  10095. // struct class-key shall be used to refer to a class (clause 9)
  10096. // declared using the class or struct class-key.
  10097. TagTypeKind OldTag = Previous->getTagKind();
  10098. if (!isDefinition || !isClassCompatTagKind(NewTag))
  10099. if (OldTag == NewTag)
  10100. return true;
  10101. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  10102. // Warn about the struct/class tag mismatch.
  10103. bool isTemplate = false;
  10104. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  10105. isTemplate = Record->getDescribedClassTemplate();
  10106. if (!ActiveTemplateInstantiations.empty()) {
  10107. // In a template instantiation, do not offer fix-its for tag mismatches
  10108. // since they usually mess up the template instead of fixing the problem.
  10109. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  10110. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10111. << getRedeclDiagFromTagKind(OldTag);
  10112. return true;
  10113. }
  10114. if (isDefinition) {
  10115. // On definitions, check previous tags and issue a fix-it for each
  10116. // one that doesn't match the current tag.
  10117. if (Previous->getDefinition()) {
  10118. // Don't suggest fix-its for redefinitions.
  10119. return true;
  10120. }
  10121. bool previousMismatch = false;
  10122. for (auto I : Previous->redecls()) {
  10123. if (I->getTagKind() != NewTag) {
  10124. if (!previousMismatch) {
  10125. previousMismatch = true;
  10126. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  10127. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10128. << getRedeclDiagFromTagKind(I->getTagKind());
  10129. }
  10130. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  10131. << getRedeclDiagFromTagKind(NewTag)
  10132. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  10133. TypeWithKeyword::getTagTypeKindName(NewTag));
  10134. }
  10135. }
  10136. return true;
  10137. }
  10138. // Check for a previous definition. If current tag and definition
  10139. // are same type, do nothing. If no definition, but disagree with
  10140. // with previous tag type, give a warning, but no fix-it.
  10141. const TagDecl *Redecl = Previous->getDefinition() ?
  10142. Previous->getDefinition() : Previous;
  10143. if (Redecl->getTagKind() == NewTag) {
  10144. return true;
  10145. }
  10146. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  10147. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10148. << getRedeclDiagFromTagKind(OldTag);
  10149. Diag(Redecl->getLocation(), diag::note_previous_use);
  10150. // If there is a previous definition, suggest a fix-it.
  10151. if (Previous->getDefinition()) {
  10152. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  10153. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  10154. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  10155. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  10156. }
  10157. return true;
  10158. }
  10159. return false;
  10160. }
  10161. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  10162. /// from an outer enclosing namespace or file scope inside a friend declaration.
  10163. /// This should provide the commented out code in the following snippet:
  10164. /// namespace N {
  10165. /// struct X;
  10166. /// namespace M {
  10167. /// struct Y { friend struct /*N::*/ X; };
  10168. /// }
  10169. /// }
  10170. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  10171. SourceLocation NameLoc) {
  10172. // While the decl is in a namespace, do repeated lookup of that name and see
  10173. // if we get the same namespace back. If we do not, continue until
  10174. // translation unit scope, at which point we have a fully qualified NNS.
  10175. SmallVector<IdentifierInfo *, 4> Namespaces;
  10176. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  10177. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  10178. // This tag should be declared in a namespace, which can only be enclosed by
  10179. // other namespaces. Bail if there's an anonymous namespace in the chain.
  10180. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  10181. if (!Namespace || Namespace->isAnonymousNamespace())
  10182. return FixItHint();
  10183. IdentifierInfo *II = Namespace->getIdentifier();
  10184. Namespaces.push_back(II);
  10185. NamedDecl *Lookup = SemaRef.LookupSingleName(
  10186. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  10187. if (Lookup == Namespace)
  10188. break;
  10189. }
  10190. // Once we have all the namespaces, reverse them to go outermost first, and
  10191. // build an NNS.
  10192. SmallString<64> Insertion;
  10193. llvm::raw_svector_ostream OS(Insertion);
  10194. if (DC->isTranslationUnit())
  10195. OS << "::";
  10196. std::reverse(Namespaces.begin(), Namespaces.end());
  10197. for (auto *II : Namespaces)
  10198. OS << II->getName() << "::";
  10199. OS.flush();
  10200. return FixItHint::CreateInsertion(NameLoc, Insertion);
  10201. }
  10202. /// \brief Determine whether a tag originally declared in context \p OldDC can
  10203. /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
  10204. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  10205. /// using-declaration).
  10206. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  10207. DeclContext *NewDC) {
  10208. OldDC = OldDC->getRedeclContext();
  10209. NewDC = NewDC->getRedeclContext();
  10210. if (OldDC->Equals(NewDC))
  10211. return true;
  10212. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  10213. // encloses the other).
  10214. if (S.getLangOpts().MSVCCompat &&
  10215. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  10216. return true;
  10217. return false;
  10218. }
  10219. /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
  10220. /// former case, Name will be non-null. In the later case, Name will be null.
  10221. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  10222. /// reference/declaration/definition of a tag.
  10223. ///
  10224. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  10225. /// trailing-type-specifier) other than one in an alias-declaration.
  10226. ///
  10227. /// \param SkipBody If non-null, will be set to indicate if the caller should
  10228. /// skip the definition of this tag and treat it as if it were a declaration.
  10229. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  10230. SourceLocation KWLoc, CXXScopeSpec &SS,
  10231. IdentifierInfo *Name, SourceLocation NameLoc,
  10232. AttributeList *Attr, AccessSpecifier AS,
  10233. SourceLocation ModulePrivateLoc,
  10234. MultiTemplateParamsArg TemplateParameterLists,
  10235. bool &OwnedDecl, bool &IsDependent,
  10236. SourceLocation ScopedEnumKWLoc,
  10237. bool ScopedEnumUsesClassTag,
  10238. TypeResult UnderlyingType,
  10239. bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
  10240. // If this is not a definition, it must have a name.
  10241. IdentifierInfo *OrigName = Name;
  10242. assert((Name != nullptr || TUK == TUK_Definition) &&
  10243. "Nameless record must be a definition!");
  10244. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  10245. OwnedDecl = false;
  10246. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  10247. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  10248. // FIXME: Check explicit specializations more carefully.
  10249. bool isExplicitSpecialization = false;
  10250. bool Invalid = false;
  10251. // We only need to do this matching if we have template parameters
  10252. // or a scope specifier, which also conveniently avoids this work
  10253. // for non-C++ cases.
  10254. if (TemplateParameterLists.size() > 0 ||
  10255. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  10256. if (TemplateParameterList *TemplateParams =
  10257. MatchTemplateParametersToScopeSpecifier(
  10258. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  10259. TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
  10260. if (Kind == TTK_Enum) {
  10261. Diag(KWLoc, diag::err_enum_template);
  10262. return nullptr;
  10263. }
  10264. if (TemplateParams->size() > 0) {
  10265. // This is a declaration or definition of a class template (which may
  10266. // be a member of another template).
  10267. if (Invalid)
  10268. return nullptr;
  10269. OwnedDecl = false;
  10270. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  10271. SS, Name, NameLoc, Attr,
  10272. TemplateParams, AS,
  10273. ModulePrivateLoc,
  10274. /*FriendLoc*/SourceLocation(),
  10275. TemplateParameterLists.size()-1,
  10276. TemplateParameterLists.data(),
  10277. SkipBody);
  10278. return Result.get();
  10279. } else {
  10280. // The "template<>" header is extraneous.
  10281. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  10282. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  10283. isExplicitSpecialization = true;
  10284. }
  10285. }
  10286. }
  10287. // Figure out the underlying type if this a enum declaration. We need to do
  10288. // this early, because it's needed to detect if this is an incompatible
  10289. // redeclaration.
  10290. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  10291. if (Kind == TTK_Enum) {
  10292. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  10293. // No underlying type explicitly specified, or we failed to parse the
  10294. // type, default to int.
  10295. EnumUnderlying = Context.IntTy.getTypePtr();
  10296. else if (UnderlyingType.get()) {
  10297. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  10298. // integral type; any cv-qualification is ignored.
  10299. TypeSourceInfo *TI = nullptr;
  10300. GetTypeFromParser(UnderlyingType.get(), &TI);
  10301. EnumUnderlying = TI;
  10302. if (CheckEnumUnderlyingType(TI))
  10303. // Recover by falling back to int.
  10304. EnumUnderlying = Context.IntTy.getTypePtr();
  10305. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  10306. UPPC_FixedUnderlyingType))
  10307. EnumUnderlying = Context.IntTy.getTypePtr();
  10308. } else if (getLangOpts().MSVCCompat)
  10309. // Microsoft enums are always of int type.
  10310. EnumUnderlying = Context.IntTy.getTypePtr();
  10311. }
  10312. // HLSL Change Starts
  10313. if (getLangOpts().HLSLVersion == 2015 && TUK == TUK_Declaration) {
  10314. Diag(NameLoc, diag::err_hlsl_unsupported_construct)
  10315. << "struct declaration without definition";
  10316. }
  10317. // HLSL Change Ends
  10318. DeclContext *SearchDC = CurContext;
  10319. DeclContext *DC = CurContext;
  10320. bool isStdBadAlloc = false;
  10321. RedeclarationKind Redecl = ForRedeclaration;
  10322. if (TUK == TUK_Friend || TUK == TUK_Reference)
  10323. Redecl = NotForRedeclaration;
  10324. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  10325. if (Name && SS.isNotEmpty()) {
  10326. // We have a nested-name tag ('struct foo::bar').
  10327. // Check for invalid 'foo::'.
  10328. if (SS.isInvalid()) {
  10329. Name = nullptr;
  10330. goto CreateNewDecl;
  10331. }
  10332. // If this is a friend or a reference to a class in a dependent
  10333. // context, don't try to make a decl for it.
  10334. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  10335. DC = computeDeclContext(SS, false);
  10336. if (!DC) {
  10337. IsDependent = true;
  10338. return nullptr;
  10339. }
  10340. } else {
  10341. DC = computeDeclContext(SS, true);
  10342. if (!DC) {
  10343. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  10344. << SS.getRange();
  10345. return nullptr;
  10346. }
  10347. }
  10348. if (RequireCompleteDeclContext(SS, DC))
  10349. return nullptr;
  10350. SearchDC = DC;
  10351. // Look-up name inside 'foo::'.
  10352. LookupQualifiedName(Previous, DC);
  10353. if (Previous.isAmbiguous())
  10354. return nullptr;
  10355. if (Previous.empty()) {
  10356. // Name lookup did not find anything. However, if the
  10357. // nested-name-specifier refers to the current instantiation,
  10358. // and that current instantiation has any dependent base
  10359. // classes, we might find something at instantiation time: treat
  10360. // this as a dependent elaborated-type-specifier.
  10361. // But this only makes any sense for reference-like lookups.
  10362. if (Previous.wasNotFoundInCurrentInstantiation() &&
  10363. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  10364. IsDependent = true;
  10365. return nullptr;
  10366. }
  10367. // A tag 'foo::bar' must already exist.
  10368. Diag(NameLoc, diag::err_not_tag_in_scope)
  10369. << Kind << Name << DC << SS.getRange();
  10370. Name = nullptr;
  10371. Invalid = true;
  10372. goto CreateNewDecl;
  10373. }
  10374. } else if (Name) {
  10375. // C++14 [class.mem]p14:
  10376. // If T is the name of a class, then each of the following shall have a
  10377. // name different from T:
  10378. // -- every member of class T that is itself a type
  10379. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  10380. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  10381. return nullptr;
  10382. // If this is a named struct, check to see if there was a previous forward
  10383. // declaration or definition.
  10384. // FIXME: We're looking into outer scopes here, even when we
  10385. // shouldn't be. Doing so can result in ambiguities that we
  10386. // shouldn't be diagnosing.
  10387. LookupName(Previous, S);
  10388. // When declaring or defining a tag, ignore ambiguities introduced
  10389. // by types using'ed into this scope.
  10390. if (Previous.isAmbiguous() &&
  10391. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  10392. LookupResult::Filter F = Previous.makeFilter();
  10393. while (F.hasNext()) {
  10394. NamedDecl *ND = F.next();
  10395. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  10396. F.erase();
  10397. }
  10398. F.done();
  10399. }
  10400. // C++11 [namespace.memdef]p3:
  10401. // If the name in a friend declaration is neither qualified nor
  10402. // a template-id and the declaration is a function or an
  10403. // elaborated-type-specifier, the lookup to determine whether
  10404. // the entity has been previously declared shall not consider
  10405. // any scopes outside the innermost enclosing namespace.
  10406. //
  10407. // MSVC doesn't implement the above rule for types, so a friend tag
  10408. // declaration may be a redeclaration of a type declared in an enclosing
  10409. // scope. They do implement this rule for friend functions.
  10410. //
  10411. // Does it matter that this should be by scope instead of by
  10412. // semantic context?
  10413. if (!Previous.empty() && TUK == TUK_Friend) {
  10414. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  10415. LookupResult::Filter F = Previous.makeFilter();
  10416. bool FriendSawTagOutsideEnclosingNamespace = false;
  10417. while (F.hasNext()) {
  10418. NamedDecl *ND = F.next();
  10419. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  10420. if (DC->isFileContext() &&
  10421. !EnclosingNS->Encloses(ND->getDeclContext())) {
  10422. if (getLangOpts().MSVCCompat)
  10423. FriendSawTagOutsideEnclosingNamespace = true;
  10424. else
  10425. F.erase();
  10426. }
  10427. }
  10428. F.done();
  10429. // Diagnose this MSVC extension in the easy case where lookup would have
  10430. // unambiguously found something outside the enclosing namespace.
  10431. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  10432. NamedDecl *ND = Previous.getFoundDecl();
  10433. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  10434. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  10435. }
  10436. }
  10437. // Note: there used to be some attempt at recovery here.
  10438. if (Previous.isAmbiguous())
  10439. return nullptr;
  10440. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  10441. // FIXME: This makes sure that we ignore the contexts associated
  10442. // with C structs, unions, and enums when looking for a matching
  10443. // tag declaration or definition. See the similar lookup tweak
  10444. // in Sema::LookupName; is there a better way to deal with this?
  10445. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  10446. SearchDC = SearchDC->getParent();
  10447. }
  10448. }
  10449. if (Previous.isSingleResult() &&
  10450. Previous.getFoundDecl()->isTemplateParameter()) {
  10451. // Maybe we will complain about the shadowed template parameter.
  10452. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  10453. // Just pretend that we didn't see the previous declaration.
  10454. Previous.clear();
  10455. }
  10456. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  10457. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  10458. // This is a declaration of or a reference to "std::bad_alloc".
  10459. isStdBadAlloc = true;
  10460. if (Previous.empty() && StdBadAlloc) {
  10461. // std::bad_alloc has been implicitly declared (but made invisible to
  10462. // name lookup). Fill in this implicit declaration as the previous
  10463. // declaration, so that the declarations get chained appropriately.
  10464. Previous.addDecl(getStdBadAlloc());
  10465. }
  10466. }
  10467. // If we didn't find a previous declaration, and this is a reference
  10468. // (or friend reference), move to the correct scope. In C++, we
  10469. // also need to do a redeclaration lookup there, just in case
  10470. // there's a shadow friend decl.
  10471. if (Name && Previous.empty() &&
  10472. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  10473. if (Invalid) goto CreateNewDecl;
  10474. assert(SS.isEmpty());
  10475. if (TUK == TUK_Reference) {
  10476. // C++ [basic.scope.pdecl]p5:
  10477. // -- for an elaborated-type-specifier of the form
  10478. //
  10479. // class-key identifier
  10480. //
  10481. // if the elaborated-type-specifier is used in the
  10482. // decl-specifier-seq or parameter-declaration-clause of a
  10483. // function defined in namespace scope, the identifier is
  10484. // declared as a class-name in the namespace that contains
  10485. // the declaration; otherwise, except as a friend
  10486. // declaration, the identifier is declared in the smallest
  10487. // non-class, non-function-prototype scope that contains the
  10488. // declaration.
  10489. //
  10490. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  10491. // C structs and unions.
  10492. //
  10493. // It is an error in C++ to declare (rather than define) an enum
  10494. // type, including via an elaborated type specifier. We'll
  10495. // diagnose that later; for now, declare the enum in the same
  10496. // scope as we would have picked for any other tag type.
  10497. //
  10498. // GNU C also supports this behavior as part of its incomplete
  10499. // enum types extension, while GNU C++ does not.
  10500. //
  10501. // Find the context where we'll be declaring the tag.
  10502. // FIXME: We would like to maintain the current DeclContext as the
  10503. // lexical context,
  10504. while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
  10505. SearchDC = SearchDC->getParent();
  10506. // Find the scope where we'll be declaring the tag.
  10507. while (S->isClassScope() ||
  10508. (getLangOpts().CPlusPlus &&
  10509. S->isFunctionPrototypeScope()) ||
  10510. ((S->getFlags() & Scope::DeclScope) == 0) ||
  10511. (S->getEntity() && S->getEntity()->isTransparentContext()))
  10512. S = S->getParent();
  10513. } else {
  10514. assert(TUK == TUK_Friend);
  10515. // C++ [namespace.memdef]p3:
  10516. // If a friend declaration in a non-local class first declares a
  10517. // class or function, the friend class or function is a member of
  10518. // the innermost enclosing namespace.
  10519. SearchDC = SearchDC->getEnclosingNamespaceContext();
  10520. }
  10521. // In C++, we need to do a redeclaration lookup to properly
  10522. // diagnose some problems.
  10523. if (getLangOpts().CPlusPlus) {
  10524. Previous.setRedeclarationKind(ForRedeclaration);
  10525. LookupQualifiedName(Previous, SearchDC);
  10526. }
  10527. }
  10528. // If we have a known previous declaration to use, then use it.
  10529. if (Previous.empty() && SkipBody && SkipBody->Previous)
  10530. Previous.addDecl(SkipBody->Previous);
  10531. if (!Previous.empty()) {
  10532. NamedDecl *PrevDecl = Previous.getFoundDecl();
  10533. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  10534. // It's okay to have a tag decl in the same scope as a typedef
  10535. // which hides a tag decl in the same scope. Finding this
  10536. // insanity with a redeclaration lookup can only actually happen
  10537. // in C++.
  10538. //
  10539. // This is also okay for elaborated-type-specifiers, which is
  10540. // technically forbidden by the current standard but which is
  10541. // okay according to the likely resolution of an open issue;
  10542. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  10543. if (getLangOpts().CPlusPlus) {
  10544. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  10545. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  10546. TagDecl *Tag = TT->getDecl();
  10547. if (Tag->getDeclName() == Name &&
  10548. Tag->getDeclContext()->getRedeclContext()
  10549. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  10550. PrevDecl = Tag;
  10551. Previous.clear();
  10552. Previous.addDecl(Tag);
  10553. Previous.resolveKind();
  10554. }
  10555. }
  10556. }
  10557. }
  10558. // If this is a redeclaration of a using shadow declaration, it must
  10559. // declare a tag in the same context. In MSVC mode, we allow a
  10560. // redefinition if either context is within the other.
  10561. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  10562. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  10563. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  10564. isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
  10565. !(OldTag && isAcceptableTagRedeclContext(
  10566. *this, OldTag->getDeclContext(), SearchDC))) {
  10567. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  10568. Diag(Shadow->getTargetDecl()->getLocation(),
  10569. diag::note_using_decl_target);
  10570. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  10571. << 0;
  10572. // Recover by ignoring the old declaration.
  10573. Previous.clear();
  10574. goto CreateNewDecl;
  10575. }
  10576. }
  10577. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  10578. // If this is a use of a previous tag, or if the tag is already declared
  10579. // in the same scope (so that the definition/declaration completes or
  10580. // rementions the tag), reuse the decl.
  10581. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  10582. isDeclInScope(DirectPrevDecl, SearchDC, S,
  10583. SS.isNotEmpty() || isExplicitSpecialization)) {
  10584. // Make sure that this wasn't declared as an enum and now used as a
  10585. // struct or something similar.
  10586. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  10587. TUK == TUK_Definition, KWLoc,
  10588. Name)) {
  10589. bool SafeToContinue
  10590. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  10591. Kind != TTK_Enum);
  10592. if (SafeToContinue)
  10593. Diag(KWLoc, diag::err_use_with_wrong_tag)
  10594. << Name
  10595. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  10596. PrevTagDecl->getKindName());
  10597. else
  10598. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  10599. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  10600. if (SafeToContinue)
  10601. Kind = PrevTagDecl->getTagKind();
  10602. else {
  10603. // Recover by making this an anonymous redefinition.
  10604. Name = nullptr;
  10605. Previous.clear();
  10606. Invalid = true;
  10607. }
  10608. }
  10609. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  10610. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  10611. // If this is an elaborated-type-specifier for a scoped enumeration,
  10612. // the 'class' keyword is not necessary and not permitted.
  10613. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  10614. if (ScopedEnum)
  10615. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  10616. << PrevEnum->isScoped()
  10617. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  10618. return PrevTagDecl;
  10619. }
  10620. QualType EnumUnderlyingTy;
  10621. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  10622. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  10623. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  10624. EnumUnderlyingTy = QualType(T, 0);
  10625. // All conflicts with previous declarations are recovered by
  10626. // returning the previous declaration, unless this is a definition,
  10627. // in which case we want the caller to bail out.
  10628. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  10629. ScopedEnum, EnumUnderlyingTy, PrevEnum))
  10630. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  10631. }
  10632. // C++11 [class.mem]p1:
  10633. // A member shall not be declared twice in the member-specification,
  10634. // except that a nested class or member class template can be declared
  10635. // and then later defined.
  10636. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  10637. S->isDeclScope(PrevDecl)) {
  10638. Diag(NameLoc, diag::ext_member_redeclared);
  10639. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  10640. }
  10641. if (!Invalid) {
  10642. // If this is a use, just return the declaration we found, unless
  10643. // we have attributes.
  10644. // FIXME: In the future, return a variant or some other clue
  10645. // for the consumer of this Decl to know it doesn't own it.
  10646. // For our current ASTs this shouldn't be a problem, but will
  10647. // need to be changed with DeclGroups.
  10648. if (!Attr &&
  10649. ((TUK == TUK_Reference &&
  10650. (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
  10651. || TUK == TUK_Friend))
  10652. return PrevTagDecl;
  10653. // Diagnose attempts to redefine a tag.
  10654. if (TUK == TUK_Definition) {
  10655. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  10656. // If we're defining a specialization and the previous definition
  10657. // is from an implicit instantiation, don't emit an error
  10658. // here; we'll catch this in the general case below.
  10659. bool IsExplicitSpecializationAfterInstantiation = false;
  10660. if (isExplicitSpecialization) {
  10661. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  10662. IsExplicitSpecializationAfterInstantiation =
  10663. RD->getTemplateSpecializationKind() !=
  10664. TSK_ExplicitSpecialization;
  10665. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  10666. IsExplicitSpecializationAfterInstantiation =
  10667. ED->getTemplateSpecializationKind() !=
  10668. TSK_ExplicitSpecialization;
  10669. }
  10670. NamedDecl *Hidden = nullptr;
  10671. if (SkipBody && getLangOpts().CPlusPlus &&
  10672. !hasVisibleDefinition(Def, &Hidden)) {
  10673. // There is a definition of this tag, but it is not visible. We
  10674. // explicitly make use of C++'s one definition rule here, and
  10675. // assume that this definition is identical to the hidden one
  10676. // we already have. Make the existing definition visible and
  10677. // use it in place of this one.
  10678. SkipBody->ShouldSkip = true;
  10679. makeMergedDefinitionVisible(Hidden, KWLoc);
  10680. return Def;
  10681. } else if (!IsExplicitSpecializationAfterInstantiation) {
  10682. // A redeclaration in function prototype scope in C isn't
  10683. // visible elsewhere, so merely issue a warning.
  10684. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  10685. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  10686. else
  10687. Diag(NameLoc, diag::err_redefinition) << Name;
  10688. Diag(Def->getLocation(), diag::note_previous_definition);
  10689. // If this is a redefinition, recover by making this
  10690. // struct be anonymous, which will make any later
  10691. // references get the previous definition.
  10692. Name = nullptr;
  10693. Previous.clear();
  10694. Invalid = true;
  10695. }
  10696. } else {
  10697. // If the type is currently being defined, complain
  10698. // about a nested redefinition.
  10699. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  10700. if (TD->isBeingDefined()) {
  10701. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  10702. Diag(PrevTagDecl->getLocation(),
  10703. diag::note_previous_definition);
  10704. Name = nullptr;
  10705. Previous.clear();
  10706. Invalid = true;
  10707. }
  10708. }
  10709. // Okay, this is definition of a previously declared or referenced
  10710. // tag. We're going to create a new Decl for it.
  10711. }
  10712. // Okay, we're going to make a redeclaration. If this is some kind
  10713. // of reference, make sure we build the redeclaration in the same DC
  10714. // as the original, and ignore the current access specifier.
  10715. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  10716. SearchDC = PrevTagDecl->getDeclContext();
  10717. AS = AS_none;
  10718. }
  10719. }
  10720. // If we get here we have (another) forward declaration or we
  10721. // have a definition. Just create a new decl.
  10722. } else {
  10723. // If we get here, this is a definition of a new tag type in a nested
  10724. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  10725. // new decl/type. We set PrevDecl to NULL so that the entities
  10726. // have distinct types.
  10727. Previous.clear();
  10728. }
  10729. // If we get here, we're going to create a new Decl. If PrevDecl
  10730. // is non-NULL, it's a definition of the tag declared by
  10731. // PrevDecl. If it's NULL, we have a new definition.
  10732. // Otherwise, PrevDecl is not a tag, but was found with tag
  10733. // lookup. This is only actually possible in C++, where a few
  10734. // things like templates still live in the tag namespace.
  10735. } else {
  10736. // Use a better diagnostic if an elaborated-type-specifier
  10737. // found the wrong kind of type on the first
  10738. // (non-redeclaration) lookup.
  10739. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  10740. !Previous.isForRedeclaration()) {
  10741. unsigned Kind = 0;
  10742. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  10743. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  10744. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  10745. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  10746. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  10747. Invalid = true;
  10748. // Otherwise, only diagnose if the declaration is in scope.
  10749. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  10750. SS.isNotEmpty() || isExplicitSpecialization)) {
  10751. // do nothing
  10752. // Diagnose implicit declarations introduced by elaborated types.
  10753. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  10754. unsigned Kind = 0;
  10755. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  10756. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  10757. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  10758. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  10759. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  10760. Invalid = true;
  10761. // Otherwise it's a declaration. Call out a particularly common
  10762. // case here.
  10763. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  10764. unsigned Kind = 0;
  10765. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  10766. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  10767. << Name << Kind << TND->getUnderlyingType();
  10768. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  10769. Invalid = true;
  10770. // Otherwise, diagnose.
  10771. } else {
  10772. // The tag name clashes with something else in the target scope,
  10773. // issue an error and recover by making this tag be anonymous.
  10774. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  10775. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  10776. Name = nullptr;
  10777. Invalid = true;
  10778. }
  10779. // The existing declaration isn't relevant to us; we're in a
  10780. // new scope, so clear out the previous declaration.
  10781. Previous.clear();
  10782. }
  10783. }
  10784. CreateNewDecl:
  10785. TagDecl *PrevDecl = nullptr;
  10786. if (Previous.isSingleResult())
  10787. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  10788. // If there is an identifier, use the location of the identifier as the
  10789. // location of the decl, otherwise use the location of the struct/union
  10790. // keyword.
  10791. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  10792. // Otherwise, create a new declaration. If there is a previous
  10793. // declaration of the same entity, the two will be linked via
  10794. // PrevDecl.
  10795. TagDecl *New;
  10796. bool IsForwardReference = false;
  10797. if (Kind == TTK_Enum) {
  10798. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  10799. // enum X { A, B, C } D; D should chain to X.
  10800. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  10801. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  10802. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  10803. // If this is an undefined enum, warn.
  10804. if (TUK != TUK_Definition && !Invalid) {
  10805. TagDecl *Def;
  10806. if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  10807. cast<EnumDecl>(New)->isFixed()) {
  10808. // C++0x: 7.2p2: opaque-enum-declaration.
  10809. // Conflicts are diagnosed above. Do nothing.
  10810. }
  10811. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  10812. Diag(Loc, diag::ext_forward_ref_enum_def)
  10813. << New;
  10814. Diag(Def->getLocation(), diag::note_previous_definition);
  10815. } else {
  10816. unsigned DiagID = diag::ext_forward_ref_enum;
  10817. if (getLangOpts().MSVCCompat)
  10818. DiagID = diag::ext_ms_forward_ref_enum;
  10819. else if (getLangOpts().CPlusPlus)
  10820. DiagID = diag::err_forward_ref_enum;
  10821. Diag(Loc, DiagID);
  10822. // If this is a forward-declared reference to an enumeration, make a
  10823. // note of it; we won't actually be introducing the declaration into
  10824. // the declaration context.
  10825. if (TUK == TUK_Reference)
  10826. IsForwardReference = true;
  10827. }
  10828. }
  10829. if (EnumUnderlying) {
  10830. EnumDecl *ED = cast<EnumDecl>(New);
  10831. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  10832. ED->setIntegerTypeSourceInfo(TI);
  10833. else
  10834. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  10835. ED->setPromotionType(ED->getIntegerType());
  10836. }
  10837. } else {
  10838. // struct/union/class
  10839. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  10840. // struct X { int A; } D; D should chain to X.
  10841. if (getLangOpts().CPlusPlus) {
  10842. // FIXME: Look for a way to use RecordDecl for simple structs.
  10843. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  10844. cast_or_null<CXXRecordDecl>(PrevDecl));
  10845. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  10846. StdBadAlloc = cast<CXXRecordDecl>(New);
  10847. } else
  10848. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  10849. cast_or_null<RecordDecl>(PrevDecl));
  10850. }
  10851. // C++11 [dcl.type]p3:
  10852. // A type-specifier-seq shall not define a class or enumeration [...].
  10853. if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
  10854. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  10855. << Context.getTagDeclType(New);
  10856. Invalid = true;
  10857. }
  10858. // Maybe add qualifier info.
  10859. if (SS.isNotEmpty()) {
  10860. if (SS.isSet()) {
  10861. // If this is either a declaration or a definition, check the
  10862. // nested-name-specifier against the current context. We don't do this
  10863. // for explicit specializations, because they have similar checking
  10864. // (with more specific diagnostics) in the call to
  10865. // CheckMemberSpecialization, below.
  10866. if (!isExplicitSpecialization &&
  10867. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  10868. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
  10869. Invalid = true;
  10870. New->setQualifierInfo(SS.getWithLocInContext(Context));
  10871. if (TemplateParameterLists.size() > 0) {
  10872. New->setTemplateParameterListsInfo(Context,
  10873. TemplateParameterLists.size(),
  10874. TemplateParameterLists.data());
  10875. }
  10876. }
  10877. else
  10878. Invalid = true;
  10879. }
  10880. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  10881. // Add alignment attributes if necessary; these attributes are checked when
  10882. // the ASTContext lays out the structure.
  10883. //
  10884. // It is important for implementing the correct semantics that this
  10885. // happen here (in act on tag decl). The #pragma pack stack is
  10886. // maintained as a result of parser callbacks which can occur at
  10887. // many points during the parsing of a struct declaration (because
  10888. // the #pragma tokens are effectively skipped over during the
  10889. // parsing of the struct).
  10890. if (TUK == TUK_Definition) {
  10891. AddAlignmentAttributesForRecord(RD);
  10892. AddMsStructLayoutForRecord(RD);
  10893. }
  10894. }
  10895. if (ModulePrivateLoc.isValid()) {
  10896. if (isExplicitSpecialization)
  10897. Diag(New->getLocation(), diag::err_module_private_specialization)
  10898. << 2
  10899. << FixItHint::CreateRemoval(ModulePrivateLoc);
  10900. // __module_private__ does not apply to local classes. However, we only
  10901. // diagnose this as an error when the declaration specifiers are
  10902. // freestanding. Here, we just ignore the __module_private__.
  10903. else if (!SearchDC->isFunctionOrMethod())
  10904. New->setModulePrivate();
  10905. }
  10906. // If this is a specialization of a member class (of a class template),
  10907. // check the specialization.
  10908. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  10909. Invalid = true;
  10910. // If we're declaring or defining a tag in function prototype scope in C,
  10911. // note that this type can only be used within the function and add it to
  10912. // the list of decls to inject into the function definition scope.
  10913. if ((Name || Kind == TTK_Enum) &&
  10914. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  10915. if (getLangOpts().CPlusPlus) {
  10916. // C++ [dcl.fct]p6:
  10917. // Types shall not be defined in return or parameter types.
  10918. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  10919. Diag(Loc, diag::err_type_defined_in_param_type)
  10920. << Name;
  10921. Invalid = true;
  10922. }
  10923. } else {
  10924. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  10925. }
  10926. DeclsInPrototypeScope.push_back(New);
  10927. }
  10928. if (Invalid)
  10929. New->setInvalidDecl();
  10930. if (Attr)
  10931. ProcessDeclAttributeList(S, New, Attr);
  10932. // Set the lexical context. If the tag has a C++ scope specifier, the
  10933. // lexical context will be different from the semantic context.
  10934. New->setLexicalDeclContext(CurContext);
  10935. // Mark this as a friend decl if applicable.
  10936. // In Microsoft mode, a friend declaration also acts as a forward
  10937. // declaration so we always pass true to setObjectOfFriendDecl to make
  10938. // the tag name visible.
  10939. if (TUK == TUK_Friend)
  10940. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  10941. // Set the access specifier.
  10942. if (!Invalid && SearchDC->isRecord())
  10943. SetMemberAccessSpecifier(New, PrevDecl, AS);
  10944. if (TUK == TUK_Definition)
  10945. New->startDefinition();
  10946. // If this has an identifier, add it to the scope stack.
  10947. if (TUK == TUK_Friend) {
  10948. // We might be replacing an existing declaration in the lookup tables;
  10949. // if so, borrow its access specifier.
  10950. if (PrevDecl)
  10951. New->setAccess(PrevDecl->getAccess());
  10952. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  10953. DC->makeDeclVisibleInContext(New);
  10954. if (Name) // can be null along some error paths
  10955. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  10956. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  10957. } else if (Name) {
  10958. S = getNonFieldDeclScope(S);
  10959. PushOnScopeChains(New, S, !IsForwardReference);
  10960. if (IsForwardReference)
  10961. SearchDC->makeDeclVisibleInContext(New);
  10962. } else {
  10963. CurContext->addDecl(New);
  10964. }
  10965. // If this is the C FILE type, notify the AST context.
  10966. if (IdentifierInfo *II = New->getIdentifier())
  10967. if (!New->isInvalidDecl() &&
  10968. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  10969. II->isStr("FILE"))
  10970. Context.setFILEDecl(New);
  10971. if (PrevDecl)
  10972. mergeDeclAttributes(New, PrevDecl);
  10973. // If there's a #pragma GCC visibility in scope, set the visibility of this
  10974. // record.
  10975. AddPushedVisibilityAttribute(New);
  10976. OwnedDecl = true;
  10977. // In C++, don't return an invalid declaration. We can't recover well from
  10978. // the cases where we make the type anonymous.
  10979. return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
  10980. }
  10981. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  10982. AdjustDeclIfTemplate(TagD);
  10983. TagDecl *Tag = cast<TagDecl>(TagD);
  10984. // Enter the tag context.
  10985. PushDeclContext(S, Tag);
  10986. ActOnDocumentableDecl(TagD);
  10987. // If there's a #pragma GCC visibility in scope, set the visibility of this
  10988. // record.
  10989. AddPushedVisibilityAttribute(Tag);
  10990. }
  10991. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  10992. assert(isa<ObjCContainerDecl>(IDecl) &&
  10993. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  10994. DeclContext *OCD = cast<DeclContext>(IDecl);
  10995. assert(getContainingDC(OCD) == CurContext &&
  10996. "The next DeclContext should be lexically contained in the current one.");
  10997. CurContext = OCD;
  10998. return IDecl;
  10999. }
  11000. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  11001. SourceLocation FinalLoc,
  11002. bool IsFinalSpelledSealed,
  11003. SourceLocation LBraceLoc) {
  11004. AdjustDeclIfTemplate(TagD);
  11005. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  11006. FieldCollector->StartClass();
  11007. if (!Record->getIdentifier())
  11008. return;
  11009. if (FinalLoc.isValid())
  11010. Record->addAttr(new (Context)
  11011. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  11012. // C++ [class]p2:
  11013. // [...] The class-name is also inserted into the scope of the
  11014. // class itself; this is known as the injected-class-name. For
  11015. // purposes of access checking, the injected-class-name is treated
  11016. // as if it were a public member name.
  11017. CXXRecordDecl *InjectedClassName
  11018. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  11019. Record->getLocStart(), Record->getLocation(),
  11020. Record->getIdentifier(),
  11021. /*PrevDecl=*/nullptr,
  11022. /*DelayTypeCreation=*/true);
  11023. Context.getTypeDeclType(InjectedClassName, Record);
  11024. InjectedClassName->setImplicit();
  11025. InjectedClassName->setAccess(AS_public);
  11026. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  11027. InjectedClassName->setDescribedClassTemplate(Template);
  11028. PushOnScopeChains(InjectedClassName, S);
  11029. assert(InjectedClassName->isInjectedClassName() &&
  11030. "Broken injected-class-name");
  11031. }
  11032. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  11033. SourceLocation RBraceLoc) {
  11034. AdjustDeclIfTemplate(TagD);
  11035. TagDecl *Tag = cast<TagDecl>(TagD);
  11036. Tag->setRBraceLoc(RBraceLoc);
  11037. // Make sure we "complete" the definition even it is invalid.
  11038. if (Tag->isBeingDefined()) {
  11039. assert(Tag->isInvalidDecl() && "We should already have completed it");
  11040. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  11041. RD->completeDefinition();
  11042. }
  11043. if (isa<CXXRecordDecl>(Tag))
  11044. FieldCollector->FinishClass();
  11045. // Exit this scope of this tag's definition.
  11046. PopDeclContext();
  11047. if (getCurLexicalContext()->isObjCContainer() &&
  11048. Tag->getDeclContext()->isFileContext())
  11049. Tag->setTopLevelDeclInObjCContainer();
  11050. // Notify the consumer that we've defined a tag.
  11051. if (!Tag->isInvalidDecl())
  11052. Consumer.HandleTagDeclDefinition(Tag);
  11053. }
  11054. void Sema::ActOnObjCContainerFinishDefinition() {
  11055. // Exit this scope of this interface definition.
  11056. PopDeclContext();
  11057. }
  11058. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  11059. assert(DC == CurContext && "Mismatch of container contexts");
  11060. OriginalLexicalContext = DC;
  11061. ActOnObjCContainerFinishDefinition();
  11062. }
  11063. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  11064. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  11065. OriginalLexicalContext = nullptr;
  11066. }
  11067. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  11068. AdjustDeclIfTemplate(TagD);
  11069. TagDecl *Tag = cast<TagDecl>(TagD);
  11070. Tag->setInvalidDecl();
  11071. // Make sure we "complete" the definition even it is invalid.
  11072. if (Tag->isBeingDefined()) {
  11073. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  11074. RD->completeDefinition();
  11075. }
  11076. // We're undoing ActOnTagStartDefinition here, not
  11077. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  11078. // the FieldCollector.
  11079. PopDeclContext();
  11080. }
  11081. // Note that FieldName may be null for anonymous bitfields.
  11082. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  11083. IdentifierInfo *FieldName,
  11084. QualType FieldTy, bool IsMsStruct,
  11085. Expr *BitWidth, bool *ZeroWidth) {
  11086. // Default to true; that shouldn't confuse checks for emptiness
  11087. if (ZeroWidth)
  11088. *ZeroWidth = true;
  11089. // C99 6.7.2.1p4 - verify the field type.
  11090. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  11091. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  11092. // Handle incomplete types with specific error.
  11093. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  11094. return ExprError();
  11095. if (FieldName)
  11096. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  11097. << FieldName << FieldTy << BitWidth->getSourceRange();
  11098. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  11099. << FieldTy << BitWidth->getSourceRange();
  11100. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  11101. UPPC_BitFieldWidth))
  11102. return ExprError();
  11103. // If the bit-width is type- or value-dependent, don't try to check
  11104. // it now.
  11105. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  11106. return BitWidth;
  11107. llvm::APSInt Value;
  11108. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  11109. if (ICE.isInvalid())
  11110. return ICE;
  11111. BitWidth = ICE.get();
  11112. if (Value != 0 && ZeroWidth)
  11113. *ZeroWidth = false;
  11114. // Zero-width bitfield is ok for anonymous field.
  11115. if (Value == 0 && FieldName)
  11116. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  11117. if (Value.isSigned() && Value.isNegative()) {
  11118. if (FieldName)
  11119. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  11120. << FieldName << Value.toString(10);
  11121. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  11122. << Value.toString(10);
  11123. }
  11124. if (!FieldTy->isDependentType()) {
  11125. uint64_t TypeSize = Context.getTypeSize(FieldTy);
  11126. if (Value.getZExtValue() > TypeSize) {
  11127. if (!getLangOpts().CPlusPlus || IsMsStruct ||
  11128. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  11129. if (FieldName)
  11130. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
  11131. << FieldName << (unsigned)Value.getZExtValue()
  11132. << (unsigned)TypeSize;
  11133. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
  11134. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  11135. }
  11136. if (FieldName)
  11137. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
  11138. << FieldName << (unsigned)Value.getZExtValue()
  11139. << (unsigned)TypeSize;
  11140. else
  11141. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
  11142. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  11143. }
  11144. }
  11145. return BitWidth;
  11146. }
  11147. /// ActOnField - Each field of a C struct/union is passed into this in order
  11148. /// to create a FieldDecl object for it.
  11149. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  11150. Declarator &D, Expr *BitfieldWidth) {
  11151. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  11152. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  11153. /*InitStyle=*/ICIS_NoInit, AS_public);
  11154. return Res;
  11155. }
  11156. /// HandleField - Analyze a field of a C struct or a C++ data member.
  11157. ///
  11158. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  11159. SourceLocation DeclStart,
  11160. Declarator &D, Expr *BitWidth,
  11161. InClassInitStyle InitStyle,
  11162. AccessSpecifier AS) {
  11163. IdentifierInfo *II = D.getIdentifier();
  11164. SourceLocation Loc = DeclStart;
  11165. if (II) Loc = D.getIdentifierLoc();
  11166. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11167. QualType T = TInfo->getType();
  11168. if (getLangOpts().CPlusPlus) {
  11169. CheckExtraCXXDefaultArguments(D);
  11170. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  11171. UPPC_DataMemberType)) {
  11172. D.setInvalidType();
  11173. T = Context.IntTy;
  11174. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  11175. }
  11176. }
  11177. // HLSL Changes Start
  11178. if (getLangOpts().HLSL) {
  11179. const bool IsParameterFalse = false;
  11180. if (!DiagnoseHLSLDecl(D, CurContext, BitWidth, TInfo, IsParameterFalse)) {
  11181. // Let the diagnostic provide errors, don't actually return nullptr here;
  11182. // compilation will recover, which is helpful because HLSL diagnostics
  11183. // need not interrupt the declaration processing.
  11184. }
  11185. }
  11186. // HLSL Changes End
  11187. // TR 18037 does not allow fields to be declared with address spaces.
  11188. if (T.getQualifiers().hasAddressSpace()) {
  11189. Diag(Loc, diag::err_field_with_address_space);
  11190. D.setInvalidType();
  11191. }
  11192. // OpenCL 1.2 spec, s6.9 r:
  11193. // The event type cannot be used to declare a structure or union field.
  11194. if (LangOpts.OpenCL && T->isEventT()) {
  11195. Diag(Loc, diag::err_event_t_struct_field);
  11196. D.setInvalidType();
  11197. }
  11198. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  11199. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  11200. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  11201. diag::err_invalid_thread)
  11202. << DeclSpec::getSpecifierName(TSCS);
  11203. // Check to see if this name was declared as a member previously
  11204. NamedDecl *PrevDecl = nullptr;
  11205. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  11206. LookupName(Previous, S);
  11207. switch (Previous.getResultKind()) {
  11208. case LookupResult::Found:
  11209. case LookupResult::FoundUnresolvedValue:
  11210. PrevDecl = Previous.getAsSingle<NamedDecl>();
  11211. break;
  11212. case LookupResult::FoundOverloaded:
  11213. PrevDecl = Previous.getRepresentativeDecl();
  11214. break;
  11215. case LookupResult::NotFound:
  11216. case LookupResult::NotFoundInCurrentInstantiation:
  11217. case LookupResult::Ambiguous:
  11218. break;
  11219. }
  11220. Previous.suppressDiagnostics();
  11221. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  11222. // Maybe we will complain about the shadowed template parameter.
  11223. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11224. // Just pretend that we didn't see the previous declaration.
  11225. PrevDecl = nullptr;
  11226. }
  11227. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  11228. PrevDecl = nullptr;
  11229. bool Mutable
  11230. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  11231. SourceLocation TSSL = D.getLocStart();
  11232. FieldDecl *NewFD
  11233. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  11234. TSSL, AS, PrevDecl, &D);
  11235. if (NewFD->isInvalidDecl())
  11236. Record->setInvalidDecl();
  11237. TransferUnusualAttributes(D, NewFD); // HLSL Change
  11238. if (D.getDeclSpec().isModulePrivateSpecified())
  11239. NewFD->setModulePrivate();
  11240. if (NewFD->isInvalidDecl() && PrevDecl) {
  11241. // Don't introduce NewFD into scope; there's already something
  11242. // with the same name in the same scope.
  11243. } else if (II) {
  11244. PushOnScopeChains(NewFD, S);
  11245. } else
  11246. Record->addDecl(NewFD);
  11247. return NewFD;
  11248. }
  11249. /// \brief Build a new FieldDecl and check its well-formedness.
  11250. ///
  11251. /// This routine builds a new FieldDecl given the fields name, type,
  11252. /// record, etc. \p PrevDecl should refer to any previous declaration
  11253. /// with the same name and in the same scope as the field to be
  11254. /// created.
  11255. ///
  11256. /// \returns a new FieldDecl.
  11257. ///
  11258. /// \todo The Declarator argument is a hack. It will be removed once
  11259. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  11260. TypeSourceInfo *TInfo,
  11261. RecordDecl *Record, SourceLocation Loc,
  11262. bool Mutable, Expr *BitWidth,
  11263. InClassInitStyle InitStyle,
  11264. SourceLocation TSSL,
  11265. AccessSpecifier AS, NamedDecl *PrevDecl,
  11266. Declarator *D) {
  11267. IdentifierInfo *II = Name.getAsIdentifierInfo();
  11268. bool InvalidDecl = false;
  11269. if (D) InvalidDecl = D->isInvalidType();
  11270. // If we receive a broken type, recover by assuming 'int' and
  11271. // marking this declaration as invalid.
  11272. if (T.isNull()) {
  11273. InvalidDecl = true;
  11274. T = Context.IntTy;
  11275. }
  11276. QualType EltTy = Context.getBaseElementType(T);
  11277. if (!EltTy->isDependentType()) {
  11278. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  11279. // Fields of incomplete type force their record to be invalid.
  11280. Record->setInvalidDecl();
  11281. InvalidDecl = true;
  11282. } else {
  11283. NamedDecl *Def;
  11284. EltTy->isIncompleteType(&Def);
  11285. if (Def && Def->isInvalidDecl()) {
  11286. Record->setInvalidDecl();
  11287. InvalidDecl = true;
  11288. }
  11289. }
  11290. }
  11291. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  11292. if (BitWidth && getLangOpts().OpenCL) {
  11293. Diag(Loc, diag::err_opencl_bitfields);
  11294. InvalidDecl = true;
  11295. }
  11296. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  11297. // than a variably modified type.
  11298. if (!InvalidDecl && T->isVariablyModifiedType()) {
  11299. bool SizeIsNegative;
  11300. llvm::APSInt Oversized;
  11301. TypeSourceInfo *FixedTInfo =
  11302. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  11303. SizeIsNegative,
  11304. Oversized);
  11305. if (FixedTInfo) {
  11306. Diag(Loc, diag::warn_illegal_constant_array_size);
  11307. TInfo = FixedTInfo;
  11308. T = FixedTInfo->getType();
  11309. } else {
  11310. if (SizeIsNegative)
  11311. Diag(Loc, diag::err_typecheck_negative_array_size);
  11312. else if (Oversized.getBoolValue())
  11313. Diag(Loc, diag::err_array_too_large)
  11314. << Oversized.toString(10);
  11315. else
  11316. Diag(Loc, diag::err_typecheck_field_variable_size);
  11317. InvalidDecl = true;
  11318. }
  11319. }
  11320. // Fields can not have abstract class types
  11321. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  11322. diag::err_abstract_type_in_decl,
  11323. AbstractFieldType))
  11324. InvalidDecl = true;
  11325. bool ZeroWidth = false;
  11326. if (InvalidDecl)
  11327. BitWidth = nullptr;
  11328. // If this is declared as a bit-field, check the bit-field.
  11329. if (BitWidth) {
  11330. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  11331. &ZeroWidth).get();
  11332. if (!BitWidth) {
  11333. InvalidDecl = true;
  11334. BitWidth = nullptr;
  11335. ZeroWidth = false;
  11336. }
  11337. }
  11338. // Check that 'mutable' is consistent with the type of the declaration.
  11339. if (!InvalidDecl && Mutable) {
  11340. unsigned DiagID = 0;
  11341. if (T->isReferenceType())
  11342. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  11343. : diag::err_mutable_reference;
  11344. else if (T.isConstQualified())
  11345. DiagID = diag::err_mutable_const;
  11346. if (DiagID) {
  11347. SourceLocation ErrLoc = Loc;
  11348. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  11349. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  11350. Diag(ErrLoc, DiagID);
  11351. if (DiagID != diag::ext_mutable_reference) {
  11352. Mutable = false;
  11353. InvalidDecl = true;
  11354. }
  11355. }
  11356. }
  11357. // C++11 [class.union]p8 (DR1460):
  11358. // At most one variant member of a union may have a
  11359. // brace-or-equal-initializer.
  11360. if (InitStyle != ICIS_NoInit)
  11361. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  11362. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  11363. BitWidth, Mutable, InitStyle);
  11364. if (InvalidDecl)
  11365. NewFD->setInvalidDecl();
  11366. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  11367. Diag(Loc, diag::err_duplicate_member) << II;
  11368. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11369. NewFD->setInvalidDecl();
  11370. }
  11371. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  11372. if (Record->isUnion()) {
  11373. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  11374. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  11375. if (RDecl->getDefinition()) {
  11376. // C++ [class.union]p1: An object of a class with a non-trivial
  11377. // constructor, a non-trivial copy constructor, a non-trivial
  11378. // destructor, or a non-trivial copy assignment operator
  11379. // cannot be a member of a union, nor can an array of such
  11380. // objects.
  11381. if (CheckNontrivialField(NewFD))
  11382. NewFD->setInvalidDecl();
  11383. }
  11384. }
  11385. // C++ [class.union]p1: If a union contains a member of reference type,
  11386. // the program is ill-formed, except when compiling with MSVC extensions
  11387. // enabled.
  11388. if (EltTy->isReferenceType()) {
  11389. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  11390. diag::ext_union_member_of_reference_type :
  11391. diag::err_union_member_of_reference_type)
  11392. << NewFD->getDeclName() << EltTy;
  11393. if (!getLangOpts().MicrosoftExt)
  11394. NewFD->setInvalidDecl();
  11395. }
  11396. }
  11397. }
  11398. // FIXME: We need to pass in the attributes given an AST
  11399. // representation, not a parser representation.
  11400. if (D) {
  11401. // FIXME: The current scope is almost... but not entirely... correct here.
  11402. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  11403. if (NewFD->hasAttrs())
  11404. CheckAlignasUnderalignment(NewFD);
  11405. }
  11406. // In auto-retain/release, infer strong retension for fields of
  11407. // retainable type.
  11408. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  11409. NewFD->setInvalidDecl();
  11410. if (T.isObjCGCWeak())
  11411. Diag(Loc, diag::warn_attribute_weak_on_field);
  11412. NewFD->setAccess(AS);
  11413. return NewFD;
  11414. }
  11415. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  11416. assert(FD);
  11417. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  11418. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  11419. return false;
  11420. QualType EltTy = Context.getBaseElementType(FD->getType());
  11421. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  11422. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  11423. if (RDecl->getDefinition()) {
  11424. // We check for copy constructors before constructors
  11425. // because otherwise we'll never get complaints about
  11426. // copy constructors.
  11427. CXXSpecialMember member = CXXInvalid;
  11428. // We're required to check for any non-trivial constructors. Since the
  11429. // implicit default constructor is suppressed if there are any
  11430. // user-declared constructors, we just need to check that there is a
  11431. // trivial default constructor and a trivial copy constructor. (We don't
  11432. // worry about move constructors here, since this is a C++98 check.)
  11433. if (RDecl->hasNonTrivialCopyConstructor())
  11434. member = CXXCopyConstructor;
  11435. else if (!RDecl->hasTrivialDefaultConstructor())
  11436. member = CXXDefaultConstructor;
  11437. else if (RDecl->hasNonTrivialCopyAssignment())
  11438. member = CXXCopyAssignment;
  11439. else if (RDecl->hasNonTrivialDestructor())
  11440. member = CXXDestructor;
  11441. if (member != CXXInvalid) {
  11442. if (!getLangOpts().CPlusPlus11 &&
  11443. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  11444. // Objective-C++ ARC: it is an error to have a non-trivial field of
  11445. // a union. However, system headers in Objective-C programs
  11446. // occasionally have Objective-C lifetime objects within unions,
  11447. // and rather than cause the program to fail, we make those
  11448. // members unavailable.
  11449. SourceLocation Loc = FD->getLocation();
  11450. if (getSourceManager().isInSystemHeader(Loc)) {
  11451. if (!FD->hasAttr<UnavailableAttr>())
  11452. FD->addAttr(UnavailableAttr::CreateImplicit(Context,
  11453. "this system field has retaining ownership",
  11454. Loc));
  11455. return false;
  11456. }
  11457. }
  11458. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  11459. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  11460. diag::err_illegal_union_or_anon_struct_member)
  11461. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  11462. DiagnoseNontrivial(RDecl, member);
  11463. return !getLangOpts().CPlusPlus11;
  11464. }
  11465. }
  11466. }
  11467. return false;
  11468. }
  11469. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  11470. /// AST enum value.
  11471. static ObjCIvarDecl::AccessControl
  11472. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  11473. switch (ivarVisibility) {
  11474. default: llvm_unreachable("Unknown visitibility kind");
  11475. case tok::objc_private: return ObjCIvarDecl::Private;
  11476. case tok::objc_public: return ObjCIvarDecl::Public;
  11477. case tok::objc_protected: return ObjCIvarDecl::Protected;
  11478. case tok::objc_package: return ObjCIvarDecl::Package;
  11479. }
  11480. }
  11481. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  11482. /// in order to create an IvarDecl object for it.
  11483. Decl *Sema::ActOnIvar(Scope *S,
  11484. SourceLocation DeclStart,
  11485. Declarator &D, Expr *BitfieldWidth,
  11486. tok::ObjCKeywordKind Visibility) {
  11487. IdentifierInfo *II = D.getIdentifier();
  11488. Expr *BitWidth = (Expr*)BitfieldWidth;
  11489. SourceLocation Loc = DeclStart;
  11490. if (II) Loc = D.getIdentifierLoc();
  11491. // FIXME: Unnamed fields can be handled in various different ways, for
  11492. // example, unnamed unions inject all members into the struct namespace!
  11493. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11494. QualType T = TInfo->getType();
  11495. if (BitWidth) {
  11496. // 6.7.2.1p3, 6.7.2.1p4
  11497. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  11498. if (!BitWidth)
  11499. D.setInvalidType();
  11500. } else {
  11501. // Not a bitfield.
  11502. // validate II.
  11503. }
  11504. if (T->isReferenceType()) {
  11505. Diag(Loc, diag::err_ivar_reference_type);
  11506. D.setInvalidType();
  11507. }
  11508. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  11509. // than a variably modified type.
  11510. else if (T->isVariablyModifiedType()) {
  11511. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  11512. D.setInvalidType();
  11513. }
  11514. // Get the visibility (access control) for this ivar.
  11515. ObjCIvarDecl::AccessControl ac =
  11516. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  11517. : ObjCIvarDecl::None;
  11518. // Must set ivar's DeclContext to its enclosing interface.
  11519. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  11520. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  11521. return nullptr;
  11522. ObjCContainerDecl *EnclosingContext;
  11523. if (ObjCImplementationDecl *IMPDecl =
  11524. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  11525. if (LangOpts.ObjCRuntime.isFragile()) {
  11526. // Case of ivar declared in an implementation. Context is that of its class.
  11527. EnclosingContext = IMPDecl->getClassInterface();
  11528. assert(EnclosingContext && "Implementation has no class interface!");
  11529. }
  11530. else
  11531. EnclosingContext = EnclosingDecl;
  11532. } else {
  11533. if (ObjCCategoryDecl *CDecl =
  11534. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  11535. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  11536. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  11537. return nullptr;
  11538. }
  11539. }
  11540. EnclosingContext = EnclosingDecl;
  11541. }
  11542. // Construct the decl.
  11543. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  11544. DeclStart, Loc, II, T,
  11545. TInfo, ac, (Expr *)BitfieldWidth);
  11546. if (II) {
  11547. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  11548. ForRedeclaration);
  11549. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  11550. && !isa<TagDecl>(PrevDecl)) {
  11551. Diag(Loc, diag::err_duplicate_member) << II;
  11552. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11553. NewID->setInvalidDecl();
  11554. }
  11555. }
  11556. // Process attributes attached to the ivar.
  11557. ProcessDeclAttributes(S, NewID, D);
  11558. if (D.isInvalidType())
  11559. NewID->setInvalidDecl();
  11560. // In ARC, infer 'retaining' for ivars of retainable type.
  11561. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  11562. NewID->setInvalidDecl();
  11563. if (D.getDeclSpec().isModulePrivateSpecified())
  11564. NewID->setModulePrivate();
  11565. if (II) {
  11566. // FIXME: When interfaces are DeclContexts, we'll need to add
  11567. // these to the interface.
  11568. S->AddDecl(NewID);
  11569. IdResolver.AddDecl(NewID);
  11570. }
  11571. if (LangOpts.ObjCRuntime.isNonFragile() &&
  11572. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  11573. Diag(Loc, diag::warn_ivars_in_interface);
  11574. return NewID;
  11575. }
  11576. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  11577. /// class and class extensions. For every class \@interface and class
  11578. /// extension \@interface, if the last ivar is a bitfield of any type,
  11579. /// then add an implicit `char :0` ivar to the end of that interface.
  11580. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  11581. SmallVectorImpl<Decl *> &AllIvarDecls) {
  11582. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  11583. return;
  11584. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  11585. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  11586. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  11587. return;
  11588. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  11589. if (!ID) {
  11590. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  11591. if (!CD->IsClassExtension())
  11592. return;
  11593. }
  11594. // No need to add this to end of @implementation.
  11595. else
  11596. return;
  11597. }
  11598. // All conditions are met. Add a new bitfield to the tail end of ivars.
  11599. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  11600. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  11601. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  11602. DeclLoc, DeclLoc, nullptr,
  11603. Context.CharTy,
  11604. Context.getTrivialTypeSourceInfo(Context.CharTy,
  11605. DeclLoc),
  11606. ObjCIvarDecl::Private, BW,
  11607. true);
  11608. AllIvarDecls.push_back(Ivar);
  11609. }
  11610. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  11611. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  11612. SourceLocation RBrac, AttributeList *Attr) {
  11613. assert(EnclosingDecl && "missing record or interface decl");
  11614. // If this is an Objective-C @implementation or category and we have
  11615. // new fields here we should reset the layout of the interface since
  11616. // it will now change.
  11617. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  11618. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  11619. switch (DC->getKind()) {
  11620. default: break;
  11621. case Decl::ObjCCategory:
  11622. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  11623. break;
  11624. case Decl::ObjCImplementation:
  11625. Context.
  11626. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  11627. break;
  11628. }
  11629. }
  11630. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  11631. // Start counting up the number of named members; make sure to include
  11632. // members of anonymous structs and unions in the total.
  11633. unsigned NumNamedMembers = 0;
  11634. if (Record) {
  11635. for (const auto *I : Record->decls()) {
  11636. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  11637. if (IFD->getDeclName())
  11638. ++NumNamedMembers;
  11639. }
  11640. }
  11641. // Verify that all the fields are okay.
  11642. SmallVector<FieldDecl*, 32> RecFields;
  11643. bool ARCErrReported = false;
  11644. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  11645. i != end; ++i) {
  11646. FieldDecl *FD = cast<FieldDecl>(*i);
  11647. // Get the type for the field.
  11648. const Type *FDTy = FD->getType().getTypePtr();
  11649. if (!FD->isAnonymousStructOrUnion()) {
  11650. // Remember all fields written by the user.
  11651. RecFields.push_back(FD);
  11652. }
  11653. // If the field is already invalid for some reason, don't emit more
  11654. // diagnostics about it.
  11655. if (FD->isInvalidDecl()) {
  11656. EnclosingDecl->setInvalidDecl();
  11657. continue;
  11658. }
  11659. // C99 6.7.2.1p2:
  11660. // A structure or union shall not contain a member with
  11661. // incomplete or function type (hence, a structure shall not
  11662. // contain an instance of itself, but may contain a pointer to
  11663. // an instance of itself), except that the last member of a
  11664. // structure with more than one named member may have incomplete
  11665. // array type; such a structure (and any union containing,
  11666. // possibly recursively, a member that is such a structure)
  11667. // shall not be a member of a structure or an element of an
  11668. // array.
  11669. if (FDTy->isFunctionType()) {
  11670. // Field declared as a function.
  11671. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  11672. << FD->getDeclName();
  11673. FD->setInvalidDecl();
  11674. EnclosingDecl->setInvalidDecl();
  11675. continue;
  11676. } else if (FDTy->isIncompleteArrayType() && Record &&
  11677. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  11678. ((getLangOpts().MicrosoftExt ||
  11679. getLangOpts().CPlusPlus) &&
  11680. (i + 1 == Fields.end() || Record->isUnion())))) {
  11681. // Flexible array member.
  11682. // Microsoft and g++ is more permissive regarding flexible array.
  11683. // It will accept flexible array in union and also
  11684. // as the sole element of a struct/class.
  11685. unsigned DiagID = 0;
  11686. if (Record->isUnion())
  11687. DiagID = getLangOpts().MicrosoftExt
  11688. ? diag::ext_flexible_array_union_ms
  11689. : getLangOpts().CPlusPlus
  11690. ? diag::ext_flexible_array_union_gnu
  11691. : diag::err_flexible_array_union;
  11692. else if (Fields.size() == 1)
  11693. DiagID = getLangOpts().MicrosoftExt
  11694. ? diag::ext_flexible_array_empty_aggregate_ms
  11695. : getLangOpts().CPlusPlus
  11696. ? diag::ext_flexible_array_empty_aggregate_gnu
  11697. : NumNamedMembers < 1
  11698. ? diag::err_flexible_array_empty_aggregate
  11699. : 0;
  11700. if (DiagID)
  11701. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  11702. << Record->getTagKind();
  11703. // While the layout of types that contain virtual bases is not specified
  11704. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  11705. // virtual bases after the derived members. This would make a flexible
  11706. // array member declared at the end of an object not adjacent to the end
  11707. // of the type.
  11708. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  11709. if (RD->getNumVBases() != 0)
  11710. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  11711. << FD->getDeclName() << Record->getTagKind();
  11712. if (!getLangOpts().C99)
  11713. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  11714. << FD->getDeclName() << Record->getTagKind();
  11715. // If the element type has a non-trivial destructor, we would not
  11716. // implicitly destroy the elements, so disallow it for now.
  11717. //
  11718. // FIXME: GCC allows this. We should probably either implicitly delete
  11719. // the destructor of the containing class, or just allow this.
  11720. QualType BaseElem = Context.getBaseElementType(FD->getType());
  11721. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  11722. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  11723. << FD->getDeclName() << FD->getType();
  11724. FD->setInvalidDecl();
  11725. EnclosingDecl->setInvalidDecl();
  11726. continue;
  11727. }
  11728. // Okay, we have a legal flexible array member at the end of the struct.
  11729. Record->setHasFlexibleArrayMember(true);
  11730. } else if (!FDTy->isDependentType() &&
  11731. RequireCompleteType(FD->getLocation(), FD->getType(),
  11732. diag::err_field_incomplete)) {
  11733. // Incomplete type
  11734. FD->setInvalidDecl();
  11735. EnclosingDecl->setInvalidDecl();
  11736. continue;
  11737. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  11738. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  11739. // A type which contains a flexible array member is considered to be a
  11740. // flexible array member.
  11741. Record->setHasFlexibleArrayMember(true);
  11742. if (!Record->isUnion()) {
  11743. // If this is a struct/class and this is not the last element, reject
  11744. // it. Note that GCC supports variable sized arrays in the middle of
  11745. // structures.
  11746. if (i + 1 != Fields.end())
  11747. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  11748. << FD->getDeclName() << FD->getType();
  11749. else {
  11750. // We support flexible arrays at the end of structs in
  11751. // other structs as an extension.
  11752. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  11753. << FD->getDeclName();
  11754. }
  11755. }
  11756. }
  11757. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  11758. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  11759. diag::err_abstract_type_in_decl,
  11760. AbstractIvarType)) {
  11761. // Ivars can not have abstract class types
  11762. FD->setInvalidDecl();
  11763. }
  11764. if (Record && FDTTy->getDecl()->hasObjectMember())
  11765. Record->setHasObjectMember(true);
  11766. if (Record && FDTTy->getDecl()->hasVolatileMember())
  11767. Record->setHasVolatileMember(true);
  11768. } else if (FDTy->isObjCObjectType()) {
  11769. /// A field cannot be an Objective-c object
  11770. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  11771. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  11772. QualType T = Context.getObjCObjectPointerType(FD->getType());
  11773. FD->setType(T);
  11774. } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
  11775. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  11776. // It's an error in ARC if a field has lifetime.
  11777. // We don't want to report this in a system header, though,
  11778. // so we just make the field unavailable.
  11779. // FIXME: that's really not sufficient; we need to make the type
  11780. // itself invalid to, say, initialize or copy.
  11781. QualType T = FD->getType();
  11782. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  11783. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  11784. SourceLocation loc = FD->getLocation();
  11785. if (getSourceManager().isInSystemHeader(loc)) {
  11786. if (!FD->hasAttr<UnavailableAttr>()) {
  11787. FD->addAttr(UnavailableAttr::CreateImplicit(Context,
  11788. "this system field has retaining ownership",
  11789. loc));
  11790. }
  11791. } else {
  11792. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  11793. << T->isBlockPointerType() << Record->getTagKind();
  11794. }
  11795. ARCErrReported = true;
  11796. }
  11797. } else if (getLangOpts().ObjC1 &&
  11798. getLangOpts().getGC() != LangOptions::NonGC &&
  11799. Record && !Record->hasObjectMember()) {
  11800. if (FD->getType()->isObjCObjectPointerType() ||
  11801. FD->getType().isObjCGCStrong())
  11802. Record->setHasObjectMember(true);
  11803. else if (Context.getAsArrayType(FD->getType())) {
  11804. QualType BaseType = Context.getBaseElementType(FD->getType());
  11805. if (BaseType->isRecordType() &&
  11806. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  11807. Record->setHasObjectMember(true);
  11808. else if (BaseType->isObjCObjectPointerType() ||
  11809. BaseType.isObjCGCStrong())
  11810. Record->setHasObjectMember(true);
  11811. }
  11812. }
  11813. if (Record && FD->getType().isVolatileQualified())
  11814. Record->setHasVolatileMember(true);
  11815. // Keep track of the number of named members.
  11816. if (FD->getIdentifier())
  11817. ++NumNamedMembers;
  11818. }
  11819. // Okay, we successfully defined 'Record'.
  11820. if (Record) {
  11821. bool Completed = false;
  11822. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  11823. if (!CXXRecord->isInvalidDecl()) {
  11824. // Set access bits correctly on the directly-declared conversions.
  11825. for (CXXRecordDecl::conversion_iterator
  11826. I = CXXRecord->conversion_begin(),
  11827. E = CXXRecord->conversion_end(); I != E; ++I)
  11828. I.setAccess((*I)->getAccess());
  11829. if (!CXXRecord->isDependentType()) {
  11830. if (CXXRecord->hasUserDeclaredDestructor()) {
  11831. // Adjust user-defined destructor exception spec.
  11832. if (getLangOpts().CPlusPlus11)
  11833. AdjustDestructorExceptionSpec(CXXRecord,
  11834. CXXRecord->getDestructor());
  11835. }
  11836. // Add any implicitly-declared members to this class.
  11837. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  11838. // If we have virtual base classes, we may end up finding multiple
  11839. // final overriders for a given virtual function. Check for this
  11840. // problem now.
  11841. if (CXXRecord->getNumVBases()) {
  11842. CXXFinalOverriderMap FinalOverriders;
  11843. CXXRecord->getFinalOverriders(FinalOverriders);
  11844. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  11845. MEnd = FinalOverriders.end();
  11846. M != MEnd; ++M) {
  11847. for (OverridingMethods::iterator SO = M->second.begin(),
  11848. SOEnd = M->second.end();
  11849. SO != SOEnd; ++SO) {
  11850. assert(SO->second.size() > 0 &&
  11851. "Virtual function without overridding functions?");
  11852. if (SO->second.size() == 1)
  11853. continue;
  11854. // C++ [class.virtual]p2:
  11855. // In a derived class, if a virtual member function of a base
  11856. // class subobject has more than one final overrider the
  11857. // program is ill-formed.
  11858. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  11859. << (const NamedDecl *)M->first << Record;
  11860. Diag(M->first->getLocation(),
  11861. diag::note_overridden_virtual_function);
  11862. for (OverridingMethods::overriding_iterator
  11863. OM = SO->second.begin(),
  11864. OMEnd = SO->second.end();
  11865. OM != OMEnd; ++OM)
  11866. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  11867. << (const NamedDecl *)M->first << OM->Method->getParent();
  11868. Record->setInvalidDecl();
  11869. }
  11870. }
  11871. CXXRecord->completeDefinition(&FinalOverriders);
  11872. Completed = true;
  11873. }
  11874. }
  11875. }
  11876. }
  11877. if (!Completed)
  11878. Record->completeDefinition();
  11879. if (Record->hasAttrs()) {
  11880. CheckAlignasUnderalignment(Record);
  11881. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  11882. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  11883. IA->getRange(), IA->getBestCase(),
  11884. IA->getSemanticSpelling());
  11885. }
  11886. // Check if the structure/union declaration is a type that can have zero
  11887. // size in C. For C this is a language extension, for C++ it may cause
  11888. // compatibility problems.
  11889. bool CheckForZeroSize;
  11890. if (!getLangOpts().CPlusPlus) {
  11891. CheckForZeroSize = true;
  11892. } else {
  11893. // For C++ filter out types that cannot be referenced in C code.
  11894. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  11895. CheckForZeroSize =
  11896. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  11897. !CXXRecord->isDependentType() &&
  11898. CXXRecord->isCLike();
  11899. }
  11900. if (CheckForZeroSize) {
  11901. bool ZeroSize = true;
  11902. bool IsEmpty = true;
  11903. unsigned NonBitFields = 0;
  11904. for (RecordDecl::field_iterator I = Record->field_begin(),
  11905. E = Record->field_end();
  11906. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  11907. IsEmpty = false;
  11908. if (I->isUnnamedBitfield()) {
  11909. if (I->getBitWidthValue(Context) > 0)
  11910. ZeroSize = false;
  11911. } else {
  11912. ++NonBitFields;
  11913. QualType FieldType = I->getType();
  11914. if (FieldType->isIncompleteType() ||
  11915. !Context.getTypeSizeInChars(FieldType).isZero())
  11916. ZeroSize = false;
  11917. }
  11918. }
  11919. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  11920. // allowed in C++, but warn if its declaration is inside
  11921. // extern "C" block.
  11922. if (ZeroSize) {
  11923. Diag(RecLoc, getLangOpts().CPlusPlus ?
  11924. diag::warn_zero_size_struct_union_in_extern_c :
  11925. diag::warn_zero_size_struct_union_compat)
  11926. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  11927. }
  11928. // Structs without named members are extension in C (C99 6.7.2.1p7),
  11929. // but are accepted by GCC.
  11930. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  11931. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  11932. diag::ext_no_named_members_in_struct_union)
  11933. << Record->isUnion();
  11934. }
  11935. }
  11936. } else {
  11937. ObjCIvarDecl **ClsFields =
  11938. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  11939. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  11940. ID->setEndOfDefinitionLoc(RBrac);
  11941. // Add ivar's to class's DeclContext.
  11942. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  11943. ClsFields[i]->setLexicalDeclContext(ID);
  11944. ID->addDecl(ClsFields[i]);
  11945. }
  11946. // Must enforce the rule that ivars in the base classes may not be
  11947. // duplicates.
  11948. if (ID->getSuperClass())
  11949. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  11950. } else if (ObjCImplementationDecl *IMPDecl =
  11951. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  11952. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  11953. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  11954. // Ivar declared in @implementation never belongs to the implementation.
  11955. // Only it is in implementation's lexical context.
  11956. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  11957. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  11958. IMPDecl->setIvarLBraceLoc(LBrac);
  11959. IMPDecl->setIvarRBraceLoc(RBrac);
  11960. } else if (ObjCCategoryDecl *CDecl =
  11961. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  11962. // case of ivars in class extension; all other cases have been
  11963. // reported as errors elsewhere.
  11964. // FIXME. Class extension does not have a LocEnd field.
  11965. // CDecl->setLocEnd(RBrac);
  11966. // Add ivar's to class extension's DeclContext.
  11967. // Diagnose redeclaration of private ivars.
  11968. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  11969. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  11970. if (IDecl) {
  11971. if (const ObjCIvarDecl *ClsIvar =
  11972. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  11973. Diag(ClsFields[i]->getLocation(),
  11974. diag::err_duplicate_ivar_declaration);
  11975. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  11976. continue;
  11977. }
  11978. for (const auto *Ext : IDecl->known_extensions()) {
  11979. if (const ObjCIvarDecl *ClsExtIvar
  11980. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  11981. Diag(ClsFields[i]->getLocation(),
  11982. diag::err_duplicate_ivar_declaration);
  11983. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  11984. continue;
  11985. }
  11986. }
  11987. }
  11988. ClsFields[i]->setLexicalDeclContext(CDecl);
  11989. CDecl->addDecl(ClsFields[i]);
  11990. }
  11991. CDecl->setIvarLBraceLoc(LBrac);
  11992. CDecl->setIvarRBraceLoc(RBrac);
  11993. }
  11994. }
  11995. if (Attr)
  11996. ProcessDeclAttributeList(S, Record, Attr);
  11997. }
  11998. /// \brief Determine whether the given integral value is representable within
  11999. /// the given type T.
  12000. static bool isRepresentableIntegerValue(ASTContext &Context,
  12001. llvm::APSInt &Value,
  12002. QualType T) {
  12003. assert(T->isIntegralType(Context) && "Integral type required!");
  12004. unsigned BitWidth = Context.getIntWidth(T);
  12005. if (Value.isUnsigned() || Value.isNonNegative()) {
  12006. if (T->isSignedIntegerOrEnumerationType())
  12007. --BitWidth;
  12008. return Value.getActiveBits() <= BitWidth;
  12009. }
  12010. return Value.getMinSignedBits() <= BitWidth;
  12011. }
  12012. // \brief Given an integral type, return the next larger integral type
  12013. // (or a NULL type of no such type exists).
  12014. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  12015. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  12016. // enum checking below.
  12017. assert(T->isIntegralType(Context) && "Integral type required!");
  12018. const unsigned NumTypes = 4;
  12019. QualType SignedIntegralTypes[NumTypes] = {
  12020. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  12021. };
  12022. QualType UnsignedIntegralTypes[NumTypes] = {
  12023. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  12024. Context.UnsignedLongLongTy
  12025. };
  12026. unsigned BitWidth = Context.getTypeSize(T);
  12027. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  12028. : UnsignedIntegralTypes;
  12029. for (unsigned I = 0; I != NumTypes; ++I)
  12030. if (Context.getTypeSize(Types[I]) > BitWidth)
  12031. return Types[I];
  12032. return QualType();
  12033. }
  12034. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  12035. EnumConstantDecl *LastEnumConst,
  12036. SourceLocation IdLoc,
  12037. IdentifierInfo *Id,
  12038. Expr *Val) {
  12039. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  12040. llvm::APSInt EnumVal(IntWidth);
  12041. QualType EltTy;
  12042. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  12043. Val = nullptr;
  12044. if (Val)
  12045. Val = DefaultLvalueConversion(Val).get();
  12046. if (Val) {
  12047. if (Enum->isDependentType() || Val->isTypeDependent())
  12048. EltTy = Context.DependentTy;
  12049. else {
  12050. SourceLocation ExpLoc;
  12051. // HLSL Change - check constant expression for enum
  12052. if ((getLangOpts().HLSLVersion >= 2017 || getLangOpts().CPlusPlus11) &&
  12053. Enum->isFixed() && !getLangOpts().MSVCCompat) {
  12054. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  12055. // constant-expression in the enumerator-definition shall be a converted
  12056. // constant expression of the underlying type.
  12057. EltTy = Enum->getIntegerType();
  12058. ExprResult Converted =
  12059. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  12060. CCEK_Enumerator);
  12061. if (Converted.isInvalid())
  12062. Val = nullptr;
  12063. else
  12064. Val = Converted.get();
  12065. } else if (!Val->isValueDependent() &&
  12066. !(Val = VerifyIntegerConstantExpression(Val,
  12067. &EnumVal).get())) {
  12068. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  12069. } else {
  12070. if (Enum->isFixed()) {
  12071. EltTy = Enum->getIntegerType();
  12072. // In Obj-C and Microsoft mode, require the enumeration value to be
  12073. // representable in the underlying type of the enumeration. In C++11,
  12074. // we perform a non-narrowing conversion as part of converted constant
  12075. // expression checking.
  12076. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  12077. if (getLangOpts().MSVCCompat) {
  12078. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  12079. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  12080. } else
  12081. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  12082. } else
  12083. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  12084. } else if (getLangOpts().CPlusPlus) {
  12085. // C++11 [dcl.enum]p5:
  12086. // If the underlying type is not fixed, the type of each enumerator
  12087. // is the type of its initializing value:
  12088. // - If an initializer is specified for an enumerator, the
  12089. // initializing value has the same type as the expression.
  12090. EltTy = Val->getType();
  12091. } else {
  12092. // C99 6.7.2.2p2:
  12093. // The expression that defines the value of an enumeration constant
  12094. // shall be an integer constant expression that has a value
  12095. // representable as an int.
  12096. // Complain if the value is not representable in an int.
  12097. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  12098. Diag(IdLoc, diag::ext_enum_value_not_int)
  12099. << EnumVal.toString(10) << Val->getSourceRange()
  12100. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  12101. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  12102. // Force the type of the expression to 'int'.
  12103. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  12104. }
  12105. EltTy = Val->getType();
  12106. }
  12107. }
  12108. }
  12109. }
  12110. if (!Val) {
  12111. if (Enum->isDependentType())
  12112. EltTy = Context.DependentTy;
  12113. else if (!LastEnumConst) {
  12114. // C++0x [dcl.enum]p5:
  12115. // If the underlying type is not fixed, the type of each enumerator
  12116. // is the type of its initializing value:
  12117. // - If no initializer is specified for the first enumerator, the
  12118. // initializing value has an unspecified integral type.
  12119. //
  12120. // GCC uses 'int' for its unspecified integral type, as does
  12121. // C99 6.7.2.2p3.
  12122. if (Enum->isFixed()) {
  12123. EltTy = Enum->getIntegerType();
  12124. }
  12125. else {
  12126. EltTy = Context.IntTy;
  12127. }
  12128. } else {
  12129. // Assign the last value + 1.
  12130. EnumVal = LastEnumConst->getInitVal();
  12131. ++EnumVal;
  12132. EltTy = LastEnumConst->getType();
  12133. // Check for overflow on increment.
  12134. if (EnumVal < LastEnumConst->getInitVal()) {
  12135. // C++0x [dcl.enum]p5:
  12136. // If the underlying type is not fixed, the type of each enumerator
  12137. // is the type of its initializing value:
  12138. //
  12139. // - Otherwise the type of the initializing value is the same as
  12140. // the type of the initializing value of the preceding enumerator
  12141. // unless the incremented value is not representable in that type,
  12142. // in which case the type is an unspecified integral type
  12143. // sufficient to contain the incremented value. If no such type
  12144. // exists, the program is ill-formed.
  12145. QualType T = getNextLargerIntegralType(Context, EltTy);
  12146. if (T.isNull() || Enum->isFixed()) {
  12147. // There is no integral type larger enough to represent this
  12148. // value. Complain, then allow the value to wrap around.
  12149. EnumVal = LastEnumConst->getInitVal();
  12150. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  12151. ++EnumVal;
  12152. if (Enum->isFixed())
  12153. // When the underlying type is fixed, this is ill-formed.
  12154. Diag(IdLoc, diag::err_enumerator_wrapped)
  12155. << EnumVal.toString(10)
  12156. << EltTy;
  12157. else
  12158. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  12159. << EnumVal.toString(10);
  12160. } else {
  12161. EltTy = T;
  12162. }
  12163. // Retrieve the last enumerator's value, extent that type to the
  12164. // type that is supposed to be large enough to represent the incremented
  12165. // value, then increment.
  12166. EnumVal = LastEnumConst->getInitVal();
  12167. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  12168. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  12169. ++EnumVal;
  12170. // If we're not in C++, diagnose the overflow of enumerator values,
  12171. // which in C99 means that the enumerator value is not representable in
  12172. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  12173. // permits enumerator values that are representable in some larger
  12174. // integral type.
  12175. if (!getLangOpts().CPlusPlus && !T.isNull())
  12176. Diag(IdLoc, diag::warn_enum_value_overflow);
  12177. } else if (!getLangOpts().CPlusPlus &&
  12178. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  12179. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  12180. Diag(IdLoc, diag::ext_enum_value_not_int)
  12181. << EnumVal.toString(10) << 1;
  12182. }
  12183. }
  12184. }
  12185. if (!EltTy->isDependentType()) {
  12186. // Make the enumerator value match the signedness and size of the
  12187. // enumerator's type.
  12188. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  12189. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  12190. }
  12191. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  12192. Val, EnumVal);
  12193. }
  12194. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  12195. SourceLocation IILoc) {
  12196. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  12197. !getLangOpts().CPlusPlus)
  12198. return SkipBodyInfo();
  12199. // We have an anonymous enum definition. Look up the first enumerator to
  12200. // determine if we should merge the definition with an existing one and
  12201. // skip the body.
  12202. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  12203. ForRedeclaration);
  12204. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  12205. NamedDecl *Hidden;
  12206. if (PrevECD &&
  12207. !hasVisibleDefinition(cast<NamedDecl>(PrevECD->getDeclContext()),
  12208. &Hidden)) {
  12209. SkipBodyInfo Skip;
  12210. Skip.Previous = Hidden;
  12211. return Skip;
  12212. }
  12213. return SkipBodyInfo();
  12214. }
  12215. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  12216. SourceLocation IdLoc, IdentifierInfo *Id,
  12217. AttributeList *Attr,
  12218. SourceLocation EqualLoc, Expr *Val) {
  12219. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  12220. EnumConstantDecl *LastEnumConst =
  12221. cast_or_null<EnumConstantDecl>(lastEnumConst);
  12222. // The scope passed in may not be a decl scope. Zip up the scope tree until
  12223. // we find one that is.
  12224. S = getNonFieldDeclScope(S);
  12225. // Verify that there isn't already something declared with this name in this
  12226. // scope.
  12227. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  12228. ForRedeclaration);
  12229. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  12230. // Maybe we will complain about the shadowed template parameter.
  12231. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  12232. // Just pretend that we didn't see the previous declaration.
  12233. PrevDecl = nullptr;
  12234. }
  12235. if (PrevDecl) {
  12236. // When in C++, we may get a TagDecl with the same name; in this case the
  12237. // enum constant will 'hide' the tag.
  12238. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  12239. "Received TagDecl when not in C++!");
  12240. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  12241. if (isa<EnumConstantDecl>(PrevDecl))
  12242. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  12243. else
  12244. Diag(IdLoc, diag::err_redefinition) << Id;
  12245. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  12246. return nullptr;
  12247. }
  12248. }
  12249. // C++ [class.mem]p15:
  12250. // If T is the name of a class, then each of the following shall have a name
  12251. // different from T:
  12252. // - every enumerator of every member of class T that is an unscoped
  12253. // enumerated type
  12254. if (!TheEnumDecl->isScoped())
  12255. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  12256. DeclarationNameInfo(Id, IdLoc));
  12257. EnumConstantDecl *New =
  12258. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  12259. if (New) {
  12260. // Process attributes.
  12261. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  12262. // Register this decl in the current scope stack.
  12263. New->setAccess(TheEnumDecl->getAccess());
  12264. PushOnScopeChains(New, S);
  12265. }
  12266. ActOnDocumentableDecl(New);
  12267. return New;
  12268. }
  12269. // Returns true when the enum initial expression does not trigger the
  12270. // duplicate enum warning. A few common cases are exempted as follows:
  12271. // Element2 = Element1
  12272. // Element2 = Element1 + 1
  12273. // Element2 = Element1 - 1
  12274. // Where Element2 and Element1 are from the same enum.
  12275. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  12276. Expr *InitExpr = ECD->getInitExpr();
  12277. if (!InitExpr)
  12278. return true;
  12279. InitExpr = InitExpr->IgnoreImpCasts();
  12280. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  12281. if (!BO->isAdditiveOp())
  12282. return true;
  12283. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  12284. if (!IL)
  12285. return true;
  12286. if (IL->getValue() != 1)
  12287. return true;
  12288. InitExpr = BO->getLHS();
  12289. }
  12290. // This checks if the elements are from the same enum.
  12291. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  12292. if (!DRE)
  12293. return true;
  12294. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  12295. if (!EnumConstant)
  12296. return true;
  12297. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  12298. Enum)
  12299. return true;
  12300. return false;
  12301. }
  12302. struct DupKey {
  12303. int64_t val;
  12304. bool isTombstoneOrEmptyKey;
  12305. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  12306. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  12307. };
  12308. static DupKey GetDupKey(const llvm::APSInt& Val) {
  12309. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  12310. false);
  12311. }
  12312. struct DenseMapInfoDupKey {
  12313. static DupKey getEmptyKey() { return DupKey(0, true); }
  12314. static DupKey getTombstoneKey() { return DupKey(1, true); }
  12315. static unsigned getHashValue(const DupKey Key) {
  12316. return (unsigned)(Key.val * 37);
  12317. }
  12318. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  12319. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  12320. LHS.val == RHS.val;
  12321. }
  12322. };
  12323. // Emits a warning when an element is implicitly set a value that
  12324. // a previous element has already been set to.
  12325. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  12326. EnumDecl *Enum,
  12327. QualType EnumType) {
  12328. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  12329. return;
  12330. // Avoid anonymous enums
  12331. if (!Enum->getIdentifier())
  12332. return;
  12333. // Only check for small enums.
  12334. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  12335. return;
  12336. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  12337. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  12338. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  12339. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  12340. ValueToVectorMap;
  12341. DuplicatesVector DupVector;
  12342. ValueToVectorMap EnumMap;
  12343. // Populate the EnumMap with all values represented by enum constants without
  12344. // an initialier.
  12345. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12346. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  12347. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  12348. // this constant. Skip this enum since it may be ill-formed.
  12349. if (!ECD) {
  12350. return;
  12351. }
  12352. if (ECD->getInitExpr())
  12353. continue;
  12354. DupKey Key = GetDupKey(ECD->getInitVal());
  12355. DeclOrVector &Entry = EnumMap[Key];
  12356. // First time encountering this value.
  12357. if (Entry.isNull())
  12358. Entry = ECD;
  12359. }
  12360. // Create vectors for any values that has duplicates.
  12361. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12362. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  12363. if (!ValidDuplicateEnum(ECD, Enum))
  12364. continue;
  12365. DupKey Key = GetDupKey(ECD->getInitVal());
  12366. DeclOrVector& Entry = EnumMap[Key];
  12367. if (Entry.isNull())
  12368. continue;
  12369. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  12370. // Ensure constants are different.
  12371. if (D == ECD)
  12372. continue;
  12373. // Create new vector and push values onto it.
  12374. ECDVector *Vec = new ECDVector();
  12375. Vec->push_back(D);
  12376. Vec->push_back(ECD);
  12377. // Update entry to point to the duplicates vector.
  12378. Entry = Vec;
  12379. // Store the vector somewhere we can consult later for quick emission of
  12380. // diagnostics.
  12381. DupVector.push_back(Vec);
  12382. continue;
  12383. }
  12384. ECDVector *Vec = Entry.get<ECDVector*>();
  12385. // Make sure constants are not added more than once.
  12386. if (*Vec->begin() == ECD)
  12387. continue;
  12388. Vec->push_back(ECD);
  12389. }
  12390. // Emit diagnostics.
  12391. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  12392. DupVectorEnd = DupVector.end();
  12393. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  12394. ECDVector *Vec = *DupVectorIter;
  12395. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  12396. // Emit warning for one enum constant.
  12397. ECDVector::iterator I = Vec->begin();
  12398. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  12399. << (*I)->getName() << (*I)->getInitVal().toString(10)
  12400. << (*I)->getSourceRange();
  12401. ++I;
  12402. // Emit one note for each of the remaining enum constants with
  12403. // the same value.
  12404. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  12405. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  12406. << (*I)->getName() << (*I)->getInitVal().toString(10)
  12407. << (*I)->getSourceRange();
  12408. delete Vec;
  12409. }
  12410. }
  12411. bool
  12412. Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  12413. bool AllowMask) const {
  12414. FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
  12415. assert(FEAttr && "looking for value in non-flag enum");
  12416. llvm::APInt FlagMask = ~FEAttr->getFlagBits();
  12417. unsigned Width = FlagMask.getBitWidth();
  12418. // We will try a zero-extended value for the regular check first.
  12419. llvm::APInt ExtVal = Val.zextOrSelf(Width);
  12420. // A value is in a flag enum if either its bits are a subset of the enum's
  12421. // flag bits (the first condition) or we are allowing masks and the same is
  12422. // true of its complement (the second condition). When masks are allowed, we
  12423. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  12424. //
  12425. // While it's true that any value could be used as a mask, the assumption is
  12426. // that a mask will have all of the insignificant bits set. Anything else is
  12427. // likely a logic error.
  12428. if (!(FlagMask & ExtVal))
  12429. return true;
  12430. if (AllowMask) {
  12431. // Try a one-extended value instead. This can happen if the enum is wider
  12432. // than the constant used, in C with extensions to allow for wider enums.
  12433. // The mask will still have the correct behaviour, so we give the user the
  12434. // benefit of the doubt.
  12435. //
  12436. // FIXME: This heuristic can cause weird results if the enum was extended
  12437. // to a larger type and is signed, because then bit-masks of smaller types
  12438. // that get extended will fall out of range (e.g. ~0x1u). We currently don't
  12439. // detect that case and will get a false positive for it. In most cases,
  12440. // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
  12441. // be fine just to accept this as a warning.
  12442. ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
  12443. if (!(FlagMask & ~ExtVal))
  12444. return true;
  12445. }
  12446. return false;
  12447. }
  12448. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  12449. SourceLocation RBraceLoc, Decl *EnumDeclX,
  12450. ArrayRef<Decl *> Elements,
  12451. Scope *S, AttributeList *Attr) {
  12452. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  12453. QualType EnumType = Context.getTypeDeclType(Enum);
  12454. if (Attr)
  12455. ProcessDeclAttributeList(S, Enum, Attr);
  12456. if (Enum->isDependentType()) {
  12457. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12458. EnumConstantDecl *ECD =
  12459. cast_or_null<EnumConstantDecl>(Elements[i]);
  12460. if (!ECD) continue;
  12461. ECD->setType(EnumType);
  12462. }
  12463. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  12464. return;
  12465. }
  12466. // TODO: If the result value doesn't fit in an int, it must be a long or long
  12467. // long value. ISO C does not support this, but GCC does as an extension,
  12468. // emit a warning.
  12469. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  12470. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  12471. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  12472. // Verify that all the values are okay, compute the size of the values, and
  12473. // reverse the list.
  12474. unsigned NumNegativeBits = 0;
  12475. unsigned NumPositiveBits = 0;
  12476. // Keep track of whether all elements have type int.
  12477. bool AllElementsInt = true;
  12478. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12479. EnumConstantDecl *ECD =
  12480. cast_or_null<EnumConstantDecl>(Elements[i]);
  12481. if (!ECD) continue; // Already issued a diagnostic.
  12482. const llvm::APSInt &InitVal = ECD->getInitVal();
  12483. // Keep track of the size of positive and negative values.
  12484. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  12485. NumPositiveBits = std::max(NumPositiveBits,
  12486. (unsigned)InitVal.getActiveBits());
  12487. else
  12488. NumNegativeBits = std::max(NumNegativeBits,
  12489. (unsigned)InitVal.getMinSignedBits());
  12490. // Keep track of whether every enum element has type int (very commmon).
  12491. if (AllElementsInt)
  12492. AllElementsInt = ECD->getType() == Context.IntTy;
  12493. }
  12494. // Figure out the type that should be used for this enum.
  12495. QualType BestType;
  12496. unsigned BestWidth;
  12497. // C++0x N3000 [conv.prom]p3:
  12498. // An rvalue of an unscoped enumeration type whose underlying
  12499. // type is not fixed can be converted to an rvalue of the first
  12500. // of the following types that can represent all the values of
  12501. // the enumeration: int, unsigned int, long int, unsigned long
  12502. // int, long long int, or unsigned long long int.
  12503. // C99 6.4.4.3p2:
  12504. // An identifier declared as an enumeration constant has type int.
  12505. // The C99 rule is modified by a gcc extension
  12506. QualType BestPromotionType;
  12507. bool Packed = Enum->hasAttr<PackedAttr>();
  12508. // -fshort-enums is the equivalent to specifying the packed attribute on all
  12509. // enum definitions.
  12510. if (LangOpts.ShortEnums)
  12511. Packed = true;
  12512. if (Enum->isFixed()) {
  12513. BestType = Enum->getIntegerType();
  12514. if (BestType->isPromotableIntegerType())
  12515. BestPromotionType = Context.getPromotedIntegerType(BestType);
  12516. else
  12517. BestPromotionType = BestType;
  12518. BestWidth = Context.getIntWidth(BestType);
  12519. }
  12520. else if (NumNegativeBits) {
  12521. // If there is a negative value, figure out the smallest integer type (of
  12522. // int/long/longlong) that fits.
  12523. // If it's packed, check also if it fits a char or a short.
  12524. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  12525. BestType = Context.SignedCharTy;
  12526. BestWidth = CharWidth;
  12527. } else if (Packed && NumNegativeBits <= ShortWidth &&
  12528. NumPositiveBits < ShortWidth) {
  12529. BestType = Context.ShortTy;
  12530. BestWidth = ShortWidth;
  12531. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  12532. BestType = Context.IntTy;
  12533. BestWidth = IntWidth;
  12534. } else {
  12535. BestWidth = Context.getTargetInfo().getLongWidth();
  12536. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  12537. BestType = Context.LongTy;
  12538. } else {
  12539. BestWidth = Context.getTargetInfo().getLongLongWidth();
  12540. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  12541. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  12542. BestType = Context.LongLongTy;
  12543. }
  12544. }
  12545. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  12546. } else {
  12547. // If there is no negative value, figure out the smallest type that fits
  12548. // all of the enumerator values.
  12549. // If it's packed, check also if it fits a char or a short.
  12550. if (Packed && NumPositiveBits <= CharWidth) {
  12551. BestType = Context.UnsignedCharTy;
  12552. BestPromotionType = Context.IntTy;
  12553. BestWidth = CharWidth;
  12554. } else if (Packed && NumPositiveBits <= ShortWidth) {
  12555. BestType = Context.UnsignedShortTy;
  12556. BestPromotionType = Context.IntTy;
  12557. BestWidth = ShortWidth;
  12558. } else if (NumPositiveBits <= IntWidth) {
  12559. BestType = Context.UnsignedIntTy;
  12560. BestWidth = IntWidth;
  12561. BestPromotionType
  12562. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12563. ? Context.UnsignedIntTy : Context.IntTy;
  12564. } else if (NumPositiveBits <=
  12565. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  12566. BestType = Context.UnsignedLongTy;
  12567. BestPromotionType
  12568. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12569. ? Context.UnsignedLongTy : Context.LongTy;
  12570. } else {
  12571. BestWidth = Context.getTargetInfo().getLongLongWidth();
  12572. assert(NumPositiveBits <= BestWidth &&
  12573. "How could an initializer get larger than ULL?");
  12574. BestType = Context.UnsignedLongLongTy;
  12575. BestPromotionType
  12576. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12577. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  12578. }
  12579. }
  12580. FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
  12581. if (FEAttr)
  12582. FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
  12583. // Loop over all of the enumerator constants, changing their types to match
  12584. // the type of the enum if needed. If we have a flag type, we also prepare the
  12585. // FlagBits cache.
  12586. for (auto *D : Elements) {
  12587. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  12588. if (!ECD) continue; // Already issued a diagnostic.
  12589. // Standard C says the enumerators have int type, but we allow, as an
  12590. // extension, the enumerators to be larger than int size. If each
  12591. // enumerator value fits in an int, type it as an int, otherwise type it the
  12592. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  12593. // that X has type 'int', not 'unsigned'.
  12594. // Determine whether the value fits into an int.
  12595. llvm::APSInt InitVal = ECD->getInitVal();
  12596. // If it fits into an integer type, force it. Otherwise force it to match
  12597. // the enum decl type.
  12598. QualType NewTy;
  12599. unsigned NewWidth;
  12600. bool NewSign;
  12601. if (!getLangOpts().CPlusPlus &&
  12602. !Enum->isFixed() &&
  12603. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  12604. NewTy = Context.IntTy;
  12605. NewWidth = IntWidth;
  12606. NewSign = true;
  12607. } else if (ECD->getType() == BestType) {
  12608. // Already the right type!
  12609. if (getLangOpts().CPlusPlus)
  12610. // C++ [dcl.enum]p4: Following the closing brace of an
  12611. // enum-specifier, each enumerator has the type of its
  12612. // enumeration.
  12613. ECD->setType(EnumType);
  12614. goto flagbits;
  12615. } else {
  12616. NewTy = BestType;
  12617. NewWidth = BestWidth;
  12618. NewSign = BestType->isSignedIntegerOrEnumerationType();
  12619. }
  12620. // Adjust the APSInt value.
  12621. InitVal = InitVal.extOrTrunc(NewWidth);
  12622. InitVal.setIsSigned(NewSign);
  12623. ECD->setInitVal(InitVal);
  12624. // Adjust the Expr initializer and type.
  12625. if (ECD->getInitExpr() &&
  12626. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  12627. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  12628. CK_IntegralCast,
  12629. ECD->getInitExpr(),
  12630. /*base paths*/ nullptr,
  12631. VK_RValue));
  12632. if (getLangOpts().CPlusPlus)
  12633. // C++ [dcl.enum]p4: Following the closing brace of an
  12634. // enum-specifier, each enumerator has the type of its
  12635. // enumeration.
  12636. ECD->setType(EnumType);
  12637. else
  12638. ECD->setType(NewTy);
  12639. flagbits:
  12640. // Check to see if we have a constant with exactly one bit set. Note that x
  12641. // & (x - 1) will be nonzero if and only if x has more than one bit set.
  12642. if (FEAttr) {
  12643. llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
  12644. if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
  12645. FEAttr->getFlagBits() |= ExtVal;
  12646. }
  12647. }
  12648. }
  12649. if (FEAttr) {
  12650. for (Decl *D : Elements) {
  12651. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  12652. if (!ECD) continue; // Already issued a diagnostic.
  12653. llvm::APSInt InitVal = ECD->getInitVal();
  12654. if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
  12655. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  12656. << ECD << Enum;
  12657. }
  12658. }
  12659. Enum->completeDefinition(BestType, BestPromotionType,
  12660. NumPositiveBits, NumNegativeBits);
  12661. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  12662. // Now that the enum type is defined, ensure it's not been underaligned.
  12663. if (Enum->hasAttrs())
  12664. CheckAlignasUnderalignment(Enum);
  12665. }
  12666. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  12667. SourceLocation StartLoc,
  12668. SourceLocation EndLoc) {
  12669. #if 1 // HLSL Change
  12670. llvm_unreachable("HLSL parser does not produce file scope asm decl");
  12671. #else
  12672. StringLiteral *AsmString = cast<StringLiteral>(expr);
  12673. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  12674. AsmString, StartLoc,
  12675. EndLoc);
  12676. CurContext->addDecl(New);
  12677. return New;
  12678. #endif // HLSL Change
  12679. }
  12680. static void checkModuleImportContext(Sema &S, Module *M,
  12681. SourceLocation ImportLoc,
  12682. DeclContext *DC) {
  12683. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  12684. switch (LSD->getLanguage()) {
  12685. case LinkageSpecDecl::lang_c:
  12686. if (!M->IsExternC) {
  12687. S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
  12688. << M->getFullModuleName();
  12689. S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
  12690. return;
  12691. }
  12692. break;
  12693. case LinkageSpecDecl::lang_cxx:
  12694. break;
  12695. }
  12696. DC = LSD->getParent();
  12697. }
  12698. while (isa<LinkageSpecDecl>(DC))
  12699. DC = DC->getParent();
  12700. if (!isa<TranslationUnitDecl>(DC)) {
  12701. S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
  12702. << M->getFullModuleName() << DC;
  12703. S.Diag(cast<Decl>(DC)->getLocStart(),
  12704. diag::note_module_import_not_at_top_level)
  12705. << DC;
  12706. }
  12707. }
  12708. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  12709. SourceLocation ImportLoc,
  12710. ModuleIdPath Path) {
  12711. Module *Mod =
  12712. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  12713. /*IsIncludeDirective=*/false);
  12714. if (!Mod)
  12715. return true;
  12716. VisibleModules.setVisible(Mod, ImportLoc);
  12717. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  12718. // FIXME: we should support importing a submodule within a different submodule
  12719. // of the same top-level module. Until we do, make it an error rather than
  12720. // silently ignoring the import.
  12721. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
  12722. Diag(ImportLoc, diag::err_module_self_import)
  12723. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  12724. else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
  12725. Diag(ImportLoc, diag::err_module_import_in_implementation)
  12726. << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
  12727. SmallVector<SourceLocation, 2> IdentifierLocs;
  12728. Module *ModCheck = Mod;
  12729. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  12730. // If we've run out of module parents, just drop the remaining identifiers.
  12731. // We need the length to be consistent.
  12732. if (!ModCheck)
  12733. break;
  12734. ModCheck = ModCheck->Parent;
  12735. IdentifierLocs.push_back(Path[I].second);
  12736. }
  12737. ImportDecl *Import = ImportDecl::Create(Context,
  12738. Context.getTranslationUnitDecl(),
  12739. AtLoc.isValid()? AtLoc : ImportLoc,
  12740. Mod, IdentifierLocs);
  12741. Context.getTranslationUnitDecl()->addDecl(Import);
  12742. return Import;
  12743. }
  12744. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  12745. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12746. // Determine whether we're in the #include buffer for a module. The #includes
  12747. // in that buffer do not qualify as module imports; they're just an
  12748. // implementation detail of us building the module.
  12749. //
  12750. // FIXME: Should we even get ActOnModuleInclude calls for those?
  12751. bool IsInModuleIncludes =
  12752. TUKind == TU_Module &&
  12753. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  12754. // If this module import was due to an inclusion directive, create an
  12755. // implicit import declaration to capture it in the AST.
  12756. if (!IsInModuleIncludes) {
  12757. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  12758. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  12759. DirectiveLoc, Mod,
  12760. DirectiveLoc);
  12761. TU->addDecl(ImportD);
  12762. Consumer.HandleImplicitImportDecl(ImportD);
  12763. }
  12764. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  12765. VisibleModules.setVisible(Mod, DirectiveLoc);
  12766. }
  12767. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  12768. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12769. if (getLangOpts().ModulesLocalVisibility)
  12770. VisibleModulesStack.push_back(std::move(VisibleModules));
  12771. VisibleModules.setVisible(Mod, DirectiveLoc);
  12772. }
  12773. void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
  12774. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12775. if (getLangOpts().ModulesLocalVisibility) {
  12776. VisibleModules = std::move(VisibleModulesStack.back());
  12777. VisibleModulesStack.pop_back();
  12778. VisibleModules.setVisible(Mod, DirectiveLoc);
  12779. }
  12780. }
  12781. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  12782. Module *Mod) {
  12783. // Bail if we're not allowed to implicitly import a module here.
  12784. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
  12785. return;
  12786. // Create the implicit import declaration.
  12787. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  12788. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  12789. Loc, Mod, Loc);
  12790. TU->addDecl(ImportD);
  12791. Consumer.HandleImplicitImportDecl(ImportD);
  12792. // Make the module visible.
  12793. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  12794. VisibleModules.setVisible(Mod, Loc);
  12795. }
  12796. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  12797. IdentifierInfo* AliasName,
  12798. SourceLocation PragmaLoc,
  12799. SourceLocation NameLoc,
  12800. SourceLocation AliasNameLoc) {
  12801. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  12802. LookupOrdinaryName);
  12803. AsmLabelAttr *Attr =
  12804. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  12805. // If a declaration that:
  12806. // 1) declares a function or a variable
  12807. // 2) has external linkage
  12808. // already exists, add a label attribute to it.
  12809. if (PrevDecl &&
  12810. (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)) &&
  12811. PrevDecl->hasExternalFormalLinkage())
  12812. PrevDecl->addAttr(Attr);
  12813. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  12814. else
  12815. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  12816. }
  12817. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  12818. SourceLocation PragmaLoc,
  12819. SourceLocation NameLoc) {
  12820. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  12821. if (PrevDecl) {
  12822. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  12823. } else {
  12824. (void)WeakUndeclaredIdentifiers.insert(
  12825. std::pair<IdentifierInfo*,WeakInfo>
  12826. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  12827. }
  12828. }
  12829. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  12830. IdentifierInfo* AliasName,
  12831. SourceLocation PragmaLoc,
  12832. SourceLocation NameLoc,
  12833. SourceLocation AliasNameLoc) {
  12834. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  12835. LookupOrdinaryName);
  12836. WeakInfo W = WeakInfo(Name, NameLoc);
  12837. if (PrevDecl) {
  12838. if (!PrevDecl->hasAttr<AliasAttr>())
  12839. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  12840. DeclApplyPragmaWeak(TUScope, ND, W);
  12841. } else {
  12842. (void)WeakUndeclaredIdentifiers.insert(
  12843. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  12844. }
  12845. }
  12846. Decl *Sema::getObjCDeclContext() const {
  12847. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  12848. }
  12849. AvailabilityResult Sema::getCurContextAvailability() const {
  12850. const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
  12851. if (!D)
  12852. return AR_Available;
  12853. // If we are within an Objective-C method, we should consult
  12854. // both the availability of the method as well as the
  12855. // enclosing class. If the class is (say) deprecated,
  12856. // the entire method is considered deprecated from the
  12857. // purpose of checking if the current context is deprecated.
  12858. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  12859. AvailabilityResult R = MD->getAvailability();
  12860. if (R != AR_Available)
  12861. return R;
  12862. D = MD->getClassInterface();
  12863. }
  12864. // If we are within an Objective-c @implementation, it
  12865. // gets the same availability context as the @interface.
  12866. else if (const ObjCImplementationDecl *ID =
  12867. dyn_cast<ObjCImplementationDecl>(D)) {
  12868. D = ID->getClassInterface();
  12869. }
  12870. // Recover from user error.
  12871. return D ? D->getAvailability() : AR_Available;
  12872. }