SemaDecl.cpp 562 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608
  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. #else
  2646. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2647. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2648. // The old declaration provided a function prototype, but the
  2649. // new declaration does not. Merge in the prototype.
  2650. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2651. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  2652. NewQType =
  2653. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  2654. OldProto->getExtProtoInfo());
  2655. New->setType(NewQType);
  2656. New->setHasInheritedPrototype();
  2657. // Synthesize parameters with the same types.
  2658. SmallVector<ParmVarDecl*, 16> Params;
  2659. for (const auto &ParamType : OldProto->param_types()) {
  2660. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  2661. SourceLocation(), nullptr,
  2662. ParamType, /*TInfo=*/nullptr,
  2663. SC_None, nullptr);
  2664. Param->setScopeInfo(0, Params.size());
  2665. Param->setImplicit();
  2666. Params.push_back(Param);
  2667. }
  2668. New->setParams(Params);
  2669. }
  2670. #endif // HLSL Change Ends
  2671. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2672. }
  2673. #if 0 // HLSL Change Starts - commenting this out rather than fixing for inout semantics - N/A for HLSL
  2674. // GNU C permits a K&R definition to follow a prototype declaration
  2675. // if the declared types of the parameters in the K&R definition
  2676. // match the types in the prototype declaration, even when the
  2677. // promoted types of the parameters from the K&R definition differ
  2678. // from the types in the prototype. GCC then keeps the types from
  2679. // the prototype.
  2680. //
  2681. // If a variadic prototype is followed by a non-variadic K&R definition,
  2682. // the K&R definition becomes variadic. This is sort of an edge case, but
  2683. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2684. // C99 6.9.1p8.
  2685. if (!getLangOpts().CPlusPlus &&
  2686. Old->hasPrototype() && !New->hasPrototype() &&
  2687. New->getType()->getAs<FunctionProtoType>() &&
  2688. Old->getNumParams() == New->getNumParams()) {
  2689. SmallVector<QualType, 16> ArgTypes;
  2690. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2691. const FunctionProtoType *OldProto
  2692. = Old->getType()->getAs<FunctionProtoType>();
  2693. const FunctionProtoType *NewProto
  2694. = New->getType()->getAs<FunctionProtoType>();
  2695. // Determine whether this is the GNU C extension.
  2696. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  2697. NewProto->getReturnType());
  2698. bool LooseCompatible = !MergedReturn.isNull();
  2699. for (unsigned Idx = 0, End = Old->getNumParams();
  2700. LooseCompatible && Idx != End; ++Idx) {
  2701. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2702. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2703. if (Context.typesAreCompatible(OldParm->getType(),
  2704. NewProto->getParamType(Idx))) {
  2705. ArgTypes.push_back(NewParm->getType());
  2706. } else if (Context.typesAreCompatible(OldParm->getType(),
  2707. NewParm->getType(),
  2708. /*CompareUnqualified=*/true)) {
  2709. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  2710. NewProto->getParamType(Idx) };
  2711. Warnings.push_back(Warn);
  2712. ArgTypes.push_back(NewParm->getType());
  2713. } else
  2714. LooseCompatible = false;
  2715. }
  2716. if (LooseCompatible) {
  2717. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2718. Diag(Warnings[Warn].NewParm->getLocation(),
  2719. diag::ext_param_promoted_not_compatible_with_prototype)
  2720. << Warnings[Warn].PromotedType
  2721. << Warnings[Warn].OldParm->getType();
  2722. if (Warnings[Warn].OldParm->getLocation().isValid())
  2723. Diag(Warnings[Warn].OldParm->getLocation(),
  2724. diag::note_previous_declaration);
  2725. }
  2726. if (MergeTypeWithOld)
  2727. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  2728. OldProto->getExtProtoInfo()));
  2729. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2730. }
  2731. // Fall through to diagnose conflicting types.
  2732. }
  2733. #endif // HLSL Change Ends
  2734. // A function that has already been declared has been redeclared or
  2735. // defined with a different type; show an appropriate diagnostic.
  2736. // If the previous declaration was an implicitly-generated builtin
  2737. // declaration, then at the very least we should use a specialized note.
  2738. unsigned BuiltinID;
  2739. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  2740. // If it's actually a library-defined builtin function like 'malloc'
  2741. // or 'printf', just warn about the incompatible redeclaration.
  2742. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2743. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2744. Diag(OldLocation, diag::note_previous_builtin_declaration)
  2745. << Old << Old->getType();
  2746. // If this is a global redeclaration, just forget hereafter
  2747. // about the "builtin-ness" of the function.
  2748. //
  2749. // Doing this for local extern declarations is problematic. If
  2750. // the builtin declaration remains visible, a second invalid
  2751. // local declaration will produce a hard error; if it doesn't
  2752. // remain visible, a single bogus local redeclaration (which is
  2753. // actually only a warning) could break all the downstream code.
  2754. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  2755. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  2756. return false;
  2757. }
  2758. PrevDiag = diag::note_previous_builtin_declaration;
  2759. }
  2760. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2761. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2762. return true;
  2763. }
  2764. /// \brief Completes the merge of two function declarations that are
  2765. /// known to be compatible.
  2766. ///
  2767. /// This routine handles the merging of attributes and other
  2768. /// properties of function declarations from the old declaration to
  2769. /// the new declaration, once we know that New is in fact a
  2770. /// redeclaration of Old.
  2771. ///
  2772. /// \returns false
  2773. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2774. Scope *S, bool MergeTypeWithOld) {
  2775. // Merge the attributes
  2776. mergeDeclAttributes(New, Old);
  2777. // Merge "pure" flag.
  2778. if (Old->isPure())
  2779. New->setPure();
  2780. // Merge "used" flag.
  2781. if (Old->getMostRecentDecl()->isUsed(false))
  2782. New->setIsUsed();
  2783. // Merge attributes from the parameters. These can mismatch with K&R
  2784. // declarations.
  2785. if (New->getNumParams() == Old->getNumParams())
  2786. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  2787. ParmVarDecl *NewParam = New->getParamDecl(i);
  2788. ParmVarDecl *OldParam = Old->getParamDecl(i);
  2789. mergeParamDeclAttributes(NewParam, OldParam, *this);
  2790. mergeParamDeclTypes(NewParam, OldParam, *this);
  2791. }
  2792. if (getLangOpts().CPlusPlus)
  2793. return MergeCXXFunctionDecl(New, Old, S);
  2794. // Merge the function types so the we get the composite types for the return
  2795. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  2796. // was visible.
  2797. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  2798. if (!Merged.isNull() && MergeTypeWithOld)
  2799. New->setType(Merged);
  2800. return false;
  2801. }
  2802. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2803. ObjCMethodDecl *oldMethod) {
  2804. // Merge the attributes, including deprecated/unavailable
  2805. AvailabilityMergeKind MergeKind =
  2806. isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  2807. : AMK_Override;
  2808. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  2809. // Merge attributes from the parameters.
  2810. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2811. oe = oldMethod->param_end();
  2812. for (ObjCMethodDecl::param_iterator
  2813. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2814. ni != ne && oi != oe; ++ni, ++oi)
  2815. mergeParamDeclAttributes(*ni, *oi, *this);
  2816. CheckObjCMethodOverride(newMethod, oldMethod);
  2817. }
  2818. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2819. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2820. /// emitting diagnostics as appropriate.
  2821. ///
  2822. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2823. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2824. /// is attached.
  2825. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  2826. bool MergeTypeWithOld, ShadowMergeState& MergeState) { // HLSL Change - add merge state
  2827. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2828. return;
  2829. QualType MergedT;
  2830. if (getLangOpts().CPlusPlus) {
  2831. if (New->getType()->isUndeducedType()) {
  2832. // We don't know what the new type is until the initializer is attached.
  2833. return;
  2834. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2835. // These could still be something that needs exception specs checked.
  2836. return MergeVarDeclExceptionSpecs(New, Old);
  2837. }
  2838. // C++ [basic.link]p10:
  2839. // [...] the types specified by all declarations referring to a given
  2840. // object or function shall be identical, except that declarations for an
  2841. // array object can specify array types that differ by the presence or
  2842. // absence of a major array bound (8.3.4).
  2843. else if (Old->getType()->isIncompleteArrayType() &&
  2844. New->getType()->isArrayType()) {
  2845. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2846. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2847. if (Context.hasSameType(OldArray->getElementType(),
  2848. NewArray->getElementType()))
  2849. MergedT = New->getType();
  2850. } else if (Old->getType()->isArrayType() &&
  2851. New->getType()->isIncompleteArrayType()) {
  2852. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2853. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2854. if (Context.hasSameType(OldArray->getElementType(),
  2855. NewArray->getElementType()))
  2856. MergedT = Old->getType();
  2857. } else if (New->getType()->isObjCObjectPointerType() &&
  2858. Old->getType()->isObjCObjectPointerType()) {
  2859. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  2860. Old->getType());
  2861. }
  2862. } else {
  2863. // C 6.2.7p2:
  2864. // All declarations that refer to the same object or function shall have
  2865. // compatible type.
  2866. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  2867. }
  2868. if (MergedT.isNull()) {
  2869. // It's OK if we couldn't merge types if either type is dependent, for a
  2870. // block-scope variable. In other cases (static data members of class
  2871. // templates, variable templates, ...), we require the types to be
  2872. // equivalent.
  2873. // FIXME: The C++ standard doesn't say anything about this.
  2874. if ((New->getType()->isDependentType() ||
  2875. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  2876. // If the old type was dependent, we can't merge with it, so the new type
  2877. // becomes dependent for now. We'll reproduce the original type when we
  2878. // instantiate the TypeSourceInfo for the variable.
  2879. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  2880. New->setType(Context.DependentTy);
  2881. return;
  2882. }
  2883. // FIXME: Even if this merging succeeds, some other non-visible declaration
  2884. // of this variable might have an incompatible type. For instance:
  2885. //
  2886. // extern int arr[];
  2887. // void f() { extern int arr[2]; }
  2888. // void g() { extern int arr[3]; }
  2889. //
  2890. // Neither C nor C++ requires a diagnostic for this, but we should still try
  2891. // to diagnose it.
  2892. // HLSL Change Starts
  2893. if (MergeState == ShadowMergeState_Disallowed) {
  2894. Diag(New->getLocation(), New->isThisDeclarationADefinition()
  2895. ? diag::err_redefinition_different_type
  2896. : diag::err_redeclaration_different_type)
  2897. << New->getDeclName() << New->getType() << Old->getType();
  2898. diag::kind PrevDiag;
  2899. SourceLocation OldLocation;
  2900. std::tie(PrevDiag, OldLocation) =
  2901. getNoteDiagForInvalidRedeclaration(Old, New);
  2902. Diag(OldLocation, PrevDiag);
  2903. return New->setInvalidDecl();
  2904. }
  2905. else if (MergeState == ShadowMergeState_Possible) {
  2906. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition_different_type)
  2907. << New->getDeclName() << New->getType() << Old->getType();
  2908. Diag(Old->getLocation(), diag::note_previous_definition);
  2909. MergeState = ShadowMergeState_Effective;
  2910. MergeTypeWithOld = false;
  2911. }
  2912. // HLSL Change Ends
  2913. }
  2914. // Don't actually update the type on the new declaration if the old
  2915. // declaration was an extern declaration in a different scope.
  2916. if (MergeTypeWithOld)
  2917. New->setType(MergedT);
  2918. }
  2919. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  2920. LookupResult &Previous) {
  2921. // C11 6.2.7p4:
  2922. // For an identifier with internal or external linkage declared
  2923. // in a scope in which a prior declaration of that identifier is
  2924. // visible, if the prior declaration specifies internal or
  2925. // external linkage, the type of the identifier at the later
  2926. // declaration becomes the composite type.
  2927. //
  2928. // If the variable isn't visible, we do not merge with its type.
  2929. if (Previous.isShadowed())
  2930. return false;
  2931. if (S.getLangOpts().CPlusPlus) {
  2932. // C++11 [dcl.array]p3:
  2933. // If there is a preceding declaration of the entity in the same
  2934. // scope in which the bound was specified, an omitted array bound
  2935. // is taken to be the same as in that earlier declaration.
  2936. return NewVD->isPreviousDeclInSameBlockScope() ||
  2937. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  2938. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  2939. } else {
  2940. // If the old declaration was function-local, don't merge with its
  2941. // type unless we're in the same function.
  2942. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  2943. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  2944. }
  2945. }
  2946. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  2947. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  2948. /// situation, merging decls or emitting diagnostics as appropriate.
  2949. ///
  2950. /// Tentative definition rules (C99 6.9.2p2) are checked by
  2951. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  2952. /// definitions here, since the initializer hasn't been attached.
  2953. ///
  2954. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous, ShadowMergeState& MergeState) { // HLSL Change - add merge state
  2955. // If the new decl is already invalid, don't do any other checking.
  2956. if (New->isInvalidDecl())
  2957. return;
  2958. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  2959. // Verify the old decl was also a variable or variable template.
  2960. VarDecl *Old = nullptr;
  2961. VarTemplateDecl *OldTemplate = nullptr;
  2962. if (Previous.isSingleResult()) {
  2963. if (NewTemplate) {
  2964. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  2965. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  2966. if (auto *Shadow =
  2967. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  2968. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  2969. return New->setInvalidDecl();
  2970. } else {
  2971. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  2972. if (auto *Shadow =
  2973. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  2974. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  2975. return New->setInvalidDecl();
  2976. }
  2977. }
  2978. if (!Old) {
  2979. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2980. << New->getDeclName();
  2981. Diag(Previous.getRepresentativeDecl()->getLocation(),
  2982. diag::note_previous_definition);
  2983. return New->setInvalidDecl();
  2984. }
  2985. if (!shouldLinkPossiblyHiddenDecl(Old, New))
  2986. return;
  2987. // Ensure the template parameters are compatible.
  2988. if (NewTemplate &&
  2989. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  2990. OldTemplate->getTemplateParameters(),
  2991. /*Complain=*/true, TPL_TemplateMatch))
  2992. return;
  2993. // C++ [class.mem]p1:
  2994. // A member shall not be declared twice in the member-specification [...]
  2995. //
  2996. // Here, we need only consider static data members.
  2997. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  2998. Diag(New->getLocation(), diag::err_duplicate_member)
  2999. << New->getIdentifier();
  3000. Diag(Old->getLocation(), diag::note_previous_declaration);
  3001. New->setInvalidDecl();
  3002. }
  3003. mergeDeclAttributes(New, Old);
  3004. // Warn if an already-declared variable is made a weak_import in a subsequent
  3005. // declaration
  3006. if (New->hasAttr<WeakImportAttr>() &&
  3007. Old->getStorageClass() == SC_None &&
  3008. !Old->hasAttr<WeakImportAttr>()) {
  3009. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3010. Diag(Old->getLocation(), diag::note_previous_definition);
  3011. // Remove weak_import attribute on new declaration.
  3012. New->dropAttr<WeakImportAttr>();
  3013. }
  3014. // Merge the types.
  3015. VarDecl *MostRecent = Old->getMostRecentDecl();
  3016. if (MostRecent != Old) {
  3017. MergeVarDeclTypes(New, MostRecent,
  3018. mergeTypeWithPrevious(*this, New, MostRecent, Previous), MergeState); // HLSL Change - add MergeState
  3019. if (New->isInvalidDecl())
  3020. return;
  3021. }
  3022. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous), MergeState); // HLSL Change - add MergeState
  3023. if (New->isInvalidDecl())
  3024. return;
  3025. diag::kind PrevDiag;
  3026. SourceLocation OldLocation;
  3027. std::tie(PrevDiag, OldLocation) =
  3028. getNoteDiagForInvalidRedeclaration(Old, New);
  3029. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3030. if (New->getStorageClass() == SC_Static &&
  3031. !New->isStaticDataMember() &&
  3032. Old->hasExternalFormalLinkage()) {
  3033. if (getLangOpts().MicrosoftExt) {
  3034. Diag(New->getLocation(), diag::ext_static_non_static)
  3035. << New->getDeclName();
  3036. Diag(OldLocation, PrevDiag);
  3037. } else {
  3038. Diag(New->getLocation(), diag::err_static_non_static)
  3039. << New->getDeclName();
  3040. Diag(OldLocation, PrevDiag);
  3041. return New->setInvalidDecl();
  3042. }
  3043. }
  3044. // C99 6.2.2p4:
  3045. // For an identifier declared with the storage-class specifier
  3046. // extern in a scope in which a prior declaration of that
  3047. // identifier is visible,23) if the prior declaration specifies
  3048. // internal or external linkage, the linkage of the identifier at
  3049. // the later declaration is the same as the linkage specified at
  3050. // the prior declaration. If no prior declaration is visible, or
  3051. // if the prior declaration specifies no linkage, then the
  3052. // identifier has external linkage.
  3053. if (New->hasExternalStorage() && Old->hasLinkage())
  3054. /* Okay */;
  3055. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3056. !New->isStaticDataMember() &&
  3057. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3058. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3059. Diag(OldLocation, PrevDiag);
  3060. return New->setInvalidDecl();
  3061. }
  3062. // Check if extern is followed by non-extern and vice-versa.
  3063. if (New->hasExternalStorage() &&
  3064. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3065. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3066. Diag(OldLocation, PrevDiag);
  3067. return New->setInvalidDecl();
  3068. }
  3069. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3070. !New->hasExternalStorage()) {
  3071. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3072. Diag(OldLocation, PrevDiag);
  3073. return New->setInvalidDecl();
  3074. }
  3075. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3076. // FIXME: The test for external storage here seems wrong? We still
  3077. // need to check for mismatches.
  3078. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3079. // Don't complain about out-of-line definitions of static members.
  3080. !(Old->getLexicalDeclContext()->isRecord() &&
  3081. !New->getLexicalDeclContext()->isRecord())) {
  3082. // HLSL Change Starts
  3083. if (MergeState == ShadowMergeState_Disallowed) {
  3084. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3085. Diag(OldLocation, PrevDiag);
  3086. return New->setInvalidDecl();
  3087. } else if (MergeState == ShadowMergeState_Possible) {
  3088. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition)
  3089. << New->getDeclName();
  3090. Diag(Old->getLocation(), diag::note_previous_definition);
  3091. MergeState = ShadowMergeState_Effective;
  3092. }
  3093. // HLSL Change Ends
  3094. }
  3095. if (New->getTLSKind() != Old->getTLSKind()) {
  3096. if (!Old->getTLSKind()) {
  3097. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3098. Diag(OldLocation, PrevDiag);
  3099. } else if (!New->getTLSKind()) {
  3100. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3101. Diag(OldLocation, PrevDiag);
  3102. } else {
  3103. // Do not allow redeclaration to change the variable between requiring
  3104. // static and dynamic initialization.
  3105. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3106. // declaration to determine the kind. Do we need to be compatible here?
  3107. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3108. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3109. Diag(OldLocation, PrevDiag);
  3110. }
  3111. }
  3112. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3113. VarDecl *Def;
  3114. if (getLangOpts().CPlusPlus &&
  3115. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  3116. (Def = Old->getDefinition())) {
  3117. NamedDecl *Hidden = nullptr;
  3118. if (!hasVisibleDefinition(Def, &Hidden) &&
  3119. (New->getFormalLinkage() == InternalLinkage ||
  3120. New->getDescribedVarTemplate() ||
  3121. New->getNumTemplateParameterLists() ||
  3122. New->getDeclContext()->isDependentContext())) {
  3123. // The previous definition is hidden, and multiple definitions are
  3124. // permitted (in separate TUs). Form another definition of it.
  3125. } else {
  3126. // HLSL Change Starts
  3127. if (MergeState == ShadowMergeState_Disallowed) {
  3128. Diag(New->getLocation(), diag::err_redefinition) << New;
  3129. Diag(Def->getLocation(), diag::note_previous_definition);
  3130. New->setInvalidDecl();
  3131. return;
  3132. }
  3133. else if (MergeState == ShadowMergeState_Possible) {
  3134. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition) << New->getDeclName();
  3135. Diag(Old->getLocation(), diag::note_previous_definition);
  3136. MergeState = ShadowMergeState_Effective;
  3137. }
  3138. // HLSL Change Ends
  3139. }
  3140. }
  3141. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3142. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3143. Diag(OldLocation, PrevDiag);
  3144. New->setInvalidDecl();
  3145. return;
  3146. }
  3147. if (MergeState != ShadowMergeState_Effective) { // HLSL Change - avoid merging when shadowing
  3148. // Merge "used" flag.
  3149. if (Old->getMostRecentDecl()->isUsed(false))
  3150. New->setIsUsed();
  3151. // Keep a chain of previous declarations.
  3152. New->setPreviousDecl(Old);
  3153. if (NewTemplate)
  3154. NewTemplate->setPreviousDecl(OldTemplate);
  3155. // Inherit access appropriately.
  3156. New->setAccess(Old->getAccess());
  3157. if (NewTemplate)
  3158. NewTemplate->setAccess(New->getAccess());
  3159. } // HLSL Change - close block conditional on shadow merge state
  3160. }
  3161. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3162. /// no declarator (e.g. "struct foo;") is parsed.
  3163. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  3164. DeclSpec &DS) {
  3165. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
  3166. }
  3167. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3168. // disambiguate entities defined in different scopes.
  3169. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3170. // compatibility.
  3171. // We will pick our mangling number depending on which version of MSVC is being
  3172. // targeted.
  3173. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3174. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3175. ? S->getMSCurManglingNumber()
  3176. : S->getMSLastManglingNumber();
  3177. }
  3178. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3179. if (!Context.getLangOpts().CPlusPlus)
  3180. return;
  3181. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3182. // If this tag is the direct child of a class, number it if
  3183. // it is anonymous.
  3184. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3185. return;
  3186. MangleNumberingContext &MCtx =
  3187. Context.getManglingNumberContext(Tag->getParent());
  3188. Context.setManglingNumber(
  3189. Tag, MCtx.getManglingNumber(
  3190. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3191. return;
  3192. }
  3193. // If this tag isn't a direct child of a class, number it if it is local.
  3194. Decl *ManglingContextDecl;
  3195. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3196. Tag->getDeclContext(), ManglingContextDecl)) {
  3197. Context.setManglingNumber(
  3198. Tag, MCtx->getManglingNumber(
  3199. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3200. }
  3201. }
  3202. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3203. TypedefNameDecl *NewTD) {
  3204. // Do nothing if the tag is not anonymous or already has an
  3205. // associated typedef (from an earlier typedef in this decl group).
  3206. if (TagFromDeclSpec->getIdentifier())
  3207. return;
  3208. if (TagFromDeclSpec->getTypedefNameForAnonDecl())
  3209. return;
  3210. // A well-formed anonymous tag must always be a TUK_Definition.
  3211. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3212. // The type must match the tag exactly; no qualifiers allowed.
  3213. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3214. Context.getTagDeclType(TagFromDeclSpec)))
  3215. return;
  3216. // If we've already computed linkage for the anonymous tag, then
  3217. // adding a typedef name for the anonymous decl can change that
  3218. // linkage, which might be a serious problem. Diagnose this as
  3219. // unsupported and ignore the typedef name. TODO: we should
  3220. // pursue this as a language defect and establish a formal rule
  3221. // for how to handle it.
  3222. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3223. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3224. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3225. tagLoc = getLocForEndOfToken(tagLoc);
  3226. llvm::SmallString<40> textToInsert;
  3227. textToInsert += ' ';
  3228. textToInsert += NewTD->getIdentifier()->getName();
  3229. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3230. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3231. return;
  3232. }
  3233. // Otherwise, set this is the anon-decl typedef for the tag.
  3234. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3235. }
  3236. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3237. switch (T) {
  3238. case DeclSpec::TST_class:
  3239. return 0;
  3240. case DeclSpec::TST_struct:
  3241. return 1;
  3242. case DeclSpec::TST_interface:
  3243. return 2;
  3244. case DeclSpec::TST_union:
  3245. return 3;
  3246. case DeclSpec::TST_enum:
  3247. return 4;
  3248. default:
  3249. llvm_unreachable("unexpected type specifier");
  3250. }
  3251. }
  3252. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3253. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3254. /// parameters to cope with template friend declarations.
  3255. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  3256. DeclSpec &DS,
  3257. MultiTemplateParamsArg TemplateParams,
  3258. bool IsExplicitInstantiation) {
  3259. Decl *TagD = nullptr;
  3260. TagDecl *Tag = nullptr;
  3261. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3262. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3263. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3264. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3265. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3266. TagD = DS.getRepAsDecl();
  3267. if (!TagD) // We probably had an error
  3268. return nullptr;
  3269. // Note that the above type specs guarantee that the
  3270. // type rep is a Decl, whereas in many of the others
  3271. // it's a Type.
  3272. if (isa<TagDecl>(TagD))
  3273. Tag = cast<TagDecl>(TagD);
  3274. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3275. Tag = CTD->getTemplatedDecl();
  3276. }
  3277. if (Tag) {
  3278. handleTagNumbering(Tag, S);
  3279. Tag->setFreeStanding();
  3280. if (Tag->isInvalidDecl())
  3281. return Tag;
  3282. }
  3283. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3284. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3285. // or incomplete types shall not be restrict-qualified."
  3286. if (TypeQuals & DeclSpec::TQ_restrict)
  3287. Diag(DS.getRestrictSpecLoc(),
  3288. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3289. << DS.getSourceRange();
  3290. }
  3291. if (DS.isConstexprSpecified()) {
  3292. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3293. // and definitions of functions and variables.
  3294. if (Tag)
  3295. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3296. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3297. else
  3298. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3299. // Don't emit warnings after this error.
  3300. return TagD;
  3301. }
  3302. DiagnoseFunctionSpecifiers(DS);
  3303. if (DS.isFriendSpecified()) {
  3304. // If we're dealing with a decl but not a TagDecl, assume that
  3305. // whatever routines created it handled the friendship aspect.
  3306. if (TagD && !Tag)
  3307. return nullptr;
  3308. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3309. }
  3310. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3311. bool IsExplicitSpecialization =
  3312. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3313. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3314. !IsExplicitInstantiation && !IsExplicitSpecialization) {
  3315. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3316. // nested-name-specifier unless it is an explicit instantiation
  3317. // or an explicit specialization.
  3318. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3319. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3320. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3321. return nullptr;
  3322. }
  3323. // Track whether this decl-specifier declares anything.
  3324. bool DeclaresAnything = true;
  3325. // Handle anonymous struct definitions.
  3326. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3327. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3328. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3329. if (getLangOpts().CPlusPlus ||
  3330. Record->getDeclContext()->isRecord())
  3331. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3332. Context.getPrintingPolicy());
  3333. DeclaresAnything = false;
  3334. }
  3335. }
  3336. // C11 6.7.2.1p2:
  3337. // A struct-declaration that does not declare an anonymous structure or
  3338. // anonymous union shall contain a struct-declarator-list.
  3339. //
  3340. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3341. // did not permit a struct-declaration without a struct-declarator-list.
  3342. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3343. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3344. // Check for Microsoft C extension: anonymous struct/union member.
  3345. // Handle 2 kinds of anonymous struct/union:
  3346. // struct STRUCT;
  3347. // union UNION;
  3348. // and
  3349. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3350. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3351. if ((Tag && Tag->getDeclName()) ||
  3352. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3353. RecordDecl *Record = nullptr;
  3354. if (Tag)
  3355. Record = dyn_cast<RecordDecl>(Tag);
  3356. else if (const RecordType *RT =
  3357. DS.getRepAsType().get()->getAsStructureType())
  3358. Record = RT->getDecl();
  3359. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3360. Record = UT->getDecl();
  3361. if (Record && getLangOpts().MicrosoftExt) {
  3362. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3363. << Record->isUnion() << DS.getSourceRange();
  3364. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3365. }
  3366. DeclaresAnything = false;
  3367. }
  3368. }
  3369. // Skip all the checks below if we have a type error.
  3370. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3371. (TagD && TagD->isInvalidDecl()))
  3372. return TagD;
  3373. if (getLangOpts().CPlusPlus &&
  3374. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3375. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3376. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3377. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3378. DeclaresAnything = false;
  3379. if (!DS.isMissingDeclaratorOk()) {
  3380. // Customize diagnostic for a typedef missing a name.
  3381. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3382. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3383. << DS.getSourceRange();
  3384. else
  3385. DeclaresAnything = false;
  3386. }
  3387. if (DS.isModulePrivateSpecified() &&
  3388. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3389. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3390. << Tag->getTagKind()
  3391. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3392. ActOnDocumentableDecl(TagD);
  3393. // C 6.7/2:
  3394. // A declaration [...] shall declare at least a declarator [...], a tag,
  3395. // or the members of an enumeration.
  3396. // C++ [dcl.dcl]p3:
  3397. // [If there are no declarators], and except for the declaration of an
  3398. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3399. // names into the program, or shall redeclare a name introduced by a
  3400. // previous declaration.
  3401. if (!DeclaresAnything) {
  3402. // In C, we allow this as a (popular) extension / bug. Don't bother
  3403. // producing further diagnostics for redundant qualifiers after this.
  3404. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3405. return TagD;
  3406. }
  3407. // C++ [dcl.stc]p1:
  3408. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3409. // init-declarator-list of the declaration shall not be empty.
  3410. // C++ [dcl.fct.spec]p1:
  3411. // If a cv-qualifier appears in a decl-specifier-seq, the
  3412. // init-declarator-list of the declaration shall not be empty.
  3413. //
  3414. // Spurious qualifiers here appear to be valid in C.
  3415. unsigned DiagID = diag::warn_standalone_specifier;
  3416. if (getLangOpts().CPlusPlus)
  3417. DiagID = diag::ext_standalone_specifier;
  3418. // Note that a linkage-specification sets a storage class, but
  3419. // 'extern "C" struct foo;' is actually valid and not theoretically
  3420. // useless.
  3421. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3422. if (SCS == DeclSpec::SCS_mutable)
  3423. // Since mutable is not a viable storage class specifier in C, there is
  3424. // no reason to treat it as an extension. Instead, diagnose as an error.
  3425. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3426. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3427. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3428. << DeclSpec::getSpecifierName(SCS);
  3429. }
  3430. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3431. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3432. << DeclSpec::getSpecifierName(TSCS);
  3433. if (DS.getTypeQualifiers()) {
  3434. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3435. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3436. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3437. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3438. // Restrict is covered above.
  3439. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3440. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3441. }
  3442. // Warn about ignored type attributes, for example:
  3443. // __attribute__((aligned)) struct A;
  3444. // Attributes should be placed after tag to apply to type declaration.
  3445. if (!DS.getAttributes().empty()) {
  3446. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3447. if (TypeSpecType == DeclSpec::TST_class ||
  3448. TypeSpecType == DeclSpec::TST_struct ||
  3449. TypeSpecType == DeclSpec::TST_interface ||
  3450. TypeSpecType == DeclSpec::TST_union ||
  3451. TypeSpecType == DeclSpec::TST_enum) {
  3452. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3453. attrs = attrs->getNext())
  3454. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3455. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3456. }
  3457. }
  3458. return TagD;
  3459. }
  3460. /// We are trying to inject an anonymous member into the given scope;
  3461. /// check if there's an existing declaration that can't be overloaded.
  3462. ///
  3463. /// \return true if this is a forbidden redeclaration
  3464. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3465. Scope *S,
  3466. DeclContext *Owner,
  3467. DeclarationName Name,
  3468. SourceLocation NameLoc,
  3469. unsigned diagnostic) {
  3470. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3471. Sema::ForRedeclaration);
  3472. if (!SemaRef.LookupName(R, S)) return false;
  3473. if (R.getAsSingle<TagDecl>())
  3474. return false;
  3475. // Pick a representative declaration.
  3476. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3477. assert(PrevDecl && "Expected a non-null Decl");
  3478. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3479. return false;
  3480. SemaRef.Diag(NameLoc, diagnostic) << Name;
  3481. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3482. return true;
  3483. }
  3484. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3485. /// anonymous struct or union AnonRecord into the owning context Owner
  3486. /// and scope S. This routine will be invoked just after we realize
  3487. /// that an unnamed union or struct is actually an anonymous union or
  3488. /// struct, e.g.,
  3489. ///
  3490. /// @code
  3491. /// union {
  3492. /// int i;
  3493. /// float f;
  3494. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3495. /// // f into the surrounding scope.x
  3496. /// @endcode
  3497. ///
  3498. /// This routine is recursive, injecting the names of nested anonymous
  3499. /// structs/unions into the owning context and scope as well.
  3500. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  3501. DeclContext *Owner,
  3502. RecordDecl *AnonRecord,
  3503. AccessSpecifier AS,
  3504. SmallVectorImpl<NamedDecl *> &Chaining,
  3505. bool MSAnonStruct) {
  3506. unsigned diagKind
  3507. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  3508. : diag::err_anonymous_struct_member_redecl;
  3509. bool Invalid = false;
  3510. // Look every FieldDecl and IndirectFieldDecl with a name.
  3511. for (auto *D : AnonRecord->decls()) {
  3512. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3513. cast<NamedDecl>(D)->getDeclName()) {
  3514. ValueDecl *VD = cast<ValueDecl>(D);
  3515. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3516. VD->getLocation(), diagKind)) {
  3517. // C++ [class.union]p2:
  3518. // The names of the members of an anonymous union shall be
  3519. // distinct from the names of any other entity in the
  3520. // scope in which the anonymous union is declared.
  3521. Invalid = true;
  3522. } else {
  3523. // C++ [class.union]p2:
  3524. // For the purpose of name lookup, after the anonymous union
  3525. // definition, the members of the anonymous union are
  3526. // considered to have been defined in the scope in which the
  3527. // anonymous union is declared.
  3528. unsigned OldChainingSize = Chaining.size();
  3529. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3530. Chaining.append(IF->chain_begin(), IF->chain_end());
  3531. else
  3532. Chaining.push_back(VD);
  3533. assert(Chaining.size() >= 2);
  3534. NamedDecl **NamedChain =
  3535. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3536. for (unsigned i = 0; i < Chaining.size(); i++)
  3537. NamedChain[i] = Chaining[i];
  3538. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  3539. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  3540. VD->getType(), NamedChain, Chaining.size());
  3541. for (const auto *Attr : VD->attrs())
  3542. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  3543. IndirectField->setAccess(AS);
  3544. IndirectField->setImplicit();
  3545. SemaRef.PushOnScopeChains(IndirectField, S);
  3546. // That includes picking up the appropriate access specifier.
  3547. if (AS != AS_none) IndirectField->setAccess(AS);
  3548. Chaining.resize(OldChainingSize);
  3549. }
  3550. }
  3551. }
  3552. return Invalid;
  3553. }
  3554. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  3555. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  3556. /// illegal input values are mapped to SC_None.
  3557. static StorageClass
  3558. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  3559. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  3560. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  3561. "Parser allowed 'typedef' as storage class VarDecl.");
  3562. switch (StorageClassSpec) {
  3563. case DeclSpec::SCS_unspecified: return SC_None;
  3564. case DeclSpec::SCS_extern:
  3565. if (DS.isExternInLinkageSpec())
  3566. return SC_None;
  3567. return SC_Extern;
  3568. case DeclSpec::SCS_static: return SC_Static;
  3569. case DeclSpec::SCS_auto: return SC_Auto;
  3570. case DeclSpec::SCS_register: return SC_Register;
  3571. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  3572. // Illegal SCSs map to None: error reporting is up to the caller.
  3573. case DeclSpec::SCS_mutable: // Fall through.
  3574. case DeclSpec::SCS_typedef: return SC_None;
  3575. }
  3576. llvm_unreachable("unknown storage class specifier");
  3577. }
  3578. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  3579. assert(Record->hasInClassInitializer());
  3580. for (const auto *I : Record->decls()) {
  3581. const auto *FD = dyn_cast<FieldDecl>(I);
  3582. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  3583. FD = IFD->getAnonField();
  3584. if (FD && FD->hasInClassInitializer())
  3585. return FD->getLocation();
  3586. }
  3587. llvm_unreachable("couldn't find in-class initializer");
  3588. }
  3589. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3590. SourceLocation DefaultInitLoc) {
  3591. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3592. return;
  3593. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  3594. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  3595. }
  3596. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3597. CXXRecordDecl *AnonUnion) {
  3598. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3599. return;
  3600. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  3601. }
  3602. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  3603. /// anonymous structure or union. Anonymous unions are a C++ feature
  3604. /// (C++ [class.union]) and a C11 feature; anonymous structures
  3605. /// are a C11 feature and GNU C++ extension.
  3606. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  3607. AccessSpecifier AS,
  3608. RecordDecl *Record,
  3609. const PrintingPolicy &Policy) {
  3610. DeclContext *Owner = Record->getDeclContext();
  3611. // Diagnose whether this anonymous struct/union is an extension.
  3612. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  3613. Diag(Record->getLocation(), diag::ext_anonymous_union);
  3614. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  3615. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  3616. else if (!Record->isUnion() && !getLangOpts().C11)
  3617. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  3618. // C and C++ require different kinds of checks for anonymous
  3619. // structs/unions.
  3620. bool Invalid = false;
  3621. if (getLangOpts().CPlusPlus) {
  3622. const char *PrevSpec = nullptr;
  3623. unsigned DiagID;
  3624. if (Record->isUnion()) {
  3625. // C++ [class.union]p6:
  3626. // Anonymous unions declared in a named namespace or in the
  3627. // global namespace shall be declared static.
  3628. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  3629. (isa<TranslationUnitDecl>(Owner) ||
  3630. (isa<NamespaceDecl>(Owner) &&
  3631. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  3632. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  3633. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  3634. // Recover by adding 'static'.
  3635. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  3636. PrevSpec, DiagID, Policy);
  3637. }
  3638. // C++ [class.union]p6:
  3639. // A storage class is not allowed in a declaration of an
  3640. // anonymous union in a class scope.
  3641. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  3642. isa<RecordDecl>(Owner)) {
  3643. Diag(DS.getStorageClassSpecLoc(),
  3644. diag::err_anonymous_union_with_storage_spec)
  3645. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  3646. // Recover by removing the storage specifier.
  3647. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  3648. SourceLocation(),
  3649. PrevSpec, DiagID, Context.getPrintingPolicy());
  3650. }
  3651. }
  3652. // Ignore const/volatile/restrict qualifiers.
  3653. if (DS.getTypeQualifiers()) {
  3654. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3655. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  3656. << Record->isUnion() << "const"
  3657. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  3658. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3659. Diag(DS.getVolatileSpecLoc(),
  3660. diag::ext_anonymous_struct_union_qualified)
  3661. << Record->isUnion() << "volatile"
  3662. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  3663. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  3664. Diag(DS.getRestrictSpecLoc(),
  3665. diag::ext_anonymous_struct_union_qualified)
  3666. << Record->isUnion() << "restrict"
  3667. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  3668. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3669. Diag(DS.getAtomicSpecLoc(),
  3670. diag::ext_anonymous_struct_union_qualified)
  3671. << Record->isUnion() << "_Atomic"
  3672. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  3673. DS.ClearTypeQualifiers();
  3674. }
  3675. // C++ [class.union]p2:
  3676. // The member-specification of an anonymous union shall only
  3677. // define non-static data members. [Note: nested types and
  3678. // functions cannot be declared within an anonymous union. ]
  3679. for (auto *Mem : Record->decls()) {
  3680. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  3681. // C++ [class.union]p3:
  3682. // An anonymous union shall not have private or protected
  3683. // members (clause 11).
  3684. assert(FD->getAccess() != AS_none);
  3685. if (FD->getAccess() != AS_public) {
  3686. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  3687. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  3688. Invalid = true;
  3689. }
  3690. // C++ [class.union]p1
  3691. // An object of a class with a non-trivial constructor, a non-trivial
  3692. // copy constructor, a non-trivial destructor, or a non-trivial copy
  3693. // assignment operator cannot be a member of a union, nor can an
  3694. // array of such objects.
  3695. if (CheckNontrivialField(FD))
  3696. Invalid = true;
  3697. } else if (Mem->isImplicit()) {
  3698. // Any implicit members are fine.
  3699. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  3700. // This is a type that showed up in an
  3701. // elaborated-type-specifier inside the anonymous struct or
  3702. // union, but which actually declares a type outside of the
  3703. // anonymous struct or union. It's okay.
  3704. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  3705. if (!MemRecord->isAnonymousStructOrUnion() &&
  3706. MemRecord->getDeclName()) {
  3707. // Visual C++ allows type definition in anonymous struct or union.
  3708. if (getLangOpts().MicrosoftExt)
  3709. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  3710. << (int)Record->isUnion();
  3711. else {
  3712. // This is a nested type declaration.
  3713. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  3714. << (int)Record->isUnion();
  3715. Invalid = true;
  3716. }
  3717. } else {
  3718. // This is an anonymous type definition within another anonymous type.
  3719. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  3720. // not part of standard C++.
  3721. Diag(MemRecord->getLocation(),
  3722. diag::ext_anonymous_record_with_anonymous_type)
  3723. << (int)Record->isUnion();
  3724. }
  3725. } else if (isa<AccessSpecDecl>(Mem)) {
  3726. // Any access specifier is fine.
  3727. } else if (isa<StaticAssertDecl>(Mem)) {
  3728. // In C++1z, static_assert declarations are also fine.
  3729. } else {
  3730. // We have something that isn't a non-static data
  3731. // member. Complain about it.
  3732. unsigned DK = diag::err_anonymous_record_bad_member;
  3733. if (isa<TypeDecl>(Mem))
  3734. DK = diag::err_anonymous_record_with_type;
  3735. else if (isa<FunctionDecl>(Mem))
  3736. DK = diag::err_anonymous_record_with_function;
  3737. else if (isa<VarDecl>(Mem))
  3738. DK = diag::err_anonymous_record_with_static;
  3739. // Visual C++ allows type definition in anonymous struct or union.
  3740. if (getLangOpts().MicrosoftExt &&
  3741. DK == diag::err_anonymous_record_with_type)
  3742. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  3743. << (int)Record->isUnion();
  3744. else {
  3745. Diag(Mem->getLocation(), DK)
  3746. << (int)Record->isUnion();
  3747. Invalid = true;
  3748. }
  3749. }
  3750. }
  3751. // C++11 [class.union]p8 (DR1460):
  3752. // At most one variant member of a union may have a
  3753. // brace-or-equal-initializer.
  3754. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  3755. Owner->isRecord())
  3756. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  3757. cast<CXXRecordDecl>(Record));
  3758. }
  3759. if (!Record->isUnion() && !Owner->isRecord()) {
  3760. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  3761. << (int)getLangOpts().CPlusPlus;
  3762. Invalid = true;
  3763. }
  3764. // Mock up a declarator.
  3765. Declarator Dc(DS, Declarator::MemberContext);
  3766. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3767. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  3768. // Create a declaration for this anonymous struct/union.
  3769. NamedDecl *Anon = nullptr;
  3770. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  3771. Anon = FieldDecl::Create(Context, OwningClass,
  3772. DS.getLocStart(),
  3773. Record->getLocation(),
  3774. /*IdentifierInfo=*/nullptr,
  3775. Context.getTypeDeclType(Record),
  3776. TInfo,
  3777. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3778. /*InitStyle=*/ICIS_NoInit);
  3779. Anon->setAccess(AS);
  3780. if (getLangOpts().CPlusPlus)
  3781. FieldCollector->Add(cast<FieldDecl>(Anon));
  3782. } else {
  3783. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  3784. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  3785. if (SCSpec == DeclSpec::SCS_mutable) {
  3786. // mutable can only appear on non-static class members, so it's always
  3787. // an error here
  3788. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  3789. Invalid = true;
  3790. SC = SC_None;
  3791. }
  3792. Anon = VarDecl::Create(Context, Owner,
  3793. DS.getLocStart(),
  3794. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  3795. Context.getTypeDeclType(Record),
  3796. TInfo, SC);
  3797. // Default-initialize the implicit variable. This initialization will be
  3798. // trivial in almost all cases, except if a union member has an in-class
  3799. // initializer:
  3800. // union { int n = 0; };
  3801. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  3802. }
  3803. Anon->setImplicit();
  3804. // Mark this as an anonymous struct/union type.
  3805. Record->setAnonymousStructOrUnion(true);
  3806. // Add the anonymous struct/union object to the current
  3807. // context. We'll be referencing this object when we refer to one of
  3808. // its members.
  3809. Owner->addDecl(Anon);
  3810. // Inject the members of the anonymous struct/union into the owning
  3811. // context and into the identifier resolver chain for name lookup
  3812. // purposes.
  3813. SmallVector<NamedDecl*, 2> Chain;
  3814. Chain.push_back(Anon);
  3815. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  3816. Chain, false))
  3817. Invalid = true;
  3818. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  3819. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  3820. Decl *ManglingContextDecl;
  3821. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3822. NewVD->getDeclContext(), ManglingContextDecl)) {
  3823. Context.setManglingNumber(
  3824. NewVD, MCtx->getManglingNumber(
  3825. NewVD, getMSManglingNumber(getLangOpts(), S)));
  3826. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  3827. }
  3828. }
  3829. }
  3830. if (Invalid)
  3831. Anon->setInvalidDecl();
  3832. return Anon;
  3833. }
  3834. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  3835. /// Microsoft C anonymous structure.
  3836. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  3837. /// Example:
  3838. ///
  3839. /// struct A { int a; };
  3840. /// struct B { struct A; int b; };
  3841. ///
  3842. /// void foo() {
  3843. /// B var;
  3844. /// var.a = 3;
  3845. /// }
  3846. ///
  3847. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  3848. RecordDecl *Record) {
  3849. assert(Record && "expected a record!");
  3850. // Mock up a declarator.
  3851. Declarator Dc(DS, Declarator::TypeNameContext);
  3852. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3853. assert(TInfo && "couldn't build declarator info for anonymous struct");
  3854. auto *ParentDecl = cast<RecordDecl>(CurContext);
  3855. QualType RecTy = Context.getTypeDeclType(Record);
  3856. // Create a declaration for this anonymous struct.
  3857. NamedDecl *Anon = FieldDecl::Create(Context,
  3858. ParentDecl,
  3859. DS.getLocStart(),
  3860. DS.getLocStart(),
  3861. /*IdentifierInfo=*/nullptr,
  3862. RecTy,
  3863. TInfo,
  3864. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3865. /*InitStyle=*/ICIS_NoInit);
  3866. Anon->setImplicit();
  3867. // Add the anonymous struct object to the current context.
  3868. CurContext->addDecl(Anon);
  3869. // Inject the members of the anonymous struct into the current
  3870. // context and into the identifier resolver chain for name lookup
  3871. // purposes.
  3872. SmallVector<NamedDecl*, 2> Chain;
  3873. Chain.push_back(Anon);
  3874. RecordDecl *RecordDef = Record->getDefinition();
  3875. if (RequireCompleteType(Anon->getLocation(), RecTy,
  3876. diag::err_field_incomplete) ||
  3877. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  3878. AS_none, Chain, true)) {
  3879. Anon->setInvalidDecl();
  3880. ParentDecl->setInvalidDecl();
  3881. }
  3882. return Anon;
  3883. }
  3884. /// GetNameForDeclarator - Determine the full declaration name for the
  3885. /// given Declarator.
  3886. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  3887. return GetNameFromUnqualifiedId(D.getName());
  3888. }
  3889. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  3890. DeclarationNameInfo
  3891. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  3892. DeclarationNameInfo NameInfo;
  3893. NameInfo.setLoc(Name.StartLocation);
  3894. switch (Name.getKind()) {
  3895. case UnqualifiedId::IK_ImplicitSelfParam:
  3896. case UnqualifiedId::IK_Identifier:
  3897. NameInfo.setName(Name.Identifier);
  3898. NameInfo.setLoc(Name.StartLocation);
  3899. return NameInfo;
  3900. case UnqualifiedId::IK_OperatorFunctionId:
  3901. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  3902. Name.OperatorFunctionId.Operator));
  3903. NameInfo.setLoc(Name.StartLocation);
  3904. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  3905. = Name.OperatorFunctionId.SymbolLocations[0];
  3906. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  3907. = Name.EndLocation.getRawEncoding();
  3908. return NameInfo;
  3909. case UnqualifiedId::IK_LiteralOperatorId:
  3910. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  3911. Name.Identifier));
  3912. NameInfo.setLoc(Name.StartLocation);
  3913. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  3914. return NameInfo;
  3915. case UnqualifiedId::IK_ConversionFunctionId: {
  3916. TypeSourceInfo *TInfo;
  3917. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  3918. if (Ty.isNull())
  3919. return DeclarationNameInfo();
  3920. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  3921. Context.getCanonicalType(Ty)));
  3922. NameInfo.setLoc(Name.StartLocation);
  3923. NameInfo.setNamedTypeInfo(TInfo);
  3924. return NameInfo;
  3925. }
  3926. case UnqualifiedId::IK_ConstructorName: {
  3927. TypeSourceInfo *TInfo;
  3928. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  3929. if (Ty.isNull())
  3930. return DeclarationNameInfo();
  3931. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3932. Context.getCanonicalType(Ty)));
  3933. NameInfo.setLoc(Name.StartLocation);
  3934. NameInfo.setNamedTypeInfo(TInfo);
  3935. return NameInfo;
  3936. }
  3937. case UnqualifiedId::IK_ConstructorTemplateId: {
  3938. // In well-formed code, we can only have a constructor
  3939. // template-id that refers to the current context, so go there
  3940. // to find the actual type being constructed.
  3941. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  3942. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  3943. return DeclarationNameInfo();
  3944. // Determine the type of the class being constructed.
  3945. QualType CurClassType = Context.getTypeDeclType(CurClass);
  3946. // FIXME: Check two things: that the template-id names the same type as
  3947. // CurClassType, and that the template-id does not occur when the name
  3948. // was qualified.
  3949. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3950. Context.getCanonicalType(CurClassType)));
  3951. NameInfo.setLoc(Name.StartLocation);
  3952. // FIXME: should we retrieve TypeSourceInfo?
  3953. NameInfo.setNamedTypeInfo(nullptr);
  3954. return NameInfo;
  3955. }
  3956. case UnqualifiedId::IK_DestructorName: {
  3957. TypeSourceInfo *TInfo;
  3958. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  3959. if (Ty.isNull())
  3960. return DeclarationNameInfo();
  3961. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  3962. Context.getCanonicalType(Ty)));
  3963. NameInfo.setLoc(Name.StartLocation);
  3964. NameInfo.setNamedTypeInfo(TInfo);
  3965. return NameInfo;
  3966. }
  3967. case UnqualifiedId::IK_TemplateId: {
  3968. TemplateName TName = Name.TemplateId->Template.get();
  3969. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  3970. return Context.getNameForTemplate(TName, TNameLoc);
  3971. }
  3972. } // switch (Name.getKind())
  3973. llvm_unreachable("Unknown name kind");
  3974. }
  3975. static QualType getCoreType(QualType Ty) {
  3976. do {
  3977. if (Ty->isPointerType() || Ty->isReferenceType())
  3978. Ty = Ty->getPointeeType();
  3979. else if (Ty->isArrayType())
  3980. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  3981. else
  3982. return Ty.withoutLocalFastQualifiers();
  3983. } while (true);
  3984. }
  3985. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  3986. /// and Definition have "nearly" matching parameters. This heuristic is
  3987. /// used to improve diagnostics in the case where an out-of-line function
  3988. /// definition doesn't match any declaration within the class or namespace.
  3989. /// Also sets Params to the list of indices to the parameters that differ
  3990. /// between the declaration and the definition. If hasSimilarParameters
  3991. /// returns true and Params is empty, then all of the parameters match.
  3992. static bool hasSimilarParameters(ASTContext &Context,
  3993. FunctionDecl *Declaration,
  3994. FunctionDecl *Definition,
  3995. SmallVectorImpl<unsigned> &Params) {
  3996. Params.clear();
  3997. if (Declaration->param_size() != Definition->param_size())
  3998. return false;
  3999. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4000. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4001. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4002. // The parameter types are identical
  4003. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4004. continue;
  4005. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4006. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4007. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4008. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4009. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4010. (DeclTyName && DeclTyName == DefTyName))
  4011. Params.push_back(Idx);
  4012. else // The two parameters aren't even close
  4013. return false;
  4014. }
  4015. return true;
  4016. }
  4017. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4018. /// declarator needs to be rebuilt in the current instantiation.
  4019. /// Any bits of declarator which appear before the name are valid for
  4020. /// consideration here. That's specifically the type in the decl spec
  4021. /// and the base type in any member-pointer chunks.
  4022. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4023. DeclarationName Name) {
  4024. // The types we specifically need to rebuild are:
  4025. // - typenames, typeofs, and decltypes
  4026. // - types which will become injected class names
  4027. // Of course, we also need to rebuild any type referencing such a
  4028. // type. It's safest to just say "dependent", but we call out a
  4029. // few cases here.
  4030. DeclSpec &DS = D.getMutableDeclSpec();
  4031. switch (DS.getTypeSpecType()) {
  4032. case DeclSpec::TST_typename:
  4033. case DeclSpec::TST_typeofType:
  4034. case DeclSpec::TST_underlyingType:
  4035. case DeclSpec::TST_atomic: {
  4036. // Grab the type from the parser.
  4037. TypeSourceInfo *TSI = nullptr;
  4038. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4039. if (T.isNull() || !T->isDependentType()) break;
  4040. // Make sure there's a type source info. This isn't really much
  4041. // of a waste; most dependent types should have type source info
  4042. // attached already.
  4043. if (!TSI)
  4044. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4045. // Rebuild the type in the current instantiation.
  4046. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4047. if (!TSI) return true;
  4048. // Store the new type back in the decl spec.
  4049. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4050. DS.UpdateTypeRep(LocType);
  4051. break;
  4052. }
  4053. case DeclSpec::TST_decltype:
  4054. case DeclSpec::TST_typeofExpr: {
  4055. Expr *E = DS.getRepAsExpr();
  4056. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4057. if (Result.isInvalid()) return true;
  4058. DS.UpdateExprRep(Result.get());
  4059. break;
  4060. }
  4061. default:
  4062. // Nothing to do for these decl specs.
  4063. break;
  4064. }
  4065. // It doesn't matter what order we do this in.
  4066. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4067. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4068. // The only type information in the declarator which can come
  4069. // before the declaration name is the base type of a member
  4070. // pointer.
  4071. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4072. continue;
  4073. // Rebuild the scope specifier in-place.
  4074. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4075. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4076. return true;
  4077. }
  4078. return false;
  4079. }
  4080. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4081. D.setFunctionDefinitionKind(FDK_Declaration);
  4082. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4083. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4084. Dcl && Dcl->getDeclContext()->isFileContext())
  4085. Dcl->setTopLevelDeclInObjCContainer();
  4086. return Dcl;
  4087. }
  4088. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4089. /// If T is the name of a class, then each of the following shall have a
  4090. /// name different from T:
  4091. /// - every static data member of class T;
  4092. /// - every member function of class T
  4093. /// - every member of class T that is itself a type;
  4094. /// \returns true if the declaration name violates these rules.
  4095. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4096. DeclarationNameInfo NameInfo) {
  4097. DeclarationName Name = NameInfo.getName();
  4098. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  4099. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  4100. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4101. return true;
  4102. }
  4103. return false;
  4104. }
  4105. /// \brief Diagnose a declaration whose declarator-id has the given
  4106. /// nested-name-specifier.
  4107. ///
  4108. /// \param SS The nested-name-specifier of the declarator-id.
  4109. ///
  4110. /// \param DC The declaration context to which the nested-name-specifier
  4111. /// resolves.
  4112. ///
  4113. /// \param Name The name of the entity being declared.
  4114. ///
  4115. /// \param Loc The location of the name of the entity being declared.
  4116. ///
  4117. /// \returns true if we cannot safely recover from this error, false otherwise.
  4118. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4119. DeclarationName Name,
  4120. SourceLocation Loc) {
  4121. DeclContext *Cur = CurContext;
  4122. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4123. Cur = Cur->getParent();
  4124. // If the user provided a superfluous scope specifier that refers back to the
  4125. // class in which the entity is already declared, diagnose and ignore it.
  4126. //
  4127. // class X {
  4128. // void X::f();
  4129. // };
  4130. //
  4131. // Note, it was once ill-formed to give redundant qualification in all
  4132. // contexts, but that rule was removed by DR482.
  4133. if (Cur->Equals(DC)) {
  4134. if (Cur->isRecord()) {
  4135. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4136. : diag::err_member_extra_qualification)
  4137. << Name << FixItHint::CreateRemoval(SS.getRange());
  4138. SS.clear();
  4139. } else {
  4140. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4141. }
  4142. return false;
  4143. }
  4144. // Check whether the qualifying scope encloses the scope of the original
  4145. // declaration.
  4146. if (!Cur->Encloses(DC)) {
  4147. if (Cur->isRecord())
  4148. Diag(Loc, diag::err_member_qualification)
  4149. << Name << SS.getRange();
  4150. else if (isa<TranslationUnitDecl>(DC))
  4151. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4152. << Name << SS.getRange();
  4153. else if (isa<FunctionDecl>(Cur))
  4154. Diag(Loc, diag::err_invalid_declarator_in_function)
  4155. << Name << SS.getRange();
  4156. else if (isa<BlockDecl>(Cur))
  4157. Diag(Loc, diag::err_invalid_declarator_in_block)
  4158. << Name << SS.getRange();
  4159. else
  4160. Diag(Loc, diag::err_invalid_declarator_scope)
  4161. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4162. return true;
  4163. }
  4164. if (Cur->isRecord()) {
  4165. // Cannot qualify members within a class.
  4166. Diag(Loc, diag::err_member_qualification)
  4167. << Name << SS.getRange();
  4168. SS.clear();
  4169. // C++ constructors and destructors with incorrect scopes can break
  4170. // our AST invariants by having the wrong underlying types. If
  4171. // that's the case, then drop this declaration entirely.
  4172. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4173. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4174. !Context.hasSameType(Name.getCXXNameType(),
  4175. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4176. return true;
  4177. return false;
  4178. }
  4179. // C++11 [dcl.meaning]p1:
  4180. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4181. // not begin with a decltype-specifer"
  4182. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4183. while (SpecLoc.getPrefix())
  4184. SpecLoc = SpecLoc.getPrefix();
  4185. if (dyn_cast_or_null<DecltypeType>(
  4186. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4187. Diag(Loc, diag::err_decltype_in_declarator)
  4188. << SpecLoc.getTypeLoc().getSourceRange();
  4189. return false;
  4190. }
  4191. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4192. MultiTemplateParamsArg TemplateParamLists) {
  4193. // TODO: consider using NameInfo for diagnostic.
  4194. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4195. DeclarationName Name = NameInfo.getName();
  4196. // All of these full declarators require an identifier. If it doesn't have
  4197. // one, the ParsedFreeStandingDeclSpec action should be used.
  4198. if (!Name) {
  4199. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4200. Diag(D.getDeclSpec().getLocStart(),
  4201. diag::err_declarator_need_ident)
  4202. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4203. return nullptr;
  4204. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4205. return nullptr;
  4206. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4207. // we find one that is.
  4208. ShadowMergeState MergeState = S->isForDeclScope() ?
  4209. ShadowMergeState_Possible : ShadowMergeState_Disallowed; // HLSL Change - check on original scope
  4210. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4211. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4212. S = S->getParent();
  4213. DeclContext *DC = CurContext;
  4214. if (D.getCXXScopeSpec().isInvalid())
  4215. D.setInvalidType();
  4216. else if (D.getCXXScopeSpec().isSet()) {
  4217. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4218. UPPC_DeclarationQualifier))
  4219. return nullptr;
  4220. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4221. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4222. if (!DC || isa<EnumDecl>(DC)) {
  4223. // If we could not compute the declaration context, it's because the
  4224. // declaration context is dependent but does not refer to a class,
  4225. // class template, or class template partial specialization. Complain
  4226. // and return early, to avoid the coming semantic disaster.
  4227. Diag(D.getIdentifierLoc(),
  4228. diag::err_template_qualified_declarator_no_match)
  4229. << D.getCXXScopeSpec().getScopeRep()
  4230. << D.getCXXScopeSpec().getRange();
  4231. return nullptr;
  4232. }
  4233. bool IsDependentContext = DC->isDependentContext();
  4234. if (!IsDependentContext &&
  4235. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4236. return nullptr;
  4237. // If a class is incomplete, do not parse entities inside it.
  4238. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4239. Diag(D.getIdentifierLoc(),
  4240. diag::err_member_def_undefined_record)
  4241. << Name << DC << D.getCXXScopeSpec().getRange();
  4242. return nullptr;
  4243. }
  4244. if (!D.getDeclSpec().isFriendSpecified()) {
  4245. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  4246. Name, D.getIdentifierLoc())) {
  4247. if (DC->isRecord())
  4248. return nullptr;
  4249. D.setInvalidType();
  4250. }
  4251. }
  4252. // Check whether we need to rebuild the type of the given
  4253. // declaration in the current instantiation.
  4254. if (EnteringContext && IsDependentContext &&
  4255. TemplateParamLists.size() != 0) {
  4256. ContextRAII SavedContext(*this, DC);
  4257. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4258. D.setInvalidType();
  4259. }
  4260. }
  4261. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4262. QualType R = TInfo->getType();
  4263. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4264. // If this is a typedef, we'll end up spewing multiple diagnostics.
  4265. // Just return early; it's safer. If this is a function, let the
  4266. // "constructor cannot have a return type" diagnostic handle it.
  4267. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4268. return nullptr;
  4269. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4270. UPPC_DeclarationType))
  4271. D.setInvalidType();
  4272. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4273. ForRedeclaration);
  4274. // See if this is a redefinition of a variable in the same scope.
  4275. if (!D.getCXXScopeSpec().isSet()) {
  4276. bool IsLinkageLookup = false;
  4277. bool CreateBuiltins = false;
  4278. // If the declaration we're planning to build will be a function
  4279. // or object with linkage, then look for another declaration with
  4280. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4281. //
  4282. // If the declaration we're planning to build will be declared with
  4283. // external linkage in the translation unit, create any builtin with
  4284. // the same name.
  4285. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4286. /* Do nothing*/;
  4287. else if (CurContext->isFunctionOrMethod() &&
  4288. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4289. R->isFunctionType())) {
  4290. IsLinkageLookup = true;
  4291. CreateBuiltins =
  4292. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4293. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4294. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4295. CreateBuiltins = true;
  4296. if (IsLinkageLookup)
  4297. Previous.clear(LookupRedeclarationWithLinkage);
  4298. LookupName(Previous, S, CreateBuiltins);
  4299. } else { // Something like "int foo::x;"
  4300. LookupQualifiedName(Previous, DC);
  4301. // C++ [dcl.meaning]p1:
  4302. // When the declarator-id is qualified, the declaration shall refer to a
  4303. // previously declared member of the class or namespace to which the
  4304. // qualifier refers (or, in the case of a namespace, of an element of the
  4305. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4306. // thereof; [...]
  4307. //
  4308. // Note that we already checked the context above, and that we do not have
  4309. // enough information to make sure that Previous contains the declaration
  4310. // we want to match. For example, given:
  4311. //
  4312. // class X {
  4313. // void f();
  4314. // void f(float);
  4315. // };
  4316. //
  4317. // void X::f(int) { } // ill-formed
  4318. //
  4319. // In this case, Previous will point to the overload set
  4320. // containing the two f's declared in X, but neither of them
  4321. // matches.
  4322. // C++ [dcl.meaning]p1:
  4323. // [...] the member shall not merely have been introduced by a
  4324. // using-declaration in the scope of the class or namespace nominated by
  4325. // the nested-name-specifier of the declarator-id.
  4326. RemoveUsingDecls(Previous);
  4327. }
  4328. if (Previous.isSingleResult() &&
  4329. Previous.getFoundDecl()->isTemplateParameter()) {
  4330. // Maybe we will complain about the shadowed template parameter.
  4331. if (!D.isInvalidType())
  4332. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4333. Previous.getFoundDecl());
  4334. // Just pretend that we didn't see the previous declaration.
  4335. Previous.clear();
  4336. }
  4337. // In C++, the previous declaration we find might be a tag type
  4338. // (class or enum). In this case, the new declaration will hide the
  4339. // tag type. Note that this does does not apply if we're declaring a
  4340. // typedef (C++ [dcl.typedef]p4).
  4341. if (Previous.isSingleTagDecl() &&
  4342. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  4343. Previous.clear();
  4344. // Check that there are no default arguments other than in the parameters
  4345. // of a function declaration (C++ only).
  4346. if (getLangOpts().CPlusPlus)
  4347. CheckExtraCXXDefaultArguments(D);
  4348. // HLSL Change Starts
  4349. if (getLangOpts().HLSL) {
  4350. const bool IsParameterFalse = false;
  4351. if (!DiagnoseHLSLDecl(D, DC, TInfo, IsParameterFalse)) {
  4352. assert(D.isInvalidType() && "otherwise DiagnoseHLSLDecl failed but "
  4353. "didn't invalidate declaration");
  4354. return 0;
  4355. }
  4356. }
  4357. // HLSL Change Ends
  4358. NamedDecl *New;
  4359. bool AddToScope = true;
  4360. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4361. if (TemplateParamLists.size()) {
  4362. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4363. return nullptr;
  4364. }
  4365. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4366. } else if (R->isFunctionType()) {
  4367. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4368. TemplateParamLists,
  4369. AddToScope);
  4370. } else {
  4371. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4372. AddToScope, MergeState); // HLSL Change - add merge state
  4373. }
  4374. if (!New)
  4375. return nullptr;
  4376. TransferUnusualAttributes(D, New); // HLSL Change
  4377. // If this has an identifier and is not an invalid redeclaration or
  4378. // function template specialization, add it to the scope stack.
  4379. if (New->getDeclName() && AddToScope &&
  4380. !(D.isRedeclaration() && New->isInvalidDecl())) {
  4381. // Only make a locally-scoped extern declaration visible if it is the first
  4382. // declaration of this entity. Qualified lookup for such an entity should
  4383. // only find this declaration if there is no visible declaration of it.
  4384. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4385. PushOnScopeChains(New, S, AddToContext);
  4386. if (!AddToContext)
  4387. CurContext->addHiddenDecl(New);
  4388. }
  4389. return New;
  4390. }
  4391. /// Helper method to turn variable array types into constant array
  4392. /// types in certain situations which would otherwise be errors (for
  4393. /// GCC compatibility).
  4394. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4395. ASTContext &Context,
  4396. bool &SizeIsNegative,
  4397. llvm::APSInt &Oversized) {
  4398. // This method tries to turn a variable array into a constant
  4399. // array even when the size isn't an ICE. This is necessary
  4400. // for compatibility with code that depends on gcc's buggy
  4401. // constant expression folding, like struct {char x[(int)(char*)2];}
  4402. SizeIsNegative = false;
  4403. Oversized = 0;
  4404. if (T->isDependentType())
  4405. return QualType();
  4406. QualifierCollector Qs;
  4407. const Type *Ty = Qs.strip(T);
  4408. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4409. QualType Pointee = PTy->getPointeeType();
  4410. QualType FixedType =
  4411. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4412. Oversized);
  4413. if (FixedType.isNull()) return FixedType;
  4414. FixedType = Context.getPointerType(FixedType);
  4415. return Qs.apply(Context, FixedType);
  4416. }
  4417. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4418. QualType Inner = PTy->getInnerType();
  4419. QualType FixedType =
  4420. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4421. Oversized);
  4422. if (FixedType.isNull()) return FixedType;
  4423. FixedType = Context.getParenType(FixedType);
  4424. return Qs.apply(Context, FixedType);
  4425. }
  4426. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4427. if (!VLATy)
  4428. return QualType();
  4429. // FIXME: We should probably handle this case
  4430. if (VLATy->getElementType()->isVariablyModifiedType())
  4431. return QualType();
  4432. llvm::APSInt Res;
  4433. if (!VLATy->getSizeExpr() ||
  4434. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4435. return QualType();
  4436. // Check whether the array size is negative.
  4437. if (Res.isSigned() && Res.isNegative()) {
  4438. SizeIsNegative = true;
  4439. return QualType();
  4440. }
  4441. // Check whether the array is too large to be addressed.
  4442. unsigned ActiveSizeBits
  4443. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4444. Res);
  4445. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4446. Oversized = Res;
  4447. return QualType();
  4448. }
  4449. return Context.getConstantArrayType(VLATy->getElementType(),
  4450. Res, ArrayType::Normal, 0);
  4451. }
  4452. static void
  4453. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4454. SrcTL = SrcTL.getUnqualifiedLoc();
  4455. DstTL = DstTL.getUnqualifiedLoc();
  4456. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4457. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4458. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4459. DstPTL.getPointeeLoc());
  4460. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4461. return;
  4462. }
  4463. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4464. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4465. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4466. DstPTL.getInnerLoc());
  4467. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4468. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4469. return;
  4470. }
  4471. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4472. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4473. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4474. TypeLoc DstElemTL = DstATL.getElementLoc();
  4475. DstElemTL.initializeFullCopy(SrcElemTL);
  4476. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4477. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4478. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4479. }
  4480. /// Helper method to turn variable array types into constant array
  4481. /// types in certain situations which would otherwise be errors (for
  4482. /// GCC compatibility).
  4483. static TypeSourceInfo*
  4484. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4485. ASTContext &Context,
  4486. bool &SizeIsNegative,
  4487. llvm::APSInt &Oversized) {
  4488. QualType FixedTy
  4489. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4490. SizeIsNegative, Oversized);
  4491. if (FixedTy.isNull())
  4492. return nullptr;
  4493. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4494. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4495. FixedTInfo->getTypeLoc());
  4496. return FixedTInfo;
  4497. }
  4498. /// \brief Register the given locally-scoped extern "C" declaration so
  4499. /// that it can be found later for redeclarations. We include any extern "C"
  4500. /// declaration that is not visible in the translation unit here, not just
  4501. /// function-scope declarations.
  4502. void
  4503. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4504. if (!getLangOpts().CPlusPlus &&
  4505. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4506. // Don't need to track declarations in the TU in C.
  4507. return;
  4508. // Note that we have a locally-scoped external with this name.
  4509. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  4510. }
  4511. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4512. // FIXME: We can have multiple results via __attribute__((overloadable)).
  4513. auto Result = Context.getExternCContextDecl()->lookup(Name);
  4514. return Result.empty() ? nullptr : *Result.begin();
  4515. }
  4516. /// \brief Diagnose function specifiers on a declaration of an identifier that
  4517. /// does not identify a function.
  4518. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  4519. // FIXME: We should probably indicate the identifier in question to avoid
  4520. // confusion for constructs like "inline int a(), b;"
  4521. if (DS.isInlineSpecified())
  4522. Diag(DS.getInlineSpecLoc(),
  4523. diag::err_inline_non_function);
  4524. if (DS.isVirtualSpecified())
  4525. Diag(DS.getVirtualSpecLoc(),
  4526. diag::err_virtual_non_function);
  4527. if (DS.isExplicitSpecified())
  4528. Diag(DS.getExplicitSpecLoc(),
  4529. diag::err_explicit_non_function);
  4530. if (DS.isNoreturnSpecified())
  4531. Diag(DS.getNoreturnSpecLoc(),
  4532. diag::err_noreturn_non_function);
  4533. }
  4534. NamedDecl*
  4535. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  4536. TypeSourceInfo *TInfo, LookupResult &Previous) {
  4537. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  4538. if (D.getCXXScopeSpec().isSet()) {
  4539. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  4540. << D.getCXXScopeSpec().getRange();
  4541. D.setInvalidType();
  4542. // Pretend we didn't see the scope specifier.
  4543. DC = CurContext;
  4544. Previous.clear();
  4545. }
  4546. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4547. if (D.getDeclSpec().isConstexprSpecified())
  4548. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  4549. << 1;
  4550. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  4551. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  4552. << D.getName().getSourceRange();
  4553. return nullptr;
  4554. }
  4555. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  4556. if (!NewTD) return nullptr;
  4557. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4558. ProcessDeclAttributes(S, NewTD, D);
  4559. CheckTypedefForVariablyModifiedType(S, NewTD);
  4560. bool Redeclaration = D.isRedeclaration();
  4561. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  4562. D.setRedeclaration(Redeclaration);
  4563. return ND;
  4564. }
  4565. void
  4566. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  4567. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  4568. // then it shall have block scope.
  4569. // Note that variably modified types must be fixed before merging the decl so
  4570. // that redeclarations will match.
  4571. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  4572. QualType T = TInfo->getType();
  4573. if (T->isVariablyModifiedType()) {
  4574. getCurFunction()->setHasBranchProtectedScope();
  4575. if (S->getFnParent() == nullptr) {
  4576. bool SizeIsNegative;
  4577. llvm::APSInt Oversized;
  4578. TypeSourceInfo *FixedTInfo =
  4579. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  4580. SizeIsNegative,
  4581. Oversized);
  4582. if (FixedTInfo) {
  4583. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  4584. NewTD->setTypeSourceInfo(FixedTInfo);
  4585. } else {
  4586. if (SizeIsNegative)
  4587. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  4588. else if (T->isVariableArrayType())
  4589. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  4590. else if (Oversized.getBoolValue())
  4591. Diag(NewTD->getLocation(), diag::err_array_too_large)
  4592. << Oversized.toString(10);
  4593. else
  4594. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  4595. NewTD->setInvalidDecl();
  4596. }
  4597. }
  4598. }
  4599. }
  4600. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  4601. /// declares a typedef-name, either using the 'typedef' type specifier or via
  4602. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  4603. NamedDecl*
  4604. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  4605. LookupResult &Previous, bool &Redeclaration) {
  4606. // Merge the decl with the existing one if appropriate. If the decl is
  4607. // in an outer scope, it isn't the same thing.
  4608. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  4609. /*AllowInlineNamespace*/false);
  4610. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  4611. if (!Previous.empty()) {
  4612. Redeclaration = true;
  4613. MergeTypedefNameDecl(NewTD, Previous);
  4614. }
  4615. // If this is the C FILE type, notify the AST context.
  4616. if (IdentifierInfo *II = NewTD->getIdentifier())
  4617. if (!NewTD->isInvalidDecl() &&
  4618. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4619. if (II->isStr("FILE"))
  4620. Context.setFILEDecl(NewTD);
  4621. else if (II->isStr("jmp_buf"))
  4622. Context.setjmp_bufDecl(NewTD);
  4623. else if (II->isStr("sigjmp_buf"))
  4624. Context.setsigjmp_bufDecl(NewTD);
  4625. else if (II->isStr("ucontext_t"))
  4626. Context.setucontext_tDecl(NewTD);
  4627. }
  4628. return NewTD;
  4629. }
  4630. /// \brief Determines whether the given declaration is an out-of-scope
  4631. /// previous declaration.
  4632. ///
  4633. /// This routine should be invoked when name lookup has found a
  4634. /// previous declaration (PrevDecl) that is not in the scope where a
  4635. /// new declaration by the same name is being introduced. If the new
  4636. /// declaration occurs in a local scope, previous declarations with
  4637. /// linkage may still be considered previous declarations (C99
  4638. /// 6.2.2p4-5, C++ [basic.link]p6).
  4639. ///
  4640. /// \param PrevDecl the previous declaration found by name
  4641. /// lookup
  4642. ///
  4643. /// \param DC the context in which the new declaration is being
  4644. /// declared.
  4645. ///
  4646. /// \returns true if PrevDecl is an out-of-scope previous declaration
  4647. /// for a new delcaration with the same name.
  4648. static bool
  4649. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  4650. ASTContext &Context) {
  4651. if (!PrevDecl)
  4652. return false;
  4653. if (!PrevDecl->hasLinkage())
  4654. return false;
  4655. if (Context.getLangOpts().CPlusPlus) {
  4656. // C++ [basic.link]p6:
  4657. // If there is a visible declaration of an entity with linkage
  4658. // having the same name and type, ignoring entities declared
  4659. // outside the innermost enclosing namespace scope, the block
  4660. // scope declaration declares that same entity and receives the
  4661. // linkage of the previous declaration.
  4662. DeclContext *OuterContext = DC->getRedeclContext();
  4663. if (!OuterContext->isFunctionOrMethod())
  4664. // This rule only applies to block-scope declarations.
  4665. return false;
  4666. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  4667. if (PrevOuterContext->isRecord())
  4668. // We found a member function: ignore it.
  4669. return false;
  4670. // Find the innermost enclosing namespace for the new and
  4671. // previous declarations.
  4672. OuterContext = OuterContext->getEnclosingNamespaceContext();
  4673. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  4674. // The previous declaration is in a different namespace, so it
  4675. // isn't the same function.
  4676. if (!OuterContext->Equals(PrevOuterContext))
  4677. return false;
  4678. }
  4679. return true;
  4680. }
  4681. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  4682. CXXScopeSpec &SS = D.getCXXScopeSpec();
  4683. if (!SS.isSet()) return;
  4684. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  4685. }
  4686. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  4687. QualType type = decl->getType();
  4688. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  4689. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  4690. // Various kinds of declaration aren't allowed to be __autoreleasing.
  4691. unsigned kind = -1U;
  4692. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4693. if (var->hasAttr<BlocksAttr>())
  4694. kind = 0; // __block
  4695. else if (!var->hasLocalStorage())
  4696. kind = 1; // global
  4697. } else if (isa<ObjCIvarDecl>(decl)) {
  4698. kind = 3; // ivar
  4699. } else if (isa<FieldDecl>(decl)) {
  4700. kind = 2; // field
  4701. }
  4702. if (kind != -1U) {
  4703. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  4704. << kind;
  4705. }
  4706. } else if (lifetime == Qualifiers::OCL_None) {
  4707. // Try to infer lifetime.
  4708. if (!type->isObjCLifetimeType())
  4709. return false;
  4710. lifetime = type->getObjCARCImplicitLifetime();
  4711. type = Context.getLifetimeQualifiedType(type, lifetime);
  4712. decl->setType(type);
  4713. }
  4714. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4715. // Thread-local variables cannot have lifetime.
  4716. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  4717. var->getTLSKind()) {
  4718. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  4719. << var->getType();
  4720. return true;
  4721. }
  4722. }
  4723. return false;
  4724. }
  4725. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  4726. // Ensure that an auto decl is deduced otherwise the checks below might cache
  4727. // the wrong linkage.
  4728. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  4729. // 'weak' only applies to declarations with external linkage.
  4730. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  4731. if (!ND.isExternallyVisible()) {
  4732. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  4733. ND.dropAttr<WeakAttr>();
  4734. }
  4735. }
  4736. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  4737. if (ND.isExternallyVisible()) {
  4738. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  4739. ND.dropAttr<WeakRefAttr>();
  4740. ND.dropAttr<AliasAttr>();
  4741. }
  4742. }
  4743. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  4744. if (VD->hasInit()) {
  4745. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  4746. assert(VD->isThisDeclarationADefinition() &&
  4747. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  4748. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
  4749. VD->dropAttr<AliasAttr>();
  4750. }
  4751. }
  4752. }
  4753. // 'selectany' only applies to externally visible variable declarations.
  4754. // It does not apply to functions.
  4755. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  4756. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  4757. S.Diag(Attr->getLocation(),
  4758. diag::err_attribute_selectany_non_extern_data);
  4759. ND.dropAttr<SelectAnyAttr>();
  4760. }
  4761. }
  4762. // dll attributes require external linkage.
  4763. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  4764. if (!ND.isExternallyVisible()) {
  4765. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  4766. << &ND << Attr;
  4767. ND.setInvalidDecl();
  4768. }
  4769. }
  4770. }
  4771. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  4772. NamedDecl *NewDecl,
  4773. bool IsSpecialization) {
  4774. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
  4775. OldDecl = OldTD->getTemplatedDecl();
  4776. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
  4777. NewDecl = NewTD->getTemplatedDecl();
  4778. if (!OldDecl || !NewDecl)
  4779. return;
  4780. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  4781. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  4782. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  4783. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  4784. // dllimport and dllexport are inheritable attributes so we have to exclude
  4785. // inherited attribute instances.
  4786. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  4787. (NewExportAttr && !NewExportAttr->isInherited());
  4788. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  4789. // the only exception being explicit specializations.
  4790. // Implicitly generated declarations are also excluded for now because there
  4791. // is no other way to switch these to use dllimport or dllexport.
  4792. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  4793. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  4794. // Allow with a warning for free functions and global variables.
  4795. bool JustWarn = false;
  4796. if (!OldDecl->isCXXClassMember()) {
  4797. auto *VD = dyn_cast<VarDecl>(OldDecl);
  4798. if (VD && !VD->getDescribedVarTemplate())
  4799. JustWarn = true;
  4800. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  4801. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  4802. JustWarn = true;
  4803. }
  4804. // We cannot change a declaration that's been used because IR has already
  4805. // been emitted. Dllimported functions will still work though (modulo
  4806. // address equality) as they can use the thunk.
  4807. if (OldDecl->isUsed())
  4808. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  4809. JustWarn = false;
  4810. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  4811. : diag::err_attribute_dll_redeclaration;
  4812. S.Diag(NewDecl->getLocation(), DiagID)
  4813. << NewDecl
  4814. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  4815. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4816. if (!JustWarn) {
  4817. NewDecl->setInvalidDecl();
  4818. return;
  4819. }
  4820. }
  4821. // A redeclaration is not allowed to drop a dllimport attribute, the only
  4822. // exceptions being inline function definitions, local extern declarations,
  4823. // and qualified friend declarations.
  4824. // NB: MSVC converts such a declaration to dllexport.
  4825. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  4826. if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
  4827. // Ignore static data because out-of-line definitions are diagnosed
  4828. // separately.
  4829. IsStaticDataMember = VD->isStaticDataMember();
  4830. else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  4831. IsInline = FD->isInlined();
  4832. IsQualifiedFriend = FD->getQualifier() &&
  4833. FD->getFriendObjectKind() == Decl::FOK_Declared;
  4834. }
  4835. if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
  4836. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  4837. S.Diag(NewDecl->getLocation(),
  4838. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  4839. << NewDecl << OldImportAttr;
  4840. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4841. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  4842. OldDecl->dropAttr<DLLImportAttr>();
  4843. NewDecl->dropAttr<DLLImportAttr>();
  4844. } else if (IsInline && OldImportAttr &&
  4845. !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  4846. // In MinGW, seeing a function declared inline drops the dllimport attribute.
  4847. OldDecl->dropAttr<DLLImportAttr>();
  4848. NewDecl->dropAttr<DLLImportAttr>();
  4849. S.Diag(NewDecl->getLocation(),
  4850. diag::warn_dllimport_dropped_from_inline_function)
  4851. << NewDecl << OldImportAttr;
  4852. }
  4853. }
  4854. /// Given that we are within the definition of the given function,
  4855. /// will that definition behave like C99's 'inline', where the
  4856. /// definition is discarded except for optimization purposes?
  4857. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  4858. // Try to avoid calling GetGVALinkageForFunction.
  4859. // All cases of this require the 'inline' keyword.
  4860. if (!FD->isInlined()) return false;
  4861. // This is only possible in C++ with the gnu_inline attribute.
  4862. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  4863. return false;
  4864. // Okay, go ahead and call the relatively-more-expensive function.
  4865. #ifndef NDEBUG
  4866. // AST quite reasonably asserts that it's working on a function
  4867. // definition. We don't really have a way to tell it that we're
  4868. // currently defining the function, so just lie to it in +Asserts
  4869. // builds. This is an awful hack.
  4870. FD->setLazyBody(1);
  4871. #endif
  4872. bool isC99Inline =
  4873. S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  4874. #ifndef NDEBUG
  4875. FD->setLazyBody(0);
  4876. #endif
  4877. return isC99Inline;
  4878. }
  4879. /// Determine whether a variable is extern "C" prior to attaching
  4880. /// an initializer. We can't just call isExternC() here, because that
  4881. /// will also compute and cache whether the declaration is externally
  4882. /// visible, which might change when we attach the initializer.
  4883. ///
  4884. /// This can only be used if the declaration is known to not be a
  4885. /// redeclaration of an internal linkage declaration.
  4886. ///
  4887. /// For instance:
  4888. ///
  4889. /// auto x = []{};
  4890. ///
  4891. /// Attaching the initializer here makes this declaration not externally
  4892. /// visible, because its type has internal linkage.
  4893. ///
  4894. /// FIXME: This is a hack.
  4895. template<typename T>
  4896. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  4897. if (S.getLangOpts().CPlusPlus) {
  4898. // In C++, the overloadable attribute negates the effects of extern "C".
  4899. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  4900. return false;
  4901. }
  4902. return D->isExternC();
  4903. }
  4904. static bool shouldConsiderLinkage(const VarDecl *VD) {
  4905. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  4906. if (DC->isFunctionOrMethod())
  4907. return VD->hasExternalStorage();
  4908. if (DC->isFileContext())
  4909. return true;
  4910. if (DC->isRecord())
  4911. return false;
  4912. llvm_unreachable("Unexpected context");
  4913. }
  4914. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  4915. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  4916. if (DC->isFileContext() || DC->isFunctionOrMethod())
  4917. return true;
  4918. if (DC->isRecord())
  4919. return false;
  4920. llvm_unreachable("Unexpected context");
  4921. }
  4922. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  4923. AttributeList::Kind Kind) {
  4924. for (const AttributeList *L = AttrList; L; L = L->getNext())
  4925. if (L->getKind() == Kind)
  4926. return true;
  4927. return false;
  4928. }
  4929. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  4930. AttributeList::Kind Kind) {
  4931. // Check decl attributes on the DeclSpec.
  4932. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  4933. return true;
  4934. // Walk the declarator structure, checking decl attributes that were in a type
  4935. // position to the decl itself.
  4936. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  4937. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  4938. return true;
  4939. }
  4940. // Finally, check attributes on the decl itself.
  4941. return hasParsedAttr(S, PD.getAttributes(), Kind);
  4942. }
  4943. /// Adjust the \c DeclContext for a function or variable that might be a
  4944. /// function-local external declaration.
  4945. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  4946. if (!DC->isFunctionOrMethod())
  4947. return false;
  4948. // If this is a local extern function or variable declared within a function
  4949. // template, don't add it into the enclosing namespace scope until it is
  4950. // instantiated; it might have a dependent type right now.
  4951. if (DC->isDependentContext())
  4952. return true;
  4953. // C++11 [basic.link]p7:
  4954. // When a block scope declaration of an entity with linkage is not found to
  4955. // refer to some other declaration, then that entity is a member of the
  4956. // innermost enclosing namespace.
  4957. //
  4958. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  4959. // semantically-enclosing namespace, not a lexically-enclosing one.
  4960. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  4961. DC = DC->getParent();
  4962. return true;
  4963. }
  4964. /// \brief Returns true if given declaration is TU-scoped and externally
  4965. /// visible.
  4966. static bool isDeclTUScopedExternallyVisible(const Decl *D) {
  4967. if (auto *FD = dyn_cast<FunctionDecl>(D))
  4968. return (FD->getDeclContext()->isTranslationUnit() || FD->isExternC()) &&
  4969. FD->hasExternalFormalLinkage();
  4970. else if (auto *VD = dyn_cast<VarDecl>(D))
  4971. return (VD->getDeclContext()->isTranslationUnit() || VD->isExternC()) &&
  4972. VD->hasExternalFormalLinkage();
  4973. llvm_unreachable("Unknown type of decl!");
  4974. }
  4975. NamedDecl *
  4976. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4977. TypeSourceInfo *TInfo, LookupResult &Previous,
  4978. MultiTemplateParamsArg TemplateParamLists,
  4979. bool &AddToScope, ShadowMergeState MergeState) { // HLSL Change - add merge state
  4980. QualType R = TInfo->getType();
  4981. DeclarationName Name = GetNameForDeclarator(D).getName();
  4982. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  4983. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  4984. // dllimport globals without explicit storage class are treated as extern. We
  4985. // have to change the storage class this early to get the right DeclContext.
  4986. if (SC == SC_None && !DC->isRecord() &&
  4987. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  4988. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  4989. SC = SC_Extern;
  4990. DeclContext *OriginalDC = DC;
  4991. bool IsLocalExternDecl = SC == SC_Extern &&
  4992. adjustContextForLocalExternDecl(DC);
  4993. if (getLangOpts().OpenCL) {
  4994. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  4995. QualType NR = R;
  4996. while (NR->isPointerType()) {
  4997. if (NR->isFunctionPointerType()) {
  4998. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
  4999. D.setInvalidType();
  5000. break;
  5001. }
  5002. NR = NR->getPointeeType();
  5003. }
  5004. if (!getOpenCLOptions().cl_khr_fp16) {
  5005. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5006. // half array type (unless the cl_khr_fp16 extension is enabled).
  5007. if (Context.getBaseElementType(R)->isHalfType()) {
  5008. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5009. D.setInvalidType();
  5010. }
  5011. }
  5012. }
  5013. if (SCSpec == DeclSpec::SCS_mutable) {
  5014. // mutable can only appear on non-static class members, so it's always
  5015. // an error here
  5016. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5017. D.setInvalidType();
  5018. SC = SC_None;
  5019. }
  5020. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5021. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5022. D.getDeclSpec().getStorageClassSpecLoc())) {
  5023. // In C++11, the 'register' storage class specifier is deprecated.
  5024. // Suppress the warning in system macros, it's used in macros in some
  5025. // popular C system headers, such as in glibc's htonl() macro.
  5026. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5027. diag::warn_deprecated_register)
  5028. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5029. }
  5030. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5031. if (!II) {
  5032. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  5033. << Name;
  5034. return nullptr;
  5035. }
  5036. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5037. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5038. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5039. // appear in the declaration specifiers in an external declaration.
  5040. // Global Register+Asm is a GNU extension we support.
  5041. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5042. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5043. D.setInvalidType();
  5044. }
  5045. }
  5046. if (getLangOpts().OpenCL) {
  5047. // Set up the special work-group-local storage class for variables in the
  5048. // OpenCL __local address space.
  5049. if (R.getAddressSpace() == LangAS::opencl_local) {
  5050. SC = SC_OpenCLWorkGroupLocal;
  5051. }
  5052. // OpenCL v1.2 s6.9.b p4:
  5053. // The sampler type cannot be used with the __local and __global address
  5054. // space qualifiers.
  5055. if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
  5056. R.getAddressSpace() == LangAS::opencl_global)) {
  5057. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5058. }
  5059. // OpenCL 1.2 spec, p6.9 r:
  5060. // The event type cannot be used to declare a program scope variable.
  5061. // The event type cannot be used with the __local, __constant and __global
  5062. // address space qualifiers.
  5063. if (R->isEventT()) {
  5064. if (S->getParent() == nullptr) {
  5065. Diag(D.getLocStart(), diag::err_event_t_global_var);
  5066. D.setInvalidType();
  5067. }
  5068. if (R.getAddressSpace()) {
  5069. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5070. D.setInvalidType();
  5071. }
  5072. }
  5073. }
  5074. bool IsExplicitSpecialization = false;
  5075. bool IsVariableTemplateSpecialization = false;
  5076. bool IsPartialSpecialization = false;
  5077. bool IsVariableTemplate = false;
  5078. VarDecl *NewVD = nullptr;
  5079. VarTemplateDecl *NewTemplate = nullptr;
  5080. TemplateParameterList *TemplateParams = nullptr;
  5081. if (!getLangOpts().CPlusPlus) {
  5082. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5083. D.getIdentifierLoc(), II,
  5084. R, TInfo, SC);
  5085. if (D.isInvalidType())
  5086. NewVD->setInvalidDecl();
  5087. } else {
  5088. bool Invalid = false;
  5089. if (DC->isRecord() && !CurContext->isRecord()) {
  5090. // This is an out-of-line definition of a static data member.
  5091. switch (SC) {
  5092. case SC_None:
  5093. break;
  5094. case SC_Static:
  5095. if (!getLangOpts().HLSL) // HLSL Change: We had to set SC_Static for
  5096. // static data member to distinguish it from
  5097. // global constant variable.
  5098. // So we ignore this warning.
  5099. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5100. diag::err_static_out_of_line)
  5101. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5102. break;
  5103. case SC_Auto:
  5104. case SC_Register:
  5105. case SC_Extern:
  5106. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5107. // to names of variables declared in a block or to function parameters.
  5108. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5109. // of class members
  5110. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5111. diag::err_storage_class_for_static_member)
  5112. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5113. break;
  5114. case SC_PrivateExtern:
  5115. llvm_unreachable("C storage class in c++!");
  5116. case SC_OpenCLWorkGroupLocal:
  5117. llvm_unreachable("OpenCL storage class in c++!");
  5118. }
  5119. }
  5120. if (SC == SC_Static && CurContext->isRecord()) {
  5121. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5122. if (RD->isLocalClass())
  5123. Diag(D.getIdentifierLoc(),
  5124. diag::err_static_data_member_not_allowed_in_local_class)
  5125. << Name << RD->getDeclName();
  5126. // C++98 [class.union]p1: If a union contains a static data member,
  5127. // the program is ill-formed. C++11 drops this restriction.
  5128. if (RD->isUnion())
  5129. Diag(D.getIdentifierLoc(),
  5130. getLangOpts().CPlusPlus11
  5131. ? diag::warn_cxx98_compat_static_data_member_in_union
  5132. : diag::ext_static_data_member_in_union) << Name;
  5133. // We conservatively disallow static data members in anonymous structs.
  5134. else if (!RD->getDeclName())
  5135. Diag(D.getIdentifierLoc(),
  5136. diag::err_static_data_member_not_allowed_in_anon_struct)
  5137. << Name << RD->isUnion();
  5138. }
  5139. }
  5140. // Match up the template parameter lists with the scope specifier, then
  5141. // determine whether we have a template or a template specialization.
  5142. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5143. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5144. D.getCXXScopeSpec(),
  5145. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5146. ? D.getName().TemplateId
  5147. : nullptr,
  5148. TemplateParamLists,
  5149. /*never a friend*/ false, IsExplicitSpecialization, Invalid);
  5150. if (TemplateParams) {
  5151. if (!TemplateParams->size() &&
  5152. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5153. // There is an extraneous 'template<>' for this variable. Complain
  5154. // about it, but allow the declaration of the variable.
  5155. Diag(TemplateParams->getTemplateLoc(),
  5156. diag::err_template_variable_noparams)
  5157. << II
  5158. << SourceRange(TemplateParams->getTemplateLoc(),
  5159. TemplateParams->getRAngleLoc());
  5160. TemplateParams = nullptr;
  5161. } else {
  5162. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5163. // This is an explicit specialization or a partial specialization.
  5164. // FIXME: Check that we can declare a specialization here.
  5165. IsVariableTemplateSpecialization = true;
  5166. IsPartialSpecialization = TemplateParams->size() > 0;
  5167. } else { // if (TemplateParams->size() > 0)
  5168. // This is a template declaration.
  5169. IsVariableTemplate = true;
  5170. // Check that we can declare a template here.
  5171. if (CheckTemplateDeclScope(S, TemplateParams))
  5172. return nullptr;
  5173. // Only C++1y supports variable templates (N3651).
  5174. Diag(D.getIdentifierLoc(),
  5175. getLangOpts().CPlusPlus14
  5176. ? diag::warn_cxx11_compat_variable_template
  5177. : diag::ext_variable_template);
  5178. }
  5179. }
  5180. } else {
  5181. assert(
  5182. (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
  5183. "should have a 'template<>' for this decl");
  5184. }
  5185. if (IsVariableTemplateSpecialization) {
  5186. SourceLocation TemplateKWLoc =
  5187. TemplateParamLists.size() > 0
  5188. ? TemplateParamLists[0]->getTemplateLoc()
  5189. : SourceLocation();
  5190. DeclResult Res = ActOnVarTemplateSpecialization(
  5191. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5192. IsPartialSpecialization);
  5193. if (Res.isInvalid())
  5194. return nullptr;
  5195. NewVD = cast<VarDecl>(Res.get());
  5196. AddToScope = false;
  5197. } else
  5198. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5199. D.getIdentifierLoc(), II, R, TInfo, SC);
  5200. // If this is supposed to be a variable template, create it as such.
  5201. if (IsVariableTemplate) {
  5202. NewTemplate =
  5203. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5204. TemplateParams, NewVD);
  5205. NewVD->setDescribedVarTemplate(NewTemplate);
  5206. }
  5207. // If this decl has an auto type in need of deduction, make a note of the
  5208. // Decl so we can diagnose uses of it in its own initializer.
  5209. if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
  5210. ParsingInitForAutoVars.insert(NewVD);
  5211. if (D.isInvalidType() || Invalid) {
  5212. NewVD->setInvalidDecl();
  5213. if (NewTemplate)
  5214. NewTemplate->setInvalidDecl();
  5215. }
  5216. SetNestedNameSpecifier(NewVD, D);
  5217. // If we have any template parameter lists that don't directly belong to
  5218. // the variable (matching the scope specifier), store them.
  5219. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5220. if (TemplateParamLists.size() > VDTemplateParamLists)
  5221. NewVD->setTemplateParameterListsInfo(
  5222. Context, TemplateParamLists.size() - VDTemplateParamLists,
  5223. TemplateParamLists.data());
  5224. if (D.getDeclSpec().isConstexprSpecified())
  5225. NewVD->setConstexpr(true);
  5226. }
  5227. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5228. // lexical context will be different from the semantic context.
  5229. NewVD->setLexicalDeclContext(CurContext);
  5230. if (NewTemplate)
  5231. NewTemplate->setLexicalDeclContext(CurContext);
  5232. if (IsLocalExternDecl)
  5233. NewVD->setLocalExternDecl();
  5234. bool EmitTLSUnsupportedError = false;
  5235. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5236. // C++11 [dcl.stc]p4:
  5237. // When thread_local is applied to a variable of block scope the
  5238. // storage-class-specifier static is implied if it does not appear
  5239. // explicitly.
  5240. // Core issue: 'static' is not implied if the variable is declared
  5241. // 'extern'.
  5242. if (NewVD->hasLocalStorage() &&
  5243. (SCSpec != DeclSpec::SCS_unspecified ||
  5244. TSCS != DeclSpec::TSCS_thread_local ||
  5245. !DC->isFunctionOrMethod()))
  5246. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5247. diag::err_thread_non_global)
  5248. << DeclSpec::getSpecifierName(TSCS);
  5249. else if (!Context.getTargetInfo().isTLSSupported()) {
  5250. if (getLangOpts().CUDA) {
  5251. // Postpone error emission until we've collected attributes required to
  5252. // figure out whether it's a host or device variable and whether the
  5253. // error should be ignored.
  5254. EmitTLSUnsupportedError = true;
  5255. // We still need to mark the variable as TLS so it shows up in AST with
  5256. // proper storage class for other tools to use even if we're not going
  5257. // to emit any code for it.
  5258. NewVD->setTSCSpec(TSCS);
  5259. } else
  5260. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5261. diag::err_thread_unsupported);
  5262. } else
  5263. NewVD->setTSCSpec(TSCS);
  5264. }
  5265. // C99 6.7.4p3
  5266. // An inline definition of a function with external linkage shall
  5267. // not contain a definition of a modifiable object with static or
  5268. // thread storage duration...
  5269. // We only apply this when the function is required to be defined
  5270. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5271. // that a local variable with thread storage duration still has to
  5272. // be marked 'static'. Also note that it's possible to get these
  5273. // semantics in C++ using __attribute__((gnu_inline)).
  5274. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5275. !NewVD->getType().isConstQualified()) {
  5276. FunctionDecl *CurFD = getCurFunctionDecl();
  5277. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5278. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5279. diag::warn_static_local_in_extern_inline);
  5280. MaybeSuggestAddingStaticToDecl(CurFD);
  5281. }
  5282. }
  5283. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5284. if (IsVariableTemplateSpecialization)
  5285. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5286. << (IsPartialSpecialization ? 1 : 0)
  5287. << FixItHint::CreateRemoval(
  5288. D.getDeclSpec().getModulePrivateSpecLoc());
  5289. else if (IsExplicitSpecialization)
  5290. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5291. << 2
  5292. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5293. else if (NewVD->hasLocalStorage())
  5294. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5295. << 0 << NewVD->getDeclName()
  5296. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5297. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5298. else {
  5299. NewVD->setModulePrivate();
  5300. if (NewTemplate)
  5301. NewTemplate->setModulePrivate();
  5302. }
  5303. }
  5304. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5305. ProcessDeclAttributes(S, NewVD, D);
  5306. if (getLangOpts().CUDA) {
  5307. if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
  5308. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5309. diag::err_thread_unsupported);
  5310. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5311. // storage [duration]."
  5312. if (SC == SC_None && S->getFnParent() != nullptr &&
  5313. (NewVD->hasAttr<CUDASharedAttr>() ||
  5314. NewVD->hasAttr<CUDAConstantAttr>())) {
  5315. NewVD->setStorageClass(SC_Static);
  5316. }
  5317. }
  5318. // Ensure that dllimport globals without explicit storage class are treated as
  5319. // extern. The storage class is set above using parsed attributes. Now we can
  5320. // check the VarDecl itself.
  5321. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5322. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5323. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5324. // In auto-retain/release, infer strong retension for variables of
  5325. // retainable type.
  5326. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5327. NewVD->setInvalidDecl();
  5328. // Handle GNU asm-label extension (encoded as an attribute).
  5329. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5330. // The parser guarantees this is a string.
  5331. StringLiteral *SE = cast<StringLiteral>(E);
  5332. StringRef Label = SE->getString();
  5333. if (S->getFnParent() != nullptr) {
  5334. switch (SC) {
  5335. case SC_None:
  5336. case SC_Auto:
  5337. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5338. break;
  5339. case SC_Register:
  5340. // Local Named register
  5341. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  5342. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5343. break;
  5344. case SC_Static:
  5345. case SC_Extern:
  5346. case SC_PrivateExtern:
  5347. case SC_OpenCLWorkGroupLocal:
  5348. break;
  5349. }
  5350. } else if (SC == SC_Register) {
  5351. // Global Named register
  5352. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  5353. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5354. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5355. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5356. NewVD->setInvalidDecl(true);
  5357. }
  5358. }
  5359. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  5360. Context, Label, 0));
  5361. } else if (!ExtnameUndeclaredIdentifiers.empty() &&
  5362. isDeclTUScopedExternallyVisible(NewVD)) {
  5363. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5364. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  5365. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5366. NewVD->addAttr(I->second);
  5367. ExtnameUndeclaredIdentifiers.erase(I);
  5368. }
  5369. }
  5370. // Diagnose shadowed variables before filtering for scope.
  5371. if (D.getCXXScopeSpec().isEmpty())
  5372. CheckShadow(S, NewVD, Previous);
  5373. // Don't consider existing declarations that are in a different
  5374. // scope and are out-of-semantic-context declarations (if the new
  5375. // declaration has linkage).
  5376. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  5377. D.getCXXScopeSpec().isNotEmpty() ||
  5378. IsExplicitSpecialization ||
  5379. IsVariableTemplateSpecialization);
  5380. // Check whether the previous declaration is in the same block scope. This
  5381. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  5382. if (getLangOpts().CPlusPlus &&
  5383. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  5384. NewVD->setPreviousDeclInSameBlockScope(
  5385. Previous.isSingleResult() && !Previous.isShadowed() &&
  5386. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  5387. if (!getLangOpts().CPlusPlus) {
  5388. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5389. } else {
  5390. // If this is an explicit specialization of a static data member, check it.
  5391. if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
  5392. CheckMemberSpecialization(NewVD, Previous))
  5393. NewVD->setInvalidDecl();
  5394. // Merge the decl with the existing one if appropriate.
  5395. if (!Previous.empty()) {
  5396. if (Previous.isSingleResult() &&
  5397. isa<FieldDecl>(Previous.getFoundDecl()) &&
  5398. D.getCXXScopeSpec().isSet()) {
  5399. // The user tried to define a non-static data member
  5400. // out-of-line (C++ [dcl.meaning]p1).
  5401. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  5402. << D.getCXXScopeSpec().getRange();
  5403. Previous.clear();
  5404. NewVD->setInvalidDecl();
  5405. }
  5406. } else if (D.getCXXScopeSpec().isSet()) {
  5407. // No previous declaration in the qualifying scope.
  5408. Diag(D.getIdentifierLoc(), diag::err_no_member)
  5409. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  5410. << D.getCXXScopeSpec().getRange();
  5411. NewVD->setInvalidDecl();
  5412. }
  5413. if (!IsVariableTemplateSpecialization)
  5414. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous, MergeState)); // HLSL Change - add merge state
  5415. if (NewTemplate) {
  5416. VarTemplateDecl *PrevVarTemplate =
  5417. NewVD->getPreviousDecl()
  5418. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  5419. : nullptr;
  5420. // Check the template parameter list of this declaration, possibly
  5421. // merging in the template parameter list from the previous variable
  5422. // template declaration.
  5423. if (CheckTemplateParameterList(
  5424. TemplateParams,
  5425. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  5426. : nullptr,
  5427. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  5428. DC->isDependentContext())
  5429. ? TPC_ClassTemplateMember
  5430. : TPC_VarTemplate))
  5431. NewVD->setInvalidDecl();
  5432. // If we are providing an explicit specialization of a static variable
  5433. // template, make a note of that.
  5434. if (PrevVarTemplate &&
  5435. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  5436. PrevVarTemplate->setMemberSpecialization();
  5437. }
  5438. }
  5439. ProcessPragmaWeak(S, NewVD);
  5440. // If this is the first declaration of an extern C variable, update
  5441. // the map of such variables.
  5442. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  5443. isIncompleteDeclExternC(*this, NewVD))
  5444. RegisterLocallyScopedExternCDecl(NewVD, S);
  5445. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  5446. Decl *ManglingContextDecl;
  5447. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  5448. NewVD->getDeclContext(), ManglingContextDecl)) {
  5449. Context.setManglingNumber(
  5450. NewVD, MCtx->getManglingNumber(
  5451. NewVD, getMSManglingNumber(getLangOpts(), S)));
  5452. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  5453. }
  5454. }
  5455. if (D.isRedeclaration() && !Previous.empty()) {
  5456. checkDLLAttributeRedeclaration(
  5457. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  5458. IsExplicitSpecialization);
  5459. }
  5460. if (NewTemplate) {
  5461. if (NewVD->isInvalidDecl())
  5462. NewTemplate->setInvalidDecl();
  5463. ActOnDocumentableDecl(NewTemplate);
  5464. return NewTemplate;
  5465. }
  5466. return NewVD;
  5467. }
  5468. /// \brief Diagnose variable or built-in function shadowing. Implements
  5469. /// -Wshadow.
  5470. ///
  5471. /// This method is called whenever a VarDecl is added to a "useful"
  5472. /// scope.
  5473. ///
  5474. /// \param S the scope in which the shadowing name is being declared
  5475. /// \param R the lookup of the name
  5476. ///
  5477. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  5478. // Return if warning is ignored.
  5479. if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
  5480. return;
  5481. // Don't diagnose declarations at file scope.
  5482. if (D->hasGlobalStorage())
  5483. return;
  5484. DeclContext *NewDC = D->getDeclContext();
  5485. // Only diagnose if we're shadowing an unambiguous field or variable.
  5486. if (R.getResultKind() != LookupResult::Found)
  5487. return;
  5488. NamedDecl* ShadowedDecl = R.getFoundDecl();
  5489. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  5490. return;
  5491. // Fields are not shadowed by variables in C++ static methods.
  5492. if (isa<FieldDecl>(ShadowedDecl))
  5493. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  5494. if (MD->isStatic())
  5495. return;
  5496. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  5497. if (shadowedVar->isExternC()) {
  5498. // For shadowing external vars, make sure that we point to the global
  5499. // declaration, not a locally scoped extern declaration.
  5500. for (auto I : shadowedVar->redecls())
  5501. if (I->isFileVarDecl()) {
  5502. ShadowedDecl = I;
  5503. break;
  5504. }
  5505. }
  5506. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  5507. // Only warn about certain kinds of shadowing for class members.
  5508. if (NewDC && NewDC->isRecord()) {
  5509. // In particular, don't warn about shadowing non-class members.
  5510. if (!OldDC->isRecord())
  5511. return;
  5512. // TODO: should we warn about static data members shadowing
  5513. // static data members from base classes?
  5514. // TODO: don't diagnose for inaccessible shadowed members.
  5515. // This is hard to do perfectly because we might friend the
  5516. // shadowing context, but that's just a false negative.
  5517. }
  5518. // Determine what kind of declaration we're shadowing.
  5519. unsigned Kind;
  5520. if (isa<RecordDecl>(OldDC)) {
  5521. if (isa<FieldDecl>(ShadowedDecl))
  5522. Kind = 3; // field
  5523. else
  5524. Kind = 2; // static data member
  5525. } else if (OldDC->isFileContext())
  5526. Kind = 1; // global
  5527. else
  5528. Kind = 0; // local
  5529. DeclarationName Name = R.getLookupName();
  5530. // Emit warning and note.
  5531. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  5532. return;
  5533. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  5534. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  5535. }
  5536. /// \brief Check -Wshadow without the advantage of a previous lookup.
  5537. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  5538. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  5539. return;
  5540. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  5541. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  5542. LookupName(R, S);
  5543. CheckShadow(S, D, R);
  5544. }
  5545. /// Check for conflict between this global or extern "C" declaration and
  5546. /// previous global or extern "C" declarations. This is only used in C++.
  5547. template<typename T>
  5548. static bool checkGlobalOrExternCConflict(
  5549. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  5550. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  5551. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  5552. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  5553. // The common case: this global doesn't conflict with any extern "C"
  5554. // declaration.
  5555. return false;
  5556. }
  5557. if (Prev) {
  5558. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  5559. // Both the old and new declarations have C language linkage. This is a
  5560. // redeclaration.
  5561. Previous.clear();
  5562. Previous.addDecl(Prev);
  5563. return true;
  5564. }
  5565. // This is a global, non-extern "C" declaration, and there is a previous
  5566. // non-global extern "C" declaration. Diagnose if this is a variable
  5567. // declaration.
  5568. if (!isa<VarDecl>(ND))
  5569. return false;
  5570. } else {
  5571. // The declaration is extern "C". Check for any declaration in the
  5572. // translation unit which might conflict.
  5573. if (IsGlobal) {
  5574. // We have already performed the lookup into the translation unit.
  5575. IsGlobal = false;
  5576. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  5577. I != E; ++I) {
  5578. if (isa<VarDecl>(*I)) {
  5579. Prev = *I;
  5580. break;
  5581. }
  5582. }
  5583. } else {
  5584. DeclContext::lookup_result R =
  5585. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  5586. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  5587. I != E; ++I) {
  5588. if (isa<VarDecl>(*I)) {
  5589. Prev = *I;
  5590. break;
  5591. }
  5592. // FIXME: If we have any other entity with this name in global scope,
  5593. // the declaration is ill-formed, but that is a defect: it breaks the
  5594. // 'stat' hack, for instance. Only variables can have mangled name
  5595. // clashes with extern "C" declarations, so only they deserve a
  5596. // diagnostic.
  5597. }
  5598. }
  5599. if (!Prev)
  5600. return false;
  5601. }
  5602. // Use the first declaration's location to ensure we point at something which
  5603. // is lexically inside an extern "C" linkage-spec.
  5604. assert(Prev && "should have found a previous declaration to diagnose");
  5605. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  5606. Prev = FD->getFirstDecl();
  5607. else
  5608. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  5609. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  5610. << IsGlobal << ND;
  5611. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  5612. << IsGlobal;
  5613. return false;
  5614. }
  5615. /// Apply special rules for handling extern "C" declarations. Returns \c true
  5616. /// if we have found that this is a redeclaration of some prior entity.
  5617. ///
  5618. /// Per C++ [dcl.link]p6:
  5619. /// Two declarations [for a function or variable] with C language linkage
  5620. /// with the same name that appear in different scopes refer to the same
  5621. /// [entity]. An entity with C language linkage shall not be declared with
  5622. /// the same name as an entity in global scope.
  5623. template<typename T>
  5624. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  5625. LookupResult &Previous) {
  5626. if (!S.getLangOpts().CPlusPlus) {
  5627. // In C, when declaring a global variable, look for a corresponding 'extern'
  5628. // variable declared in function scope. We don't need this in C++, because
  5629. // we find local extern decls in the surrounding file-scope DeclContext.
  5630. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5631. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  5632. Previous.clear();
  5633. Previous.addDecl(Prev);
  5634. return true;
  5635. }
  5636. }
  5637. return false;
  5638. }
  5639. // A declaration in the translation unit can conflict with an extern "C"
  5640. // declaration.
  5641. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  5642. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  5643. // An extern "C" declaration can conflict with a declaration in the
  5644. // translation unit or can be a redeclaration of an extern "C" declaration
  5645. // in another scope.
  5646. if (isIncompleteDeclExternC(S,ND))
  5647. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  5648. // Neither global nor extern "C": nothing to do.
  5649. return false;
  5650. }
  5651. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  5652. // If the decl is already known invalid, don't check it.
  5653. if (NewVD->isInvalidDecl())
  5654. return;
  5655. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  5656. QualType T = TInfo->getType();
  5657. // Defer checking an 'auto' type until its initializer is attached.
  5658. if (T->isUndeducedType())
  5659. return;
  5660. if (NewVD->hasAttrs())
  5661. CheckAlignasUnderalignment(NewVD);
  5662. if (T->isObjCObjectType()) {
  5663. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  5664. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  5665. T = Context.getObjCObjectPointerType(T);
  5666. NewVD->setType(T);
  5667. }
  5668. // Emit an error if an address space was applied to decl with local storage.
  5669. // This includes arrays of objects with address space qualifiers, but not
  5670. // automatic variables that point to other address spaces.
  5671. // ISO/IEC TR 18037 S5.1.2
  5672. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  5673. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  5674. NewVD->setInvalidDecl();
  5675. return;
  5676. }
  5677. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  5678. // __constant address space.
  5679. if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
  5680. && T.getAddressSpace() != LangAS::opencl_constant
  5681. && !T->isSamplerT()){
  5682. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
  5683. NewVD->setInvalidDecl();
  5684. return;
  5685. }
  5686. // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
  5687. // scope.
  5688. if ((getLangOpts().OpenCLVersion >= 120)
  5689. && NewVD->isStaticLocal()) {
  5690. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  5691. NewVD->setInvalidDecl();
  5692. return;
  5693. }
  5694. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  5695. && !NewVD->hasAttr<BlocksAttr>()) {
  5696. if (getLangOpts().getGC() != LangOptions::NonGC)
  5697. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  5698. else {
  5699. assert(!getLangOpts().ObjCAutoRefCount);
  5700. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  5701. }
  5702. }
  5703. bool isVM = T->isVariablyModifiedType();
  5704. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  5705. NewVD->hasAttr<BlocksAttr>())
  5706. getCurFunction()->setHasBranchProtectedScope();
  5707. if ((isVM && NewVD->hasLinkage()) ||
  5708. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  5709. bool SizeIsNegative;
  5710. llvm::APSInt Oversized;
  5711. TypeSourceInfo *FixedTInfo =
  5712. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5713. SizeIsNegative, Oversized);
  5714. if (!FixedTInfo && T->isVariableArrayType()) {
  5715. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  5716. // FIXME: This won't give the correct result for
  5717. // int a[10][n];
  5718. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  5719. if (NewVD->isFileVarDecl())
  5720. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  5721. << SizeRange;
  5722. else if (NewVD->isStaticLocal())
  5723. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  5724. << SizeRange;
  5725. else
  5726. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  5727. << SizeRange;
  5728. NewVD->setInvalidDecl();
  5729. return;
  5730. }
  5731. if (!FixedTInfo) {
  5732. if (NewVD->isFileVarDecl())
  5733. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  5734. else
  5735. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  5736. NewVD->setInvalidDecl();
  5737. return;
  5738. }
  5739. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  5740. NewVD->setType(FixedTInfo->getType());
  5741. NewVD->setTypeSourceInfo(FixedTInfo);
  5742. }
  5743. if (T->isVoidType()) {
  5744. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  5745. // of objects and functions.
  5746. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  5747. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  5748. << T;
  5749. NewVD->setInvalidDecl();
  5750. return;
  5751. }
  5752. }
  5753. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  5754. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  5755. NewVD->setInvalidDecl();
  5756. return;
  5757. }
  5758. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  5759. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  5760. NewVD->setInvalidDecl();
  5761. return;
  5762. }
  5763. if (NewVD->isConstexpr() && !T->isDependentType() &&
  5764. RequireLiteralType(NewVD->getLocation(), T,
  5765. diag::err_constexpr_var_non_literal)) {
  5766. NewVD->setInvalidDecl();
  5767. return;
  5768. }
  5769. }
  5770. /// \brief Perform semantic checking on a newly-created variable
  5771. /// declaration.
  5772. ///
  5773. /// This routine performs all of the type-checking required for a
  5774. /// variable declaration once it has been built. It is used both to
  5775. /// check variables after they have been parsed and their declarators
  5776. /// have been translated into a declaration, and to check variables
  5777. /// that have been instantiated from a template.
  5778. ///
  5779. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  5780. ///
  5781. /// Returns true if the variable declaration is a redeclaration.
  5782. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous, ShadowMergeState MergeState) { // HLSL Change - add merge state
  5783. CheckVariableDeclarationType(NewVD);
  5784. // If the decl is already known invalid, don't check it.
  5785. if (NewVD->isInvalidDecl())
  5786. return false;
  5787. // If we did not find anything by this name, look for a non-visible
  5788. // extern "C" declaration with the same name.
  5789. if (Previous.empty() &&
  5790. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  5791. Previous.setShadowed();
  5792. // Filter out any non-conflicting previous declarations.
  5793. filterNonConflictingPreviousDecls(*this, NewVD, Previous);
  5794. if (!Previous.empty()) {
  5795. MergeVarDecl(NewVD, Previous, MergeState); // HLSL Change - add merge state
  5796. return true;
  5797. }
  5798. return false;
  5799. }
  5800. /// \brief Data used with FindOverriddenMethod
  5801. struct FindOverriddenMethodData {
  5802. Sema *S;
  5803. CXXMethodDecl *Method;
  5804. };
  5805. /// \brief Member lookup function that determines whether a given C++
  5806. /// method overrides a method in a base class, to be used with
  5807. /// CXXRecordDecl::lookupInBases().
  5808. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  5809. CXXBasePath &Path,
  5810. void *UserData) {
  5811. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  5812. FindOverriddenMethodData *Data
  5813. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  5814. DeclarationName Name = Data->Method->getDeclName();
  5815. // FIXME: Do we care about other names here too?
  5816. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  5817. // We really want to find the base class destructor here.
  5818. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  5819. CanQualType CT = Data->S->Context.getCanonicalType(T);
  5820. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  5821. }
  5822. for (Path.Decls = BaseRecord->lookup(Name);
  5823. !Path.Decls.empty();
  5824. Path.Decls = Path.Decls.slice(1)) {
  5825. NamedDecl *D = Path.Decls.front();
  5826. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  5827. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  5828. return true;
  5829. }
  5830. }
  5831. return false;
  5832. }
  5833. namespace {
  5834. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  5835. }
  5836. /// \brief Report an error regarding overriding, along with any relevant
  5837. /// overriden methods.
  5838. ///
  5839. /// \param DiagID the primary error to report.
  5840. /// \param MD the overriding method.
  5841. /// \param OEK which overrides to include as notes.
  5842. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  5843. OverrideErrorKind OEK = OEK_All) {
  5844. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  5845. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5846. E = MD->end_overridden_methods();
  5847. I != E; ++I) {
  5848. // This check (& the OEK parameter) could be replaced by a predicate, but
  5849. // without lambdas that would be overkill. This is still nicer than writing
  5850. // out the diag loop 3 times.
  5851. if ((OEK == OEK_All) ||
  5852. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  5853. (OEK == OEK_Deleted && (*I)->isDeleted()))
  5854. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  5855. }
  5856. }
  5857. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  5858. /// and if so, check that it's a valid override and remember it.
  5859. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  5860. // Look for methods in base classes that this method might override.
  5861. CXXBasePaths Paths;
  5862. FindOverriddenMethodData Data;
  5863. Data.Method = MD;
  5864. Data.S = this;
  5865. bool hasDeletedOverridenMethods = false;
  5866. bool hasNonDeletedOverridenMethods = false;
  5867. bool AddedAny = false;
  5868. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  5869. for (auto *I : Paths.found_decls()) {
  5870. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  5871. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  5872. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  5873. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  5874. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  5875. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  5876. hasDeletedOverridenMethods |= OldMD->isDeleted();
  5877. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  5878. AddedAny = true;
  5879. }
  5880. }
  5881. }
  5882. }
  5883. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  5884. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  5885. }
  5886. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  5887. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  5888. }
  5889. return AddedAny;
  5890. }
  5891. namespace {
  5892. // Struct for holding all of the extra arguments needed by
  5893. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  5894. struct ActOnFDArgs {
  5895. Scope *S;
  5896. Declarator &D;
  5897. MultiTemplateParamsArg TemplateParamLists;
  5898. bool AddToScope;
  5899. };
  5900. }
  5901. namespace {
  5902. // Callback to only accept typo corrections that have a non-zero edit distance.
  5903. // Also only accept corrections that have the same parent decl.
  5904. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  5905. public:
  5906. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  5907. CXXRecordDecl *Parent)
  5908. : Context(Context), OriginalFD(TypoFD),
  5909. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  5910. bool ValidateCandidate(const TypoCorrection &candidate) override {
  5911. if (candidate.getEditDistance() == 0)
  5912. return false;
  5913. SmallVector<unsigned, 1> MismatchedParams;
  5914. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  5915. CDeclEnd = candidate.end();
  5916. CDecl != CDeclEnd; ++CDecl) {
  5917. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  5918. if (FD && !FD->hasBody() &&
  5919. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  5920. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  5921. CXXRecordDecl *Parent = MD->getParent();
  5922. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  5923. return true;
  5924. } else if (!ExpectedParent) {
  5925. return true;
  5926. }
  5927. }
  5928. }
  5929. return false;
  5930. }
  5931. private:
  5932. ASTContext &Context;
  5933. FunctionDecl *OriginalFD;
  5934. CXXRecordDecl *ExpectedParent;
  5935. };
  5936. }
  5937. /// \brief Generate diagnostics for an invalid function redeclaration.
  5938. ///
  5939. /// This routine handles generating the diagnostic messages for an invalid
  5940. /// function redeclaration, including finding possible similar declarations
  5941. /// or performing typo correction if there are no previous declarations with
  5942. /// the same name.
  5943. ///
  5944. /// Returns a NamedDecl iff typo correction was performed and substituting in
  5945. /// the new declaration name does not cause new errors.
  5946. static NamedDecl *DiagnoseInvalidRedeclaration(
  5947. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  5948. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  5949. DeclarationName Name = NewFD->getDeclName();
  5950. DeclContext *NewDC = NewFD->getDeclContext();
  5951. SmallVector<unsigned, 1> MismatchedParams;
  5952. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  5953. TypoCorrection Correction;
  5954. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  5955. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  5956. : diag::err_member_decl_does_not_match;
  5957. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  5958. IsLocalFriend ? Sema::LookupLocalFriendName
  5959. : Sema::LookupOrdinaryName,
  5960. Sema::ForRedeclaration);
  5961. NewFD->setInvalidDecl();
  5962. if (IsLocalFriend)
  5963. SemaRef.LookupName(Prev, S);
  5964. else
  5965. SemaRef.LookupQualifiedName(Prev, NewDC);
  5966. assert(!Prev.isAmbiguous() &&
  5967. "Cannot have an ambiguity in previous-declaration lookup");
  5968. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  5969. if (!Prev.empty()) {
  5970. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  5971. Func != FuncEnd; ++Func) {
  5972. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  5973. if (FD &&
  5974. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  5975. // Add 1 to the index so that 0 can mean the mismatch didn't
  5976. // involve a parameter
  5977. unsigned ParamNum =
  5978. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  5979. NearMatches.push_back(std::make_pair(FD, ParamNum));
  5980. }
  5981. }
  5982. // If the qualified name lookup yielded nothing, try typo correction
  5983. } else if ((Correction = SemaRef.CorrectTypo(
  5984. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  5985. &ExtraArgs.D.getCXXScopeSpec(),
  5986. llvm::make_unique<DifferentNameValidatorCCC>(
  5987. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  5988. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  5989. // Set up everything for the call to ActOnFunctionDeclarator
  5990. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  5991. ExtraArgs.D.getIdentifierLoc());
  5992. Previous.clear();
  5993. Previous.setLookupName(Correction.getCorrection());
  5994. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  5995. CDeclEnd = Correction.end();
  5996. CDecl != CDeclEnd; ++CDecl) {
  5997. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  5998. if (FD && !FD->hasBody() &&
  5999. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6000. Previous.addDecl(FD);
  6001. }
  6002. }
  6003. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6004. NamedDecl *Result;
  6005. // Retry building the function declaration with the new previous
  6006. // declarations, and with errors suppressed.
  6007. {
  6008. // Trap errors.
  6009. Sema::SFINAETrap Trap(SemaRef);
  6010. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6011. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6012. // eliminate the need for the parameter pack ExtraArgs.
  6013. Result = SemaRef.ActOnFunctionDeclarator(
  6014. ExtraArgs.S, ExtraArgs.D,
  6015. Correction.getCorrectionDecl()->getDeclContext(),
  6016. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6017. ExtraArgs.AddToScope);
  6018. if (Trap.hasErrorOccurred())
  6019. Result = nullptr;
  6020. }
  6021. if (Result) {
  6022. // Determine which correction we picked.
  6023. Decl *Canonical = Result->getCanonicalDecl();
  6024. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6025. I != E; ++I)
  6026. if ((*I)->getCanonicalDecl() == Canonical)
  6027. Correction.setCorrectionDecl(*I);
  6028. SemaRef.diagnoseTypo(
  6029. Correction,
  6030. SemaRef.PDiag(IsLocalFriend
  6031. ? diag::err_no_matching_local_friend_suggest
  6032. : diag::err_member_decl_does_not_match_suggest)
  6033. << Name << NewDC << IsDefinition);
  6034. return Result;
  6035. }
  6036. // Pretend the typo correction never occurred
  6037. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6038. ExtraArgs.D.getIdentifierLoc());
  6039. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6040. Previous.clear();
  6041. Previous.setLookupName(Name);
  6042. }
  6043. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6044. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6045. bool NewFDisConst = false;
  6046. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6047. NewFDisConst = NewMD->isConst();
  6048. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6049. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6050. NearMatch != NearMatchEnd; ++NearMatch) {
  6051. FunctionDecl *FD = NearMatch->first;
  6052. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6053. bool FDisConst = MD && MD->isConst();
  6054. bool IsMember = MD || !IsLocalFriend;
  6055. // FIXME: These notes are poorly worded for the local friend case.
  6056. if (unsigned Idx = NearMatch->second) {
  6057. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6058. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6059. if (Loc.isInvalid()) Loc = FD->getLocation();
  6060. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6061. : diag::note_local_decl_close_param_match)
  6062. << Idx << FDParam->getType()
  6063. << NewFD->getParamDecl(Idx - 1)->getType();
  6064. } else if (FDisConst != NewFDisConst) {
  6065. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6066. << NewFDisConst << FD->getSourceRange().getEnd();
  6067. } else
  6068. SemaRef.Diag(FD->getLocation(),
  6069. IsMember ? diag::note_member_def_close_match
  6070. : diag::note_local_decl_close_match);
  6071. }
  6072. return nullptr;
  6073. }
  6074. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6075. switch (D.getDeclSpec().getStorageClassSpec()) {
  6076. default: llvm_unreachable("Unknown storage class!");
  6077. case DeclSpec::SCS_auto:
  6078. case DeclSpec::SCS_register:
  6079. case DeclSpec::SCS_mutable:
  6080. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6081. diag::err_typecheck_sclass_func);
  6082. D.setInvalidType();
  6083. break;
  6084. case DeclSpec::SCS_unspecified: break;
  6085. case DeclSpec::SCS_extern:
  6086. if (D.getDeclSpec().isExternInLinkageSpec())
  6087. return SC_None;
  6088. return SC_Extern;
  6089. case DeclSpec::SCS_static: {
  6090. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6091. // C99 6.7.1p5:
  6092. // The declaration of an identifier for a function that has
  6093. // block scope shall have no explicit storage-class specifier
  6094. // other than extern
  6095. // See also (C++ [dcl.stc]p4).
  6096. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6097. diag::err_static_block_func);
  6098. break;
  6099. } else
  6100. return SC_Static;
  6101. }
  6102. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6103. }
  6104. // No explicit storage class has already been returned
  6105. return SC_None;
  6106. }
  6107. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6108. DeclContext *DC, QualType &R,
  6109. TypeSourceInfo *TInfo,
  6110. StorageClass SC,
  6111. bool &IsVirtualOkay) {
  6112. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6113. DeclarationName Name = NameInfo.getName();
  6114. FunctionDecl *NewFD = nullptr;
  6115. bool isInline = D.getDeclSpec().isInlineSpecified();
  6116. if (!SemaRef.getLangOpts().CPlusPlus) {
  6117. // Determine whether the function was written with a
  6118. // prototype. This true when:
  6119. // - there is a prototype in the declarator, or
  6120. // - the type R of the function is some kind of typedef or other reference
  6121. // to a type name (which eventually refers to a function type).
  6122. bool HasPrototype =
  6123. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  6124. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  6125. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  6126. D.getLocStart(), NameInfo, R,
  6127. TInfo, SC, isInline,
  6128. HasPrototype, false);
  6129. if (D.isInvalidType())
  6130. NewFD->setInvalidDecl();
  6131. return NewFD;
  6132. }
  6133. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6134. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6135. // Check that the return type is not an abstract class type.
  6136. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6137. // the class has been completely parsed.
  6138. if (!DC->isRecord() &&
  6139. SemaRef.RequireNonAbstractType(
  6140. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  6141. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  6142. D.setInvalidType();
  6143. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  6144. // This is a C++ constructor declaration.
  6145. assert(DC->isRecord() &&
  6146. "Constructors can only be declared in a member context");
  6147. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  6148. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6149. D.getLocStart(), NameInfo,
  6150. R, TInfo, isExplicit, isInline,
  6151. /*isImplicitlyDeclared=*/false,
  6152. isConstexpr);
  6153. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6154. // This is a C++ destructor declaration.
  6155. if (DC->isRecord()) {
  6156. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  6157. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  6158. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  6159. SemaRef.Context, Record,
  6160. D.getLocStart(),
  6161. NameInfo, R, TInfo, isInline,
  6162. /*isImplicitlyDeclared=*/false);
  6163. // If the class is complete, then we now create the implicit exception
  6164. // specification. If the class is incomplete or dependent, we can't do
  6165. // it yet.
  6166. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  6167. Record->getDefinition() && !Record->isBeingDefined() &&
  6168. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  6169. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  6170. }
  6171. IsVirtualOkay = true;
  6172. return NewDD;
  6173. } else {
  6174. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  6175. D.setInvalidType();
  6176. // Create a FunctionDecl to satisfy the function definition parsing
  6177. // code path.
  6178. return FunctionDecl::Create(SemaRef.Context, DC,
  6179. D.getLocStart(),
  6180. D.getIdentifierLoc(), Name, R, TInfo,
  6181. SC, isInline,
  6182. /*hasPrototype=*/true, isConstexpr);
  6183. }
  6184. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  6185. if (!DC->isRecord()) {
  6186. SemaRef.Diag(D.getIdentifierLoc(),
  6187. diag::err_conv_function_not_member);
  6188. return nullptr;
  6189. }
  6190. SemaRef.CheckConversionDeclarator(D, R, SC);
  6191. IsVirtualOkay = true;
  6192. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6193. D.getLocStart(), NameInfo,
  6194. R, TInfo, isInline, isExplicit,
  6195. isConstexpr, SourceLocation());
  6196. } else if (DC->isRecord()) {
  6197. // If the name of the function is the same as the name of the record,
  6198. // then this must be an invalid constructor that has a return type.
  6199. // (The parser checks for a return type and makes the declarator a
  6200. // constructor if it has no return type).
  6201. if (Name.getAsIdentifierInfo() &&
  6202. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  6203. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  6204. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6205. << SourceRange(D.getIdentifierLoc());
  6206. return nullptr;
  6207. }
  6208. // This is a C++ method declaration.
  6209. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  6210. cast<CXXRecordDecl>(DC),
  6211. D.getLocStart(), NameInfo, R,
  6212. TInfo, SC, isInline,
  6213. isConstexpr, SourceLocation());
  6214. IsVirtualOkay = !Ret->isStatic();
  6215. return Ret;
  6216. } else {
  6217. bool isFriend =
  6218. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  6219. if (!isFriend && SemaRef.CurContext->isRecord())
  6220. return nullptr;
  6221. // Determine whether the function was written with a
  6222. // prototype. This true when:
  6223. // - we're in C++ (where every function has a prototype),
  6224. return FunctionDecl::Create(SemaRef.Context, DC,
  6225. D.getLocStart(),
  6226. NameInfo, R, TInfo, SC, isInline,
  6227. true/*HasPrototype*/, isConstexpr);
  6228. }
  6229. }
  6230. enum OpenCLParamType {
  6231. ValidKernelParam,
  6232. PtrPtrKernelParam,
  6233. PtrKernelParam,
  6234. PrivatePtrKernelParam,
  6235. InvalidKernelParam,
  6236. RecordKernelParam
  6237. };
  6238. static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
  6239. if (PT->isPointerType()) {
  6240. QualType PointeeType = PT->getPointeeType();
  6241. if (PointeeType->isPointerType())
  6242. return PtrPtrKernelParam;
  6243. return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
  6244. : PtrKernelParam;
  6245. }
  6246. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  6247. // be used as builtin types.
  6248. if (PT->isImageType())
  6249. return PtrKernelParam;
  6250. if (PT->isBooleanType())
  6251. return InvalidKernelParam;
  6252. if (PT->isEventT())
  6253. return InvalidKernelParam;
  6254. if (PT->isHalfType())
  6255. return InvalidKernelParam;
  6256. if (PT->isRecordType())
  6257. return RecordKernelParam;
  6258. return ValidKernelParam;
  6259. }
  6260. static void checkIsValidOpenCLKernelParameter(
  6261. Sema &S,
  6262. Declarator &D,
  6263. ParmVarDecl *Param,
  6264. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  6265. QualType PT = Param->getType();
  6266. // Cache the valid types we encounter to avoid rechecking structs that are
  6267. // used again
  6268. if (ValidTypes.count(PT.getTypePtr()))
  6269. return;
  6270. switch (getOpenCLKernelParameterType(PT)) {
  6271. case PtrPtrKernelParam:
  6272. // OpenCL v1.2 s6.9.a:
  6273. // A kernel function argument cannot be declared as a
  6274. // pointer to a pointer type.
  6275. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  6276. D.setInvalidType();
  6277. return;
  6278. case PrivatePtrKernelParam:
  6279. // OpenCL v1.2 s6.9.a:
  6280. // A kernel function argument cannot be declared as a
  6281. // pointer to the private address space.
  6282. S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
  6283. D.setInvalidType();
  6284. return;
  6285. // OpenCL v1.2 s6.9.k:
  6286. // Arguments to kernel functions in a program cannot be declared with the
  6287. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  6288. // uintptr_t or a struct and/or union that contain fields declared to be
  6289. // one of these built-in scalar types.
  6290. case InvalidKernelParam:
  6291. // OpenCL v1.2 s6.8 n:
  6292. // A kernel function argument cannot be declared
  6293. // of event_t type.
  6294. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6295. D.setInvalidType();
  6296. return;
  6297. case PtrKernelParam:
  6298. case ValidKernelParam:
  6299. ValidTypes.insert(PT.getTypePtr());
  6300. return;
  6301. case RecordKernelParam:
  6302. break;
  6303. }
  6304. // Track nested structs we will inspect
  6305. SmallVector<const Decl *, 4> VisitStack;
  6306. // Track where we are in the nested structs. Items will migrate from
  6307. // VisitStack to HistoryStack as we do the DFS for bad field.
  6308. SmallVector<const FieldDecl *, 4> HistoryStack;
  6309. HistoryStack.push_back(nullptr);
  6310. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  6311. VisitStack.push_back(PD);
  6312. assert(VisitStack.back() && "First decl null?");
  6313. do {
  6314. const Decl *Next = VisitStack.pop_back_val();
  6315. if (!Next) {
  6316. assert(!HistoryStack.empty());
  6317. // Found a marker, we have gone up a level
  6318. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  6319. ValidTypes.insert(Hist->getType().getTypePtr());
  6320. continue;
  6321. }
  6322. // Adds everything except the original parameter declaration (which is not a
  6323. // field itself) to the history stack.
  6324. const RecordDecl *RD;
  6325. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  6326. HistoryStack.push_back(Field);
  6327. RD = Field->getType()->castAs<RecordType>()->getDecl();
  6328. } else {
  6329. RD = cast<RecordDecl>(Next);
  6330. }
  6331. // Add a null marker so we know when we've gone back up a level
  6332. VisitStack.push_back(nullptr);
  6333. for (const auto *FD : RD->fields()) {
  6334. QualType QT = FD->getType();
  6335. if (ValidTypes.count(QT.getTypePtr()))
  6336. continue;
  6337. OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
  6338. if (ParamType == ValidKernelParam)
  6339. continue;
  6340. if (ParamType == RecordKernelParam) {
  6341. VisitStack.push_back(FD);
  6342. continue;
  6343. }
  6344. // OpenCL v1.2 s6.9.p:
  6345. // Arguments to kernel functions that are declared to be a struct or union
  6346. // do not allow OpenCL objects to be passed as elements of the struct or
  6347. // union.
  6348. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  6349. ParamType == PrivatePtrKernelParam) {
  6350. S.Diag(Param->getLocation(),
  6351. diag::err_record_with_pointers_kernel_param)
  6352. << PT->isUnionType()
  6353. << PT;
  6354. } else {
  6355. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6356. }
  6357. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  6358. << PD->getDeclName();
  6359. // We have an error, now let's go back up through history and show where
  6360. // the offending field came from
  6361. for (ArrayRef<const FieldDecl *>::const_iterator
  6362. I = HistoryStack.begin() + 1,
  6363. E = HistoryStack.end();
  6364. I != E; ++I) {
  6365. const FieldDecl *OuterField = *I;
  6366. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  6367. << OuterField->getType();
  6368. }
  6369. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  6370. << QT->isPointerType()
  6371. << QT;
  6372. D.setInvalidType();
  6373. return;
  6374. }
  6375. } while (!VisitStack.empty());
  6376. }
  6377. NamedDecl*
  6378. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  6379. TypeSourceInfo *TInfo, LookupResult &Previous,
  6380. MultiTemplateParamsArg TemplateParamLists,
  6381. bool &AddToScope) {
  6382. QualType R = TInfo->getType();
  6383. assert(R.getTypePtr()->isFunctionType());
  6384. // TODO: consider using NameInfo for diagnostic.
  6385. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  6386. DeclarationName Name = NameInfo.getName();
  6387. StorageClass SC = getFunctionStorageClass(*this, D);
  6388. // HLSL Change - reject 'extern' functions
  6389. if (getLangOpts().HLSL && SC == SC_Extern) {
  6390. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'" << "function";
  6391. }
  6392. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  6393. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6394. diag::err_invalid_thread)
  6395. << DeclSpec::getSpecifierName(TSCS);
  6396. if (D.isFirstDeclarationOfMember())
  6397. adjustMemberFunctionCC(R, D.isStaticMember());
  6398. bool isFriend = false;
  6399. FunctionTemplateDecl *FunctionTemplate = nullptr;
  6400. bool isExplicitSpecialization = false;
  6401. bool isFunctionTemplateSpecialization = false;
  6402. bool isDependentClassScopeExplicitSpecialization = false;
  6403. bool HasExplicitTemplateArgs = false;
  6404. TemplateArgumentListInfo TemplateArgs;
  6405. bool isVirtualOkay = false;
  6406. DeclContext *OriginalDC = DC;
  6407. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  6408. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  6409. isVirtualOkay);
  6410. if (!NewFD) return nullptr;
  6411. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  6412. NewFD->setTopLevelDeclInObjCContainer();
  6413. // Set the lexical context. If this is a function-scope declaration, or has a
  6414. // C++ scope specifier, or is the object of a friend declaration, the lexical
  6415. // context will be different from the semantic context.
  6416. NewFD->setLexicalDeclContext(CurContext);
  6417. if (IsLocalExternDecl)
  6418. NewFD->setLocalExternDecl();
  6419. if (getLangOpts().CPlusPlus) {
  6420. bool isInline = D.getDeclSpec().isInlineSpecified();
  6421. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  6422. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6423. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6424. isFriend = D.getDeclSpec().isFriendSpecified();
  6425. if (isFriend && !isInline && D.isFunctionDefinition()) {
  6426. // C++ [class.friend]p5
  6427. // A function can be defined in a friend declaration of a
  6428. // class . . . . Such a function is implicitly inline.
  6429. NewFD->setImplicitlyInline();
  6430. }
  6431. // If this is a method defined in an __interface, and is not a constructor
  6432. // or an overloaded operator, then set the pure flag (isVirtual will already
  6433. // return true).
  6434. if (const CXXRecordDecl *Parent =
  6435. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  6436. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  6437. NewFD->setPure(true);
  6438. // C++ [class.union]p2
  6439. // A union can have member functions, but not virtual functions.
  6440. if (isVirtual && Parent->isUnion())
  6441. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  6442. }
  6443. SetNestedNameSpecifier(NewFD, D);
  6444. isExplicitSpecialization = false;
  6445. isFunctionTemplateSpecialization = false;
  6446. if (D.isInvalidType())
  6447. NewFD->setInvalidDecl();
  6448. // Match up the template parameter lists with the scope specifier, then
  6449. // determine whether we have a template or a template specialization.
  6450. bool Invalid = false;
  6451. if (TemplateParameterList *TemplateParams =
  6452. MatchTemplateParametersToScopeSpecifier(
  6453. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  6454. D.getCXXScopeSpec(),
  6455. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  6456. ? D.getName().TemplateId
  6457. : nullptr,
  6458. TemplateParamLists, isFriend, isExplicitSpecialization,
  6459. Invalid)) {
  6460. if (TemplateParams->size() > 0) {
  6461. // This is a function template
  6462. // Check that we can declare a template here.
  6463. if (CheckTemplateDeclScope(S, TemplateParams))
  6464. NewFD->setInvalidDecl();
  6465. // A destructor cannot be a template.
  6466. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6467. Diag(NewFD->getLocation(), diag::err_destructor_template);
  6468. NewFD->setInvalidDecl();
  6469. }
  6470. // If we're adding a template to a dependent context, we may need to
  6471. // rebuilding some of the types used within the template parameter list,
  6472. // now that we know what the current instantiation is.
  6473. if (DC->isDependentContext()) {
  6474. ContextRAII SavedContext(*this, DC);
  6475. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  6476. Invalid = true;
  6477. }
  6478. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  6479. NewFD->getLocation(),
  6480. Name, TemplateParams,
  6481. NewFD);
  6482. FunctionTemplate->setLexicalDeclContext(CurContext);
  6483. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  6484. // For source fidelity, store the other template param lists.
  6485. if (TemplateParamLists.size() > 1) {
  6486. NewFD->setTemplateParameterListsInfo(Context,
  6487. TemplateParamLists.size() - 1,
  6488. TemplateParamLists.data());
  6489. }
  6490. } else {
  6491. // This is a function template specialization.
  6492. isFunctionTemplateSpecialization = true;
  6493. // For source fidelity, store all the template param lists.
  6494. if (TemplateParamLists.size() > 0)
  6495. NewFD->setTemplateParameterListsInfo(Context,
  6496. TemplateParamLists.size(),
  6497. TemplateParamLists.data());
  6498. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  6499. if (isFriend) {
  6500. // We want to remove the "template<>", found here.
  6501. SourceRange RemoveRange = TemplateParams->getSourceRange();
  6502. // If we remove the template<> and the name is not a
  6503. // template-id, we're actually silently creating a problem:
  6504. // the friend declaration will refer to an untemplated decl,
  6505. // and clearly the user wants a template specialization. So
  6506. // we need to insert '<>' after the name.
  6507. SourceLocation InsertLoc;
  6508. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  6509. InsertLoc = D.getName().getSourceRange().getEnd();
  6510. InsertLoc = getLocForEndOfToken(InsertLoc);
  6511. }
  6512. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  6513. << Name << RemoveRange
  6514. << FixItHint::CreateRemoval(RemoveRange)
  6515. << FixItHint::CreateInsertion(InsertLoc, "<>");
  6516. }
  6517. }
  6518. }
  6519. else {
  6520. // All template param lists were matched against the scope specifier:
  6521. // this is NOT (an explicit specialization of) a template.
  6522. if (TemplateParamLists.size() > 0)
  6523. // For source fidelity, store all the template param lists.
  6524. NewFD->setTemplateParameterListsInfo(Context,
  6525. TemplateParamLists.size(),
  6526. TemplateParamLists.data());
  6527. }
  6528. if (Invalid) {
  6529. NewFD->setInvalidDecl();
  6530. if (FunctionTemplate)
  6531. FunctionTemplate->setInvalidDecl();
  6532. }
  6533. // C++ [dcl.fct.spec]p5:
  6534. // The virtual specifier shall only be used in declarations of
  6535. // nonstatic class member functions that appear within a
  6536. // member-specification of a class declaration; see 10.3.
  6537. //
  6538. if (isVirtual && !NewFD->isInvalidDecl()) {
  6539. if (!isVirtualOkay) {
  6540. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6541. diag::err_virtual_non_function);
  6542. } else if (!CurContext->isRecord()) {
  6543. // 'virtual' was specified outside of the class.
  6544. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6545. diag::err_virtual_out_of_class)
  6546. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  6547. } else if (NewFD->getDescribedFunctionTemplate()) {
  6548. // C++ [temp.mem]p3:
  6549. // A member function template shall not be virtual.
  6550. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6551. diag::err_virtual_member_function_template)
  6552. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  6553. } else {
  6554. // Okay: Add virtual to the method.
  6555. NewFD->setVirtualAsWritten(true);
  6556. }
  6557. if (getLangOpts().CPlusPlus14 &&
  6558. NewFD->getReturnType()->isUndeducedType())
  6559. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  6560. }
  6561. if (getLangOpts().CPlusPlus14 &&
  6562. (NewFD->isDependentContext() ||
  6563. (isFriend && CurContext->isDependentContext())) &&
  6564. NewFD->getReturnType()->isUndeducedType()) {
  6565. // If the function template is referenced directly (for instance, as a
  6566. // member of the current instantiation), pretend it has a dependent type.
  6567. // This is not really justified by the standard, but is the only sane
  6568. // thing to do.
  6569. // FIXME: For a friend function, we have not marked the function as being
  6570. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  6571. const FunctionProtoType *FPT =
  6572. NewFD->getType()->castAs<FunctionProtoType>();
  6573. QualType Result =
  6574. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  6575. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  6576. FPT->getExtProtoInfo(), FPT->getParamMods())); // HLSL Change - add param mods
  6577. }
  6578. // C++ [dcl.fct.spec]p3:
  6579. // The inline specifier shall not appear on a block scope function
  6580. // declaration.
  6581. if (isInline && !NewFD->isInvalidDecl()) {
  6582. if (CurContext->isFunctionOrMethod()) {
  6583. // 'inline' is not allowed on block scope function declaration.
  6584. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6585. diag::err_inline_declaration_block_scope) << Name
  6586. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6587. }
  6588. }
  6589. // C++ [dcl.fct.spec]p6:
  6590. // The explicit specifier shall be used only in the declaration of a
  6591. // constructor or conversion function within its class definition;
  6592. // see 12.3.1 and 12.3.2.
  6593. if (isExplicit && !NewFD->isInvalidDecl()) {
  6594. if (!CurContext->isRecord()) {
  6595. // 'explicit' was specified outside of the class.
  6596. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6597. diag::err_explicit_out_of_class)
  6598. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6599. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  6600. !isa<CXXConversionDecl>(NewFD)) {
  6601. // 'explicit' was specified on a function that wasn't a constructor
  6602. // or conversion function.
  6603. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6604. diag::err_explicit_non_ctor_or_conv_function)
  6605. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6606. }
  6607. }
  6608. if (isConstexpr) {
  6609. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  6610. // are implicitly inline.
  6611. NewFD->setImplicitlyInline();
  6612. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  6613. // be either constructors or to return a literal type. Therefore,
  6614. // destructors cannot be declared constexpr.
  6615. if (isa<CXXDestructorDecl>(NewFD))
  6616. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  6617. }
  6618. // If __module_private__ was specified, mark the function accordingly.
  6619. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6620. if (isFunctionTemplateSpecialization) {
  6621. SourceLocation ModulePrivateLoc
  6622. = D.getDeclSpec().getModulePrivateSpecLoc();
  6623. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  6624. << 0
  6625. << FixItHint::CreateRemoval(ModulePrivateLoc);
  6626. } else {
  6627. NewFD->setModulePrivate();
  6628. if (FunctionTemplate)
  6629. FunctionTemplate->setModulePrivate();
  6630. }
  6631. }
  6632. if (isFriend) {
  6633. if (FunctionTemplate) {
  6634. FunctionTemplate->setObjectOfFriendDecl();
  6635. FunctionTemplate->setAccess(AS_public);
  6636. }
  6637. NewFD->setObjectOfFriendDecl();
  6638. NewFD->setAccess(AS_public);
  6639. }
  6640. // If a function is defined as defaulted or deleted, mark it as such now.
  6641. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  6642. // definition kind to FDK_Definition.
  6643. switch (D.getFunctionDefinitionKind()) {
  6644. case FDK_Declaration:
  6645. case FDK_Definition:
  6646. break;
  6647. case FDK_Defaulted:
  6648. NewFD->setDefaulted();
  6649. break;
  6650. case FDK_Deleted:
  6651. NewFD->setDeletedAsWritten();
  6652. break;
  6653. }
  6654. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  6655. D.isFunctionDefinition()) {
  6656. // C++ [class.mfct]p2:
  6657. // A member function may be defined (8.4) in its class definition, in
  6658. // which case it is an inline member function (7.1.2)
  6659. NewFD->setImplicitlyInline();
  6660. }
  6661. // HLSL Change: We had to set SC_Static for static data member to
  6662. // distinguish it from global constant variable.
  6663. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  6664. !CurContext->isRecord() && !getLangOpts().HLSL) {
  6665. // C++ [class.static]p1:
  6666. // A data or function member of a class may be declared static
  6667. // in a class definition, in which case it is a static member of
  6668. // the class.
  6669. // Complain about the 'static' specifier if it's on an out-of-line
  6670. // member function definition.
  6671. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6672. diag::err_static_out_of_line)
  6673. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6674. }
  6675. // C++11 [except.spec]p15:
  6676. // A deallocation function with no exception-specification is treated
  6677. // as if it were specified with noexcept(true).
  6678. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  6679. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  6680. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  6681. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  6682. NewFD->setType(Context.getFunctionType(
  6683. FPT->getReturnType(), FPT->getParamTypes(),
  6684. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept),
  6685. FPT->getParamMods())); // HLSL Change - get param mods
  6686. }
  6687. // Filter out previous declarations that don't match the scope.
  6688. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  6689. D.getCXXScopeSpec().isNotEmpty() ||
  6690. isExplicitSpecialization ||
  6691. isFunctionTemplateSpecialization);
  6692. // Handle GNU asm-label extension (encoded as an attribute).
  6693. if (Expr *E = (Expr*) D.getAsmLabel()) {
  6694. // The parser guarantees this is a string.
  6695. StringLiteral *SE = cast<StringLiteral>(E);
  6696. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  6697. SE->getString(), 0));
  6698. } else if (!ExtnameUndeclaredIdentifiers.empty() &&
  6699. isDeclTUScopedExternallyVisible(NewFD)) {
  6700. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6701. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  6702. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6703. NewFD->addAttr(I->second);
  6704. ExtnameUndeclaredIdentifiers.erase(I);
  6705. }
  6706. }
  6707. // Copy the parameter declarations from the declarator D to the function
  6708. // declaration NewFD, if they are available. First scavenge them into Params.
  6709. SmallVector<ParmVarDecl*, 16> Params;
  6710. if (D.isFunctionDeclarator()) {
  6711. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6712. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  6713. // function that takes no arguments, not a function that takes a
  6714. // single void argument.
  6715. // We let through "const void" here because Sema::GetTypeForDeclarator
  6716. // already checks for that case.
  6717. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  6718. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  6719. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  6720. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  6721. Param->setDeclContext(NewFD);
  6722. Params.push_back(Param);
  6723. if (Param->isInvalidDecl())
  6724. NewFD->setInvalidDecl();
  6725. }
  6726. }
  6727. // HLSL Change Starts - error on typedef or type alias of void parameter
  6728. if (getLangOpts().HLSL && FTI.NumParams && FTIHasSingleVoidParameter(FTI)) {
  6729. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[0].Param);
  6730. bool IsTypeAlias = false;
  6731. if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
  6732. IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
  6733. else if (const TemplateSpecializationType *TST =
  6734. Param->getType()->getAs<TemplateSpecializationType>())
  6735. IsTypeAlias = TST->isTypeAlias();
  6736. Diag(Param->getLocation(), diag::err_hlsl_param_typedef_of_void) << IsTypeAlias;
  6737. }
  6738. // HLSL Change Ends
  6739. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  6740. // When we're declaring a function with a typedef, typeof, etc as in the
  6741. // following example, we'll need to synthesize (unnamed)
  6742. // parameters for use in the declaration.
  6743. //
  6744. // @code
  6745. // typedef void fn(int);
  6746. // fn f;
  6747. // @endcode
  6748. // Synthesize a parameter for each argument type.
  6749. for (const auto &AI : FT->param_types()) {
  6750. ParmVarDecl *Param =
  6751. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  6752. Param->setScopeInfo(0, Params.size());
  6753. Params.push_back(Param);
  6754. }
  6755. } else {
  6756. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  6757. "Should not need args for typedef of non-prototype fn");
  6758. }
  6759. // Finally, we know we have the right number of parameters, install them.
  6760. NewFD->setParams(Params);
  6761. // Find all anonymous symbols defined during the declaration of this function
  6762. // and add to NewFD. This lets us track decls such 'enum Y' in:
  6763. //
  6764. // void f(enum Y {AA} x) {}
  6765. //
  6766. // which would otherwise incorrectly end up in the translation unit scope.
  6767. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  6768. DeclsInPrototypeScope.clear();
  6769. if (D.getDeclSpec().isNoreturnSpecified())
  6770. NewFD->addAttr(
  6771. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  6772. Context, 0));
  6773. // Functions returning a variably modified type violate C99 6.7.5.2p2
  6774. // because all functions have linkage.
  6775. if (!NewFD->isInvalidDecl() &&
  6776. NewFD->getReturnType()->isVariablyModifiedType()) {
  6777. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  6778. NewFD->setInvalidDecl();
  6779. }
  6780. // Apply an implicit SectionAttr if #pragma code_seg is active.
  6781. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  6782. !NewFD->hasAttr<SectionAttr>()) {
  6783. NewFD->addAttr(
  6784. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  6785. CodeSegStack.CurrentValue->getString(),
  6786. CodeSegStack.CurrentPragmaLocation));
  6787. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  6788. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  6789. ASTContext::PSF_Read,
  6790. NewFD))
  6791. NewFD->dropAttr<SectionAttr>();
  6792. }
  6793. // Handle attributes.
  6794. ProcessDeclAttributes(S, NewFD, D);
  6795. if (getLangOpts().OpenCL) {
  6796. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  6797. // type declaration will generate a compilation error.
  6798. unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
  6799. if (AddressSpace == LangAS::opencl_local ||
  6800. AddressSpace == LangAS::opencl_global ||
  6801. AddressSpace == LangAS::opencl_constant) {
  6802. Diag(NewFD->getLocation(),
  6803. diag::err_opencl_return_value_with_address_space);
  6804. NewFD->setInvalidDecl();
  6805. }
  6806. }
  6807. if (!getLangOpts().CPlusPlus) {
  6808. // Perform semantic checking on the function declaration.
  6809. bool isExplicitSpecialization=false;
  6810. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  6811. CheckMain(NewFD, D.getDeclSpec());
  6812. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  6813. CheckMSVCRTEntryPoint(NewFD);
  6814. if (!NewFD->isInvalidDecl())
  6815. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6816. isExplicitSpecialization));
  6817. else if (!Previous.empty())
  6818. // Recover gracefully from an invalid redeclaration.
  6819. D.setRedeclaration(true);
  6820. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6821. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6822. "previous declaration set still overloaded");
  6823. // Diagnose no-prototype function declarations with calling conventions that
  6824. // don't support variadic calls. Only do this in C and do it after merging
  6825. // possibly prototyped redeclarations.
  6826. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  6827. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  6828. CallingConv CC = FT->getExtInfo().getCC();
  6829. if (!supportsVariadicCall(CC)) {
  6830. // Windows system headers sometimes accidentally use stdcall without
  6831. // (void) parameters, so we relax this to a warning.
  6832. int DiagID =
  6833. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  6834. Diag(NewFD->getLocation(), DiagID)
  6835. << FunctionType::getNameForCallConv(CC);
  6836. }
  6837. }
  6838. } else {
  6839. // C++11 [replacement.functions]p3:
  6840. // The program's definitions shall not be specified as inline.
  6841. //
  6842. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  6843. //
  6844. // Suppress the diagnostic if the function is __attribute__((used)), since
  6845. // that forces an external definition to be emitted.
  6846. if (D.getDeclSpec().isInlineSpecified() &&
  6847. NewFD->isReplaceableGlobalAllocationFunction() &&
  6848. !NewFD->hasAttr<UsedAttr>())
  6849. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6850. diag::ext_operator_new_delete_declared_inline)
  6851. << NewFD->getDeclName();
  6852. // If the declarator is a template-id, translate the parser's template
  6853. // argument list into our AST format.
  6854. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  6855. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  6856. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  6857. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  6858. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6859. TemplateId->NumArgs);
  6860. translateTemplateArguments(TemplateArgsPtr,
  6861. TemplateArgs);
  6862. HasExplicitTemplateArgs = true;
  6863. if (NewFD->isInvalidDecl()) {
  6864. HasExplicitTemplateArgs = false;
  6865. } else if (FunctionTemplate) {
  6866. // Function template with explicit template arguments.
  6867. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  6868. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  6869. HasExplicitTemplateArgs = false;
  6870. } else {
  6871. assert((isFunctionTemplateSpecialization ||
  6872. D.getDeclSpec().isFriendSpecified()) &&
  6873. "should have a 'template<>' for this decl");
  6874. // "friend void foo<>(int);" is an implicit specialization decl.
  6875. isFunctionTemplateSpecialization = true;
  6876. }
  6877. } else if (isFriend && isFunctionTemplateSpecialization) {
  6878. // This combination is only possible in a recovery case; the user
  6879. // wrote something like:
  6880. // template <> friend void foo(int);
  6881. // which we're recovering from as if the user had written:
  6882. // friend void foo<>(int);
  6883. // Go ahead and fake up a template id.
  6884. HasExplicitTemplateArgs = true;
  6885. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  6886. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  6887. }
  6888. // If it's a friend (and only if it's a friend), it's possible
  6889. // that either the specialized function type or the specialized
  6890. // template is dependent, and therefore matching will fail. In
  6891. // this case, don't check the specialization yet.
  6892. bool InstantiationDependent = false;
  6893. if (isFunctionTemplateSpecialization && isFriend &&
  6894. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  6895. TemplateSpecializationType::anyDependentTemplateArguments(
  6896. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  6897. InstantiationDependent))) {
  6898. assert(HasExplicitTemplateArgs &&
  6899. "friend function specialization without template args");
  6900. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  6901. Previous))
  6902. NewFD->setInvalidDecl();
  6903. } else if (isFunctionTemplateSpecialization) {
  6904. if (CurContext->isDependentContext() && CurContext->isRecord()
  6905. && !isFriend) {
  6906. isDependentClassScopeExplicitSpecialization = true;
  6907. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  6908. diag::ext_function_specialization_in_class :
  6909. diag::err_function_specialization_in_class)
  6910. << NewFD->getDeclName();
  6911. } else if (CheckFunctionTemplateSpecialization(NewFD,
  6912. (HasExplicitTemplateArgs ? &TemplateArgs
  6913. : nullptr),
  6914. Previous))
  6915. NewFD->setInvalidDecl();
  6916. // C++ [dcl.stc]p1:
  6917. // A storage-class-specifier shall not be specified in an explicit
  6918. // specialization (14.7.3)
  6919. FunctionTemplateSpecializationInfo *Info =
  6920. NewFD->getTemplateSpecializationInfo();
  6921. if (Info && SC != SC_None) {
  6922. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  6923. Diag(NewFD->getLocation(),
  6924. diag::err_explicit_specialization_inconsistent_storage_class)
  6925. << SC
  6926. << FixItHint::CreateRemoval(
  6927. D.getDeclSpec().getStorageClassSpecLoc());
  6928. else
  6929. Diag(NewFD->getLocation(),
  6930. diag::ext_explicit_specialization_storage_class)
  6931. << FixItHint::CreateRemoval(
  6932. D.getDeclSpec().getStorageClassSpecLoc());
  6933. }
  6934. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  6935. if (CheckMemberSpecialization(NewFD, Previous))
  6936. NewFD->setInvalidDecl();
  6937. }
  6938. // Perform semantic checking on the function declaration.
  6939. if (!isDependentClassScopeExplicitSpecialization) {
  6940. if (!getLangOpts().HLSL && !NewFD->isInvalidDecl() && NewFD->isMain()) // HLSL Change: no main() checks in HLSL
  6941. CheckMain(NewFD, D.getDeclSpec());
  6942. if (!getLangOpts().HLSL && !NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) // HLSL Change: no entry point checks in HLSL
  6943. CheckMSVCRTEntryPoint(NewFD);
  6944. if (!NewFD->isInvalidDecl())
  6945. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6946. isExplicitSpecialization));
  6947. else if (!Previous.empty())
  6948. // Recover gracefully from an invalid redeclaration.
  6949. D.setRedeclaration(true);
  6950. }
  6951. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6952. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6953. "previous declaration set still overloaded");
  6954. NamedDecl *PrincipalDecl = (FunctionTemplate
  6955. ? cast<NamedDecl>(FunctionTemplate)
  6956. : NewFD);
  6957. if (isFriend && D.isRedeclaration()) {
  6958. AccessSpecifier Access = AS_public;
  6959. if (!NewFD->isInvalidDecl())
  6960. Access = NewFD->getPreviousDecl()->getAccess();
  6961. NewFD->setAccess(Access);
  6962. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  6963. }
  6964. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  6965. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  6966. PrincipalDecl->setNonMemberOperator();
  6967. // If we have a function template, check the template parameter
  6968. // list. This will check and merge default template arguments.
  6969. if (FunctionTemplate) {
  6970. FunctionTemplateDecl *PrevTemplate =
  6971. FunctionTemplate->getPreviousDecl();
  6972. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  6973. PrevTemplate ? PrevTemplate->getTemplateParameters()
  6974. : nullptr,
  6975. D.getDeclSpec().isFriendSpecified()
  6976. ? (D.isFunctionDefinition()
  6977. ? TPC_FriendFunctionTemplateDefinition
  6978. : TPC_FriendFunctionTemplate)
  6979. : (D.getCXXScopeSpec().isSet() &&
  6980. DC && DC->isRecord() &&
  6981. DC->isDependentContext())
  6982. ? TPC_ClassTemplateMember
  6983. : TPC_FunctionTemplate);
  6984. }
  6985. if (NewFD->isInvalidDecl()) {
  6986. // Ignore all the rest of this.
  6987. } else if (!D.isRedeclaration()) {
  6988. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  6989. AddToScope };
  6990. // Fake up an access specifier if it's supposed to be a class member.
  6991. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  6992. NewFD->setAccess(AS_public);
  6993. // Qualified decls generally require a previous declaration.
  6994. if (D.getCXXScopeSpec().isSet()) {
  6995. // ...with the major exception of templated-scope or
  6996. // dependent-scope friend declarations.
  6997. // TODO: we currently also suppress this check in dependent
  6998. // contexts because (1) the parameter depth will be off when
  6999. // matching friend templates and (2) we might actually be
  7000. // selecting a friend based on a dependent factor. But there
  7001. // are situations where these conditions don't apply and we
  7002. // can actually do this check immediately.
  7003. if (isFriend &&
  7004. (TemplateParamLists.size() ||
  7005. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  7006. CurContext->isDependentContext())) {
  7007. // ignore these
  7008. } else {
  7009. // The user tried to provide an out-of-line definition for a
  7010. // function that is a member of a class or namespace, but there
  7011. // was no such member function declared (C++ [class.mfct]p2,
  7012. // C++ [namespace.memdef]p2). For example:
  7013. //
  7014. // class X {
  7015. // void f() const;
  7016. // };
  7017. //
  7018. // void X::f() { } // ill-formed
  7019. //
  7020. // Complain about this problem, and attempt to suggest close
  7021. // matches (e.g., those that differ only in cv-qualifiers and
  7022. // whether the parameter types are references).
  7023. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7024. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7025. AddToScope = ExtraArgs.AddToScope;
  7026. return Result;
  7027. }
  7028. }
  7029. // Unqualified local friend declarations are required to resolve
  7030. // to something.
  7031. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7032. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7033. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7034. AddToScope = ExtraArgs.AddToScope;
  7035. return Result;
  7036. }
  7037. }
  7038. } else if (!D.isFunctionDefinition() &&
  7039. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7040. !isFriend && !isFunctionTemplateSpecialization &&
  7041. !isExplicitSpecialization) {
  7042. // An out-of-line member function declaration must also be a
  7043. // definition (C++ [class.mfct]p2).
  7044. // Note that this is not the case for explicit specializations of
  7045. // function templates or member functions of class templates, per
  7046. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7047. // extension for compatibility with old SWIG code which likes to
  7048. // generate them.
  7049. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7050. << D.getCXXScopeSpec().getRange();
  7051. }
  7052. }
  7053. ProcessPragmaWeak(S, NewFD);
  7054. checkAttributesAfterMerging(*this, *NewFD);
  7055. AddKnownFunctionAttributes(NewFD);
  7056. if (NewFD->hasAttr<OverloadableAttr>() &&
  7057. !NewFD->getType()->getAs<FunctionProtoType>()) {
  7058. Diag(NewFD->getLocation(),
  7059. diag::err_attribute_overloadable_no_prototype)
  7060. << NewFD;
  7061. // Turn this into a variadic function with no parameters.
  7062. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  7063. FunctionProtoType::ExtProtoInfo EPI(
  7064. Context.getDefaultCallingConvention(true, false));
  7065. EPI.Variadic = true;
  7066. EPI.ExtInfo = FT->getExtInfo();
  7067. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI, None); // HLSL Change - all defaults are in
  7068. NewFD->setType(R);
  7069. }
  7070. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7071. // member, set the visibility of this function.
  7072. if (!DC->isRecord() && NewFD->isExternallyVisible())
  7073. AddPushedVisibilityAttribute(NewFD);
  7074. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  7075. // marking the function.
  7076. AddCFAuditedAttribute(NewFD);
  7077. // If this is a function definition, check if we have to apply optnone due to
  7078. // a pragma.
  7079. if(D.isFunctionDefinition())
  7080. AddRangeBasedOptnone(NewFD);
  7081. // If this is the first declaration of an extern C variable, update
  7082. // the map of such variables.
  7083. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  7084. isIncompleteDeclExternC(*this, NewFD))
  7085. RegisterLocallyScopedExternCDecl(NewFD, S);
  7086. // Set this FunctionDecl's range up to the right paren.
  7087. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  7088. if (D.isRedeclaration() && !Previous.empty()) {
  7089. checkDLLAttributeRedeclaration(
  7090. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  7091. isExplicitSpecialization || isFunctionTemplateSpecialization);
  7092. }
  7093. if (getLangOpts().CPlusPlus) {
  7094. if (FunctionTemplate) {
  7095. if (NewFD->isInvalidDecl())
  7096. FunctionTemplate->setInvalidDecl();
  7097. return FunctionTemplate;
  7098. }
  7099. }
  7100. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  7101. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  7102. if ((getLangOpts().OpenCLVersion >= 120)
  7103. && (SC == SC_Static)) {
  7104. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  7105. D.setInvalidType();
  7106. }
  7107. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  7108. if (!NewFD->getReturnType()->isVoidType()) {
  7109. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  7110. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  7111. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  7112. : FixItHint());
  7113. D.setInvalidType();
  7114. }
  7115. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  7116. for (auto Param : NewFD->params())
  7117. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  7118. }
  7119. MarkUnusedFileScopedDecl(NewFD);
  7120. if (getLangOpts().CUDA)
  7121. if (IdentifierInfo *II = NewFD->getIdentifier())
  7122. if (!NewFD->isInvalidDecl() &&
  7123. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  7124. if (II->isStr("cudaConfigureCall")) {
  7125. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  7126. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  7127. Context.setcudaConfigureCallDecl(NewFD);
  7128. }
  7129. }
  7130. // Here we have an function template explicit specialization at class scope.
  7131. // The actually specialization will be postponed to template instatiation
  7132. // time via the ClassScopeFunctionSpecializationDecl node.
  7133. if (isDependentClassScopeExplicitSpecialization) {
  7134. ClassScopeFunctionSpecializationDecl *NewSpec =
  7135. ClassScopeFunctionSpecializationDecl::Create(
  7136. Context, CurContext, SourceLocation(),
  7137. cast<CXXMethodDecl>(NewFD),
  7138. HasExplicitTemplateArgs, TemplateArgs);
  7139. CurContext->addDecl(NewSpec);
  7140. AddToScope = false;
  7141. }
  7142. return NewFD;
  7143. }
  7144. /// \brief Perform semantic checking of a new function declaration.
  7145. ///
  7146. /// Performs semantic analysis of the new function declaration
  7147. /// NewFD. This routine performs all semantic checking that does not
  7148. /// require the actual declarator involved in the declaration, and is
  7149. /// used both for the declaration of functions as they are parsed
  7150. /// (called via ActOnDeclarator) and for the declaration of functions
  7151. /// that have been instantiated via C++ template instantiation (called
  7152. /// via InstantiateDecl).
  7153. ///
  7154. /// \param IsExplicitSpecialization whether this new function declaration is
  7155. /// an explicit specialization of the previous declaration.
  7156. ///
  7157. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  7158. ///
  7159. /// \returns true if the function declaration is a redeclaration.
  7160. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  7161. LookupResult &Previous,
  7162. bool IsExplicitSpecialization) {
  7163. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  7164. "Variably modified return types are not handled here");
  7165. // Determine whether the type of this function should be merged with
  7166. // a previous visible declaration. This never happens for functions in C++,
  7167. // and always happens in C if the previous declaration was visible.
  7168. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  7169. !Previous.isShadowed();
  7170. // Filter out any non-conflicting previous declarations.
  7171. filterNonConflictingPreviousDecls(*this, NewFD, Previous);
  7172. bool Redeclaration = false;
  7173. NamedDecl *OldDecl = nullptr;
  7174. // Merge or overload the declaration with an existing declaration of
  7175. // the same name, if appropriate.
  7176. if (!Previous.empty()) {
  7177. // Determine whether NewFD is an overload of PrevDecl or
  7178. // a declaration that requires merging. If it's an overload,
  7179. // there's no more work to do here; we'll just add the new
  7180. // function to the scope.
  7181. if (!AllowOverloadingOfFunction(Previous, Context)) {
  7182. NamedDecl *Candidate = Previous.getFoundDecl();
  7183. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  7184. Redeclaration = true;
  7185. OldDecl = Candidate;
  7186. }
  7187. } else {
  7188. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  7189. /*NewIsUsingDecl*/ false)) {
  7190. case Ovl_Match:
  7191. Redeclaration = true;
  7192. break;
  7193. case Ovl_NonFunction:
  7194. Redeclaration = true;
  7195. break;
  7196. case Ovl_Overload:
  7197. Redeclaration = false;
  7198. break;
  7199. }
  7200. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7201. // If a function name is overloadable in C, then every function
  7202. // with that name must be marked "overloadable".
  7203. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7204. << Redeclaration << NewFD;
  7205. NamedDecl *OverloadedDecl = nullptr;
  7206. if (Redeclaration)
  7207. OverloadedDecl = OldDecl;
  7208. else if (!Previous.empty())
  7209. OverloadedDecl = Previous.getRepresentativeDecl();
  7210. if (OverloadedDecl)
  7211. Diag(OverloadedDecl->getLocation(),
  7212. diag::note_attribute_overloadable_prev_overload);
  7213. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7214. }
  7215. }
  7216. }
  7217. // Check for a previous extern "C" declaration with this name.
  7218. if (!Redeclaration &&
  7219. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  7220. filterNonConflictingPreviousDecls(*this, NewFD, Previous);
  7221. if (!Previous.empty()) {
  7222. // This is an extern "C" declaration with the same name as a previous
  7223. // declaration, and thus redeclares that entity...
  7224. Redeclaration = true;
  7225. OldDecl = Previous.getFoundDecl();
  7226. MergeTypeWithPrevious = false;
  7227. // ... except in the presence of __attribute__((overloadable)).
  7228. if (OldDecl->hasAttr<OverloadableAttr>()) {
  7229. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7230. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7231. << Redeclaration << NewFD;
  7232. Diag(Previous.getFoundDecl()->getLocation(),
  7233. diag::note_attribute_overloadable_prev_overload);
  7234. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7235. }
  7236. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  7237. Redeclaration = false;
  7238. OldDecl = nullptr;
  7239. }
  7240. }
  7241. }
  7242. }
  7243. // HLSL Change Starts
  7244. // Rather than fix for inout parameters, comment out - this is N/A for HLSL
  7245. #if 0
  7246. // HLSL Change Ends
  7247. // C++11 [dcl.constexpr]p8:
  7248. // A constexpr specifier for a non-static member function that is not
  7249. // a constructor declares that member function to be const.
  7250. //
  7251. // This needs to be delayed until we know whether this is an out-of-line
  7252. // definition of a static member function.
  7253. //
  7254. // This rule is not present in C++1y, so we produce a backwards
  7255. // compatibility warning whenever it happens in C++11.
  7256. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7257. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  7258. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  7259. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  7260. CXXMethodDecl *OldMD = nullptr;
  7261. if (OldDecl)
  7262. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  7263. if (!OldMD || !OldMD->isStatic()) {
  7264. const FunctionProtoType *FPT =
  7265. MD->getType()->castAs<FunctionProtoType>();
  7266. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7267. EPI.TypeQuals |= Qualifiers::Const;
  7268. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  7269. FPT->getParamTypes(), EPI));
  7270. // Warn that we did this, if we're not performing template instantiation.
  7271. // In that case, we'll have warned already when the template was defined.
  7272. if (ActiveTemplateInstantiations.empty()) {
  7273. SourceLocation AddConstLoc;
  7274. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  7275. .IgnoreParens().getAs<FunctionTypeLoc>())
  7276. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  7277. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  7278. << FixItHint::CreateInsertion(AddConstLoc, " const");
  7279. }
  7280. }
  7281. }
  7282. #endif // HLSL Change Ends
  7283. if (Redeclaration) {
  7284. // NewFD and OldDecl represent declarations that need to be
  7285. // merged.
  7286. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  7287. NewFD->setInvalidDecl();
  7288. return Redeclaration;
  7289. }
  7290. Previous.clear();
  7291. Previous.addDecl(OldDecl);
  7292. if (FunctionTemplateDecl *OldTemplateDecl
  7293. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  7294. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  7295. FunctionTemplateDecl *NewTemplateDecl
  7296. = NewFD->getDescribedFunctionTemplate();
  7297. assert(NewTemplateDecl && "Template/non-template mismatch");
  7298. if (CXXMethodDecl *Method
  7299. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  7300. Method->setAccess(OldTemplateDecl->getAccess());
  7301. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  7302. }
  7303. // If this is an explicit specialization of a member that is a function
  7304. // template, mark it as a member specialization.
  7305. if (IsExplicitSpecialization &&
  7306. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  7307. NewTemplateDecl->setMemberSpecialization();
  7308. assert(OldTemplateDecl->isMemberSpecialization());
  7309. }
  7310. } else {
  7311. // This needs to happen first so that 'inline' propagates.
  7312. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  7313. if (isa<CXXMethodDecl>(NewFD))
  7314. NewFD->setAccess(OldDecl->getAccess());
  7315. }
  7316. }
  7317. // Semantic checking for this function declaration (in isolation).
  7318. if (getLangOpts().CPlusPlus) {
  7319. // C++-specific checks.
  7320. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  7321. CheckConstructor(Constructor);
  7322. } else if (CXXDestructorDecl *Destructor =
  7323. dyn_cast<CXXDestructorDecl>(NewFD)) {
  7324. CXXRecordDecl *Record = Destructor->getParent();
  7325. QualType ClassType = Context.getTypeDeclType(Record);
  7326. // FIXME: Shouldn't we be able to perform this check even when the class
  7327. // type is dependent? Both gcc and edg can handle that.
  7328. if (!ClassType->isDependentType()) {
  7329. DeclarationName Name
  7330. = Context.DeclarationNames.getCXXDestructorName(
  7331. Context.getCanonicalType(ClassType));
  7332. if (NewFD->getDeclName() != Name) {
  7333. Diag(NewFD->getLocation(), diag::err_destructor_name);
  7334. NewFD->setInvalidDecl();
  7335. return Redeclaration;
  7336. }
  7337. }
  7338. } else if (CXXConversionDecl *Conversion
  7339. = dyn_cast<CXXConversionDecl>(NewFD)) {
  7340. ActOnConversionDeclarator(Conversion);
  7341. }
  7342. // Find any virtual functions that this function overrides.
  7343. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  7344. if (!Method->isFunctionTemplateSpecialization() &&
  7345. !Method->getDescribedFunctionTemplate() &&
  7346. Method->isCanonicalDecl()) {
  7347. if (AddOverriddenMethods(Method->getParent(), Method)) {
  7348. // If the function was marked as "static", we have a problem.
  7349. if (NewFD->getStorageClass() == SC_Static) {
  7350. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  7351. }
  7352. }
  7353. }
  7354. if (Method->isStatic())
  7355. checkThisInStaticMemberFunctionType(Method);
  7356. }
  7357. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  7358. if (NewFD->isOverloadedOperator() &&
  7359. CheckOverloadedOperatorDeclaration(NewFD)) {
  7360. NewFD->setInvalidDecl();
  7361. return Redeclaration;
  7362. }
  7363. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  7364. if (NewFD->getLiteralIdentifier() &&
  7365. CheckLiteralOperatorDeclaration(NewFD)) {
  7366. NewFD->setInvalidDecl();
  7367. return Redeclaration;
  7368. }
  7369. // In C++, check default arguments now that we have merged decls. Unless
  7370. // the lexical context is the class, because in this case this is done
  7371. // during delayed parsing anyway.
  7372. if (!CurContext->isRecord())
  7373. CheckCXXDefaultArguments(NewFD);
  7374. // If this function declares a builtin function, check the type of this
  7375. // declaration against the expected type for the builtin.
  7376. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  7377. ASTContext::GetBuiltinTypeError Error;
  7378. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  7379. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  7380. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  7381. // The type of this function differs from the type of the builtin,
  7382. // so forget about the builtin entirely.
  7383. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  7384. }
  7385. }
  7386. // If this function is declared as being extern "C", then check to see if
  7387. // the function returns a UDT (class, struct, or union type) that is not C
  7388. // compatible, and if it does, warn the user.
  7389. // But, issue any diagnostic on the first declaration only.
  7390. if (Previous.empty() && NewFD->isExternC()) {
  7391. QualType R = NewFD->getReturnType();
  7392. if (R->isIncompleteType() && !R->isVoidType())
  7393. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  7394. << NewFD << R;
  7395. else if (!R.isPODType(Context) && !R->isVoidType() &&
  7396. !R->isObjCObjectPointerType())
  7397. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  7398. }
  7399. }
  7400. return Redeclaration;
  7401. }
  7402. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  7403. // C++11 [basic.start.main]p3:
  7404. // A program that [...] declares main to be inline, static or
  7405. // constexpr is ill-formed.
  7406. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  7407. // appear in a declaration of main.
  7408. // static main is not an error under C99, but we should warn about it.
  7409. // We accept _Noreturn main as an extension.
  7410. if (FD->getStorageClass() == SC_Static)
  7411. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  7412. ? diag::err_static_main : diag::warn_static_main)
  7413. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  7414. if (FD->isInlineSpecified())
  7415. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  7416. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  7417. if (DS.isNoreturnSpecified()) {
  7418. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  7419. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  7420. Diag(NoreturnLoc, diag::ext_noreturn_main);
  7421. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  7422. << FixItHint::CreateRemoval(NoreturnRange);
  7423. }
  7424. if (FD->isConstexpr()) {
  7425. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  7426. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  7427. FD->setConstexpr(false);
  7428. }
  7429. if (getLangOpts().OpenCL) {
  7430. Diag(FD->getLocation(), diag::err_opencl_no_main)
  7431. << FD->hasAttr<OpenCLKernelAttr>();
  7432. FD->setInvalidDecl();
  7433. return;
  7434. }
  7435. QualType T = FD->getType();
  7436. assert(T->isFunctionType() && "function decl is not of function type");
  7437. const FunctionType* FT = T->castAs<FunctionType>();
  7438. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  7439. // In C with GNU extensions we allow main() to have non-integer return
  7440. // type, but we should warn about the extension, and we disable the
  7441. // implicit-return-zero rule.
  7442. // GCC in C mode accepts qualified 'int'.
  7443. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  7444. FD->setHasImplicitReturnZero(true);
  7445. else {
  7446. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  7447. SourceRange RTRange = FD->getReturnTypeSourceRange();
  7448. if (RTRange.isValid())
  7449. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  7450. << FixItHint::CreateReplacement(RTRange, "int");
  7451. }
  7452. } else {
  7453. // In C and C++, main magically returns 0 if you fall off the end;
  7454. // set the flag which tells us that.
  7455. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  7456. // All the standards say that main() should return 'int'.
  7457. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  7458. FD->setHasImplicitReturnZero(true);
  7459. else {
  7460. // Otherwise, this is just a flat-out error.
  7461. SourceRange RTRange = FD->getReturnTypeSourceRange();
  7462. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  7463. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  7464. : FixItHint());
  7465. FD->setInvalidDecl(true);
  7466. }
  7467. }
  7468. // Treat protoless main() as nullary.
  7469. if (isa<FunctionNoProtoType>(FT)) return;
  7470. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  7471. unsigned nparams = FTP->getNumParams();
  7472. assert(FD->getNumParams() == nparams);
  7473. bool HasExtraParameters = (nparams > 3);
  7474. if (FTP->isVariadic()) {
  7475. Diag(FD->getLocation(), diag::ext_variadic_main);
  7476. // FIXME: if we had information about the location of the ellipsis, we
  7477. // could add a FixIt hint to remove it as a parameter.
  7478. }
  7479. // Darwin passes an undocumented fourth argument of type char**. If
  7480. // other platforms start sprouting these, the logic below will start
  7481. // getting shifty.
  7482. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  7483. HasExtraParameters = false;
  7484. if (HasExtraParameters) {
  7485. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  7486. FD->setInvalidDecl(true);
  7487. nparams = 3;
  7488. }
  7489. // FIXME: a lot of the following diagnostics would be improved
  7490. // if we had some location information about types.
  7491. QualType CharPP =
  7492. Context.getPointerType(Context.getPointerType(Context.CharTy));
  7493. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  7494. for (unsigned i = 0; i < nparams; ++i) {
  7495. QualType AT = FTP->getParamType(i);
  7496. bool mismatch = true;
  7497. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  7498. mismatch = false;
  7499. else if (Expected[i] == CharPP) {
  7500. // As an extension, the following forms are okay:
  7501. // char const **
  7502. // char const * const *
  7503. // char * const *
  7504. QualifierCollector qs;
  7505. const PointerType* PT;
  7506. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  7507. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  7508. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  7509. Context.CharTy)) {
  7510. qs.removeConst();
  7511. mismatch = !qs.empty();
  7512. }
  7513. }
  7514. if (mismatch) {
  7515. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  7516. // TODO: suggest replacing given type with expected type
  7517. FD->setInvalidDecl(true);
  7518. }
  7519. }
  7520. if (nparams == 1 && !FD->isInvalidDecl()) {
  7521. Diag(FD->getLocation(), diag::warn_main_one_arg);
  7522. }
  7523. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  7524. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  7525. FD->setInvalidDecl();
  7526. }
  7527. }
  7528. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  7529. QualType T = FD->getType();
  7530. assert(T->isFunctionType() && "function decl is not of function type");
  7531. const FunctionType *FT = T->castAs<FunctionType>();
  7532. // Set an implicit return of 'zero' if the function can return some integral,
  7533. // enumeration, pointer or nullptr type.
  7534. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  7535. FT->getReturnType()->isAnyPointerType() ||
  7536. FT->getReturnType()->isNullPtrType())
  7537. // DllMain is exempt because a return value of zero means it failed.
  7538. if (FD->getName() != "DllMain")
  7539. FD->setHasImplicitReturnZero(true);
  7540. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  7541. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  7542. FD->setInvalidDecl();
  7543. }
  7544. }
  7545. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  7546. // FIXME: Need strict checking. In C89, we need to check for
  7547. // any assignment, increment, decrement, function-calls, or
  7548. // commas outside of a sizeof. In C99, it's the same list,
  7549. // except that the aforementioned are allowed in unevaluated
  7550. // expressions. Everything else falls under the
  7551. // "may accept other forms of constant expressions" exception.
  7552. // (We never end up here for C++, so the constant expression
  7553. // rules there don't matter.)
  7554. const Expr *Culprit;
  7555. if (Init->isConstantInitializer(Context, false, &Culprit))
  7556. return false;
  7557. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  7558. << Culprit->getSourceRange();
  7559. return true;
  7560. }
  7561. namespace {
  7562. // Visits an initialization expression to see if OrigDecl is evaluated in
  7563. // its own initialization and throws a warning if it does.
  7564. class SelfReferenceChecker
  7565. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  7566. Sema &S;
  7567. Decl *OrigDecl;
  7568. bool isRecordType;
  7569. bool isPODType;
  7570. bool isReferenceType;
  7571. bool isInitList;
  7572. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  7573. public:
  7574. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  7575. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  7576. S(S), OrigDecl(OrigDecl) {
  7577. isPODType = false;
  7578. isRecordType = false;
  7579. isReferenceType = false;
  7580. isInitList = false;
  7581. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  7582. isPODType = VD->getType().isPODType(S.Context);
  7583. isRecordType = VD->getType()->isRecordType();
  7584. isReferenceType = VD->getType()->isReferenceType();
  7585. }
  7586. }
  7587. // For most expressions, just call the visitor. For initializer lists,
  7588. // track the index of the field being initialized since fields are
  7589. // initialized in order allowing use of previously initialized fields.
  7590. void CheckExpr(Expr *E) {
  7591. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  7592. if (!InitList) {
  7593. Visit(E);
  7594. return;
  7595. }
  7596. // Track and increment the index here.
  7597. isInitList = true;
  7598. InitFieldIndex.push_back(0);
  7599. for (auto Child : InitList->children()) {
  7600. CheckExpr(cast<Expr>(Child));
  7601. ++InitFieldIndex.back();
  7602. }
  7603. InitFieldIndex.pop_back();
  7604. }
  7605. // Returns true if MemberExpr is checked and no futher checking is needed.
  7606. // Returns false if additional checking is required.
  7607. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  7608. llvm::SmallVector<FieldDecl*, 4> Fields;
  7609. Expr *Base = E;
  7610. bool ReferenceField = false;
  7611. // Get the field memebers used.
  7612. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7613. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  7614. if (!FD)
  7615. return false;
  7616. Fields.push_back(FD);
  7617. if (FD->getType()->isReferenceType())
  7618. ReferenceField = true;
  7619. Base = ME->getBase()->IgnoreParenImpCasts();
  7620. }
  7621. // Keep checking only if the base Decl is the same.
  7622. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  7623. if (!DRE || DRE->getDecl() != OrigDecl)
  7624. return false;
  7625. // A reference field can be bound to an unininitialized field.
  7626. if (CheckReference && !ReferenceField)
  7627. return true;
  7628. // Convert FieldDecls to their index number.
  7629. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  7630. for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
  7631. UsedFieldIndex.push_back((*I)->getFieldIndex());
  7632. }
  7633. // See if a warning is needed by checking the first difference in index
  7634. // numbers. If field being used has index less than the field being
  7635. // initialized, then the use is safe.
  7636. for (auto UsedIter = UsedFieldIndex.begin(),
  7637. UsedEnd = UsedFieldIndex.end(),
  7638. OrigIter = InitFieldIndex.begin(),
  7639. OrigEnd = InitFieldIndex.end();
  7640. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  7641. if (*UsedIter < *OrigIter)
  7642. return true;
  7643. if (*UsedIter > *OrigIter)
  7644. break;
  7645. }
  7646. // TODO: Add a different warning which will print the field names.
  7647. HandleDeclRefExpr(DRE);
  7648. return true;
  7649. }
  7650. // For most expressions, the cast is directly above the DeclRefExpr.
  7651. // For conditional operators, the cast can be outside the conditional
  7652. // operator if both expressions are DeclRefExpr's.
  7653. void HandleValue(Expr *E) {
  7654. E = E->IgnoreParens();
  7655. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  7656. HandleDeclRefExpr(DRE);
  7657. return;
  7658. }
  7659. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7660. Visit(CO->getCond());
  7661. HandleValue(CO->getTrueExpr());
  7662. HandleValue(CO->getFalseExpr());
  7663. return;
  7664. }
  7665. if (BinaryConditionalOperator *BCO =
  7666. dyn_cast<BinaryConditionalOperator>(E)) {
  7667. Visit(BCO->getCond());
  7668. HandleValue(BCO->getFalseExpr());
  7669. return;
  7670. }
  7671. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  7672. HandleValue(OVE->getSourceExpr());
  7673. return;
  7674. }
  7675. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  7676. if (BO->getOpcode() == BO_Comma) {
  7677. Visit(BO->getLHS());
  7678. HandleValue(BO->getRHS());
  7679. return;
  7680. }
  7681. }
  7682. if (isa<MemberExpr>(E)) {
  7683. if (isInitList) {
  7684. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  7685. false /*CheckReference*/))
  7686. return;
  7687. }
  7688. Expr *Base = E->IgnoreParenImpCasts();
  7689. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7690. // Check for static member variables and don't warn on them.
  7691. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7692. return;
  7693. Base = ME->getBase()->IgnoreParenImpCasts();
  7694. }
  7695. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  7696. HandleDeclRefExpr(DRE);
  7697. return;
  7698. }
  7699. Visit(E);
  7700. }
  7701. // Reference types not handled in HandleValue are handled here since all
  7702. // uses of references are bad, not just r-value uses.
  7703. void VisitDeclRefExpr(DeclRefExpr *E) {
  7704. if (isReferenceType)
  7705. HandleDeclRefExpr(E);
  7706. }
  7707. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  7708. if (E->getCastKind() == CK_LValueToRValue) {
  7709. HandleValue(E->getSubExpr());
  7710. return;
  7711. }
  7712. Inherited::VisitImplicitCastExpr(E);
  7713. }
  7714. void VisitMemberExpr(MemberExpr *E) {
  7715. if (isInitList) {
  7716. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  7717. return;
  7718. }
  7719. // Don't warn on arrays since they can be treated as pointers.
  7720. if (E->getType()->canDecayToPointerType()) return;
  7721. // Warn when a non-static method call is followed by non-static member
  7722. // field accesses, which is followed by a DeclRefExpr.
  7723. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  7724. bool Warn = (MD && !MD->isStatic());
  7725. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  7726. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7727. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7728. Warn = false;
  7729. Base = ME->getBase()->IgnoreParenImpCasts();
  7730. }
  7731. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  7732. if (Warn)
  7733. HandleDeclRefExpr(DRE);
  7734. return;
  7735. }
  7736. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  7737. // Visit that expression.
  7738. Visit(Base);
  7739. }
  7740. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  7741. Expr *Callee = E->getCallee();
  7742. if (isa<UnresolvedLookupExpr>(Callee))
  7743. return Inherited::VisitCXXOperatorCallExpr(E);
  7744. Visit(Callee);
  7745. for (auto Arg: E->arguments())
  7746. HandleValue(Arg->IgnoreParenImpCasts());
  7747. }
  7748. void VisitUnaryOperator(UnaryOperator *E) {
  7749. // For POD record types, addresses of its own members are well-defined.
  7750. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  7751. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  7752. if (!isPODType)
  7753. HandleValue(E->getSubExpr());
  7754. return;
  7755. }
  7756. if (E->isIncrementDecrementOp()) {
  7757. HandleValue(E->getSubExpr());
  7758. return;
  7759. }
  7760. Inherited::VisitUnaryOperator(E);
  7761. }
  7762. void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
  7763. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  7764. if (E->getConstructor()->isCopyConstructor()) {
  7765. Expr *ArgExpr = E->getArg(0);
  7766. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  7767. if (ILE->getNumInits() == 1)
  7768. ArgExpr = ILE->getInit(0);
  7769. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  7770. if (ICE->getCastKind() == CK_NoOp)
  7771. ArgExpr = ICE->getSubExpr();
  7772. HandleValue(ArgExpr);
  7773. return;
  7774. }
  7775. Inherited::VisitCXXConstructExpr(E);
  7776. }
  7777. void VisitCallExpr(CallExpr *E) {
  7778. // Treat std::move as a use.
  7779. if (E->getNumArgs() == 1) {
  7780. if (FunctionDecl *FD = E->getDirectCallee()) {
  7781. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  7782. FD->getIdentifier()->isStr("move")) {
  7783. HandleValue(E->getArg(0));
  7784. return;
  7785. }
  7786. }
  7787. }
  7788. Inherited::VisitCallExpr(E);
  7789. }
  7790. void VisitBinaryOperator(BinaryOperator *E) {
  7791. if (E->isCompoundAssignmentOp()) {
  7792. HandleValue(E->getLHS());
  7793. Visit(E->getRHS());
  7794. return;
  7795. }
  7796. Inherited::VisitBinaryOperator(E);
  7797. }
  7798. // A custom visitor for BinaryConditionalOperator is needed because the
  7799. // regular visitor would check the condition and true expression separately
  7800. // but both point to the same place giving duplicate diagnostics.
  7801. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  7802. Visit(E->getCond());
  7803. Visit(E->getFalseExpr());
  7804. }
  7805. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  7806. Decl* ReferenceDecl = DRE->getDecl();
  7807. if (OrigDecl != ReferenceDecl) return;
  7808. unsigned diag;
  7809. if (isReferenceType) {
  7810. diag = diag::warn_uninit_self_reference_in_reference_init;
  7811. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  7812. diag = diag::warn_static_self_reference_in_init;
  7813. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  7814. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  7815. DRE->getDecl()->getType()->isRecordType()) {
  7816. diag = diag::warn_uninit_self_reference_in_init;
  7817. } else {
  7818. // Local variables will be handled by the CFG analysis.
  7819. return;
  7820. }
  7821. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  7822. S.PDiag(diag)
  7823. << DRE->getNameInfo().getName()
  7824. << OrigDecl->getLocation()
  7825. << DRE->getSourceRange());
  7826. }
  7827. };
  7828. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  7829. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  7830. bool DirectInit) {
  7831. // Parameters arguments are occassionially constructed with itself,
  7832. // for instance, in recursive functions. Skip them.
  7833. if (isa<ParmVarDecl>(OrigDecl))
  7834. return;
  7835. E = E->IgnoreParens();
  7836. // Skip checking T a = a where T is not a record or reference type.
  7837. // Doing so is a way to silence uninitialized warnings.
  7838. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  7839. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  7840. if (ICE->getCastKind() == CK_LValueToRValue)
  7841. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  7842. if (DRE->getDecl() == OrigDecl)
  7843. return;
  7844. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  7845. }
  7846. }
  7847. /// AddInitializerToDecl - Adds the initializer Init to the
  7848. /// declaration dcl. If DirectInit is true, this is C++ direct
  7849. /// initialization rather than copy initialization.
  7850. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  7851. bool DirectInit, bool TypeMayContainAuto) {
  7852. // If there is no declaration, there was an error parsing it. Just ignore
  7853. // the initializer.
  7854. if (!RealDecl || RealDecl->isInvalidDecl()) {
  7855. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  7856. return;
  7857. }
  7858. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  7859. // Pure-specifiers are handled in ActOnPureSpecifier.
  7860. Diag(Method->getLocation(), diag::err_member_function_initialization)
  7861. << Method->getDeclName() << Init->getSourceRange();
  7862. Method->setInvalidDecl();
  7863. return;
  7864. }
  7865. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  7866. if (!VDecl) {
  7867. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  7868. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  7869. RealDecl->setInvalidDecl();
  7870. return;
  7871. }
  7872. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7873. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  7874. if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
  7875. // Attempt typo correction early so that the type of the init expression can
  7876. // be deduced based on the chosen correction:if the original init contains a
  7877. // TypoExpr.
  7878. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  7879. if (!Res.isUsable()) {
  7880. RealDecl->setInvalidDecl();
  7881. return;
  7882. }
  7883. if (Res.get() != Init) {
  7884. Init = Res.get();
  7885. if (CXXDirectInit)
  7886. CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7887. }
  7888. Expr *DeduceInit = Init;
  7889. // Initializer could be a C++ direct-initializer. Deduction only works if it
  7890. // contains exactly one expression.
  7891. if (CXXDirectInit) {
  7892. if (CXXDirectInit->getNumExprs() == 0) {
  7893. // It isn't possible to write this directly, but it is possible to
  7894. // end up in this situation with "auto x(some_pack...);"
  7895. Diag(CXXDirectInit->getLocStart(),
  7896. VDecl->isInitCapture() ? diag::err_init_capture_no_expression
  7897. : diag::err_auto_var_init_no_expression)
  7898. << VDecl->getDeclName() << VDecl->getType()
  7899. << VDecl->getSourceRange();
  7900. RealDecl->setInvalidDecl();
  7901. return;
  7902. } else if (CXXDirectInit->getNumExprs() > 1) {
  7903. Diag(CXXDirectInit->getExpr(1)->getLocStart(),
  7904. VDecl->isInitCapture()
  7905. ? diag::err_init_capture_multiple_expressions
  7906. : diag::err_auto_var_init_multiple_expressions)
  7907. << VDecl->getDeclName() << VDecl->getType()
  7908. << VDecl->getSourceRange();
  7909. RealDecl->setInvalidDecl();
  7910. return;
  7911. } else {
  7912. DeduceInit = CXXDirectInit->getExpr(0);
  7913. if (isa<InitListExpr>(DeduceInit))
  7914. Diag(CXXDirectInit->getLocStart(),
  7915. diag::err_auto_var_init_paren_braces)
  7916. << VDecl->getDeclName() << VDecl->getType()
  7917. << VDecl->getSourceRange();
  7918. }
  7919. }
  7920. // Expressions default to 'id' when we're in a debugger.
  7921. bool DefaultedToAuto = false;
  7922. if (getLangOpts().DebuggerCastResultToId &&
  7923. Init->getType() == Context.UnknownAnyTy) {
  7924. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  7925. if (Result.isInvalid()) {
  7926. VDecl->setInvalidDecl();
  7927. return;
  7928. }
  7929. Init = Result.get();
  7930. DefaultedToAuto = true;
  7931. }
  7932. QualType DeducedType;
  7933. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  7934. DAR_Failed)
  7935. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  7936. if (DeducedType.isNull()) {
  7937. RealDecl->setInvalidDecl();
  7938. return;
  7939. }
  7940. VDecl->setType(DeducedType);
  7941. assert(VDecl->isLinkageValid());
  7942. // In ARC, infer lifetime.
  7943. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  7944. VDecl->setInvalidDecl();
  7945. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  7946. // 'id' instead of a specific object type prevents most of our usual checks.
  7947. // We only want to warn outside of template instantiations, though:
  7948. // inside a template, the 'id' could have come from a parameter.
  7949. if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
  7950. DeducedType->isObjCIdType()) {
  7951. SourceLocation Loc =
  7952. VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
  7953. Diag(Loc, diag::warn_auto_var_is_id)
  7954. << VDecl->getDeclName() << DeduceInit->getSourceRange();
  7955. }
  7956. // If this is a redeclaration, check that the type we just deduced matches
  7957. // the previously declared type.
  7958. assert(!getLangOpts().HLSL && "auto types are not supported - merge type below is inconsequential"); // HLSL Change
  7959. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  7960. // We never need to merge the type, because we cannot form an incomplete
  7961. // array of auto, nor deduce such a type.
  7962. ShadowMergeState MergeState = ShadowMergeState_Disallowed; // HLSL Change - add merge state
  7963. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false, MergeState); // HLSL Change - add merge state
  7964. }
  7965. // Check the deduced type is valid for a variable declaration.
  7966. CheckVariableDeclarationType(VDecl);
  7967. if (VDecl->isInvalidDecl())
  7968. return;
  7969. // If all looks well, warn if this is a case that will change meaning when
  7970. // we implement N3922.
  7971. if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
  7972. Diag(Init->getLocStart(),
  7973. diag::warn_auto_var_direct_list_init)
  7974. << FixItHint::CreateInsertion(Init->getLocStart(), "=");
  7975. }
  7976. }
  7977. // dllimport cannot be used on variable definitions.
  7978. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  7979. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  7980. VDecl->setInvalidDecl();
  7981. return;
  7982. }
  7983. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  7984. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  7985. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  7986. VDecl->setInvalidDecl();
  7987. return;
  7988. }
  7989. if (!VDecl->getType()->isDependentType()) {
  7990. // A definition must end up with a complete type, which means it must be
  7991. // complete with the restriction that an array type might be completed by
  7992. // the initializer; note that later code assumes this restriction.
  7993. QualType BaseDeclType = VDecl->getType();
  7994. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  7995. BaseDeclType = Array->getElementType();
  7996. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  7997. diag::err_typecheck_decl_incomplete_type)) {
  7998. RealDecl->setInvalidDecl();
  7999. return;
  8000. }
  8001. // The variable can not have an abstract class type.
  8002. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  8003. diag::err_abstract_type_in_decl,
  8004. AbstractVariableType))
  8005. VDecl->setInvalidDecl();
  8006. }
  8007. VarDecl *Def;
  8008. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  8009. NamedDecl *Hidden = nullptr;
  8010. if (!hasVisibleDefinition(Def, &Hidden) &&
  8011. (VDecl->getFormalLinkage() == InternalLinkage ||
  8012. VDecl->getDescribedVarTemplate() ||
  8013. VDecl->getNumTemplateParameterLists() ||
  8014. VDecl->getDeclContext()->isDependentContext())) {
  8015. // The previous definition is hidden, and multiple definitions are
  8016. // permitted (in separate TUs). Form another definition of it.
  8017. } else {
  8018. Diag(VDecl->getLocation(), diag::err_redefinition)
  8019. << VDecl->getDeclName();
  8020. Diag(Def->getLocation(), diag::note_previous_definition);
  8021. VDecl->setInvalidDecl();
  8022. return;
  8023. }
  8024. }
  8025. if (getLangOpts().CPlusPlus) {
  8026. // C++ [class.static.data]p4
  8027. // If a static data member is of const integral or const
  8028. // enumeration type, its declaration in the class definition can
  8029. // specify a constant-initializer which shall be an integral
  8030. // constant expression (5.19). In that case, the member can appear
  8031. // in integral constant expressions. The member shall still be
  8032. // defined in a namespace scope if it is used in the program and the
  8033. // namespace scope definition shall not contain an initializer.
  8034. //
  8035. // We already performed a redefinition check above, but for static
  8036. // data members we also need to check whether there was an in-class
  8037. // declaration with an initializer.
  8038. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  8039. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  8040. << VDecl->getDeclName();
  8041. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  8042. diag::note_previous_initializer)
  8043. << 0;
  8044. return;
  8045. }
  8046. if (VDecl->hasLocalStorage())
  8047. getCurFunction()->setHasBranchProtectedScope();
  8048. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  8049. VDecl->setInvalidDecl();
  8050. return;
  8051. }
  8052. }
  8053. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  8054. // a kernel function cannot be initialized."
  8055. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  8056. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  8057. VDecl->setInvalidDecl();
  8058. return;
  8059. }
  8060. // Get the decls type and save a reference for later, since
  8061. // CheckInitializerTypes may change it.
  8062. QualType DclT = VDecl->getType(), SavT = DclT;
  8063. // Expressions default to 'id' when we're in a debugger
  8064. // and we are assigning it to a variable of Objective-C pointer type.
  8065. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  8066. Init->getType() == Context.UnknownAnyTy) {
  8067. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8068. if (Result.isInvalid()) {
  8069. VDecl->setInvalidDecl();
  8070. return;
  8071. }
  8072. Init = Result.get();
  8073. }
  8074. // Perform the initialization.
  8075. if (!VDecl->isInvalidDecl()) {
  8076. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  8077. InitializationKind Kind
  8078. = DirectInit ?
  8079. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  8080. Init->getLocStart(),
  8081. Init->getLocEnd())
  8082. : InitializationKind::CreateDirectList(
  8083. VDecl->getLocation())
  8084. : InitializationKind::CreateCopy(VDecl->getLocation(),
  8085. Init->getLocStart());
  8086. MultiExprArg Args = Init;
  8087. if (CXXDirectInit)
  8088. Args = MultiExprArg(CXXDirectInit->getExprs(),
  8089. CXXDirectInit->getNumExprs());
  8090. // Try to correct any TypoExprs in the initialization arguments.
  8091. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  8092. ExprResult Res = CorrectDelayedTyposInExpr(
  8093. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  8094. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  8095. return Init.Failed() ? ExprError() : E;
  8096. });
  8097. if (Res.isInvalid()) {
  8098. VDecl->setInvalidDecl();
  8099. } else if (Res.get() != Args[Idx]) {
  8100. Args[Idx] = Res.get();
  8101. }
  8102. }
  8103. if (VDecl->isInvalidDecl())
  8104. return;
  8105. InitializationSequence InitSeq(*this, Entity, Kind, Args);
  8106. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  8107. if (Result.isInvalid()) {
  8108. VDecl->setInvalidDecl();
  8109. return;
  8110. }
  8111. Init = Result.getAs<Expr>();
  8112. assert(Init != nullptr && "otherwise result should be invalid"); // HLSL Change
  8113. }
  8114. // Check for self-references within variable initializers.
  8115. // Variables declared within a function/method body (except for references)
  8116. // are handled by a dataflow analysis.
  8117. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  8118. VDecl->getType()->isReferenceType()) {
  8119. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  8120. }
  8121. // If the type changed, it means we had an incomplete type that was
  8122. // completed by the initializer. For example:
  8123. // int ary[] = { 1, 3, 5 };
  8124. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  8125. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  8126. VDecl->setType(DclT);
  8127. #if 0 // HLSL Change Starts - no ObjC support
  8128. if (!VDecl->isInvalidDecl()) {
  8129. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  8130. if (VDecl->hasAttr<BlocksAttr>())
  8131. checkRetainCycles(VDecl, Init);
  8132. // It is safe to assign a weak reference into a strong variable.
  8133. // Although this code can still have problems:
  8134. // id x = self.weakProp;
  8135. // id y = self.weakProp;
  8136. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8137. // paths through the function. This should be revisited if
  8138. // -Wrepeated-use-of-weak is made flow-sensitive.
  8139. if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
  8140. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8141. Init->getLocStart()))
  8142. getCurFunction()->markSafeWeakUse(Init);
  8143. }
  8144. #endif // HLSL Change Ends - no ObjC support
  8145. // The initialization is usually a full-expression.
  8146. //
  8147. // FIXME: If this is a braced initialization of an aggregate, it is not
  8148. // an expression, and each individual field initializer is a separate
  8149. // full-expression. For instance, in:
  8150. //
  8151. // struct Temp { ~Temp(); };
  8152. // struct S { S(Temp); };
  8153. // struct T { S a, b; } t = { Temp(), Temp() }
  8154. //
  8155. // we should destroy the first Temp before constructing the second.
  8156. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  8157. false,
  8158. VDecl->isConstexpr());
  8159. if (Result.isInvalid()) {
  8160. VDecl->setInvalidDecl();
  8161. return;
  8162. }
  8163. Init = Result.get();
  8164. // Attach the initializer to the decl.
  8165. VDecl->setInit(Init);
  8166. if (VDecl->isLocalVarDecl()) {
  8167. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  8168. // static storage duration shall be constant expressions or string literals.
  8169. // C++ does not have this restriction.
  8170. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
  8171. const Expr *Culprit;
  8172. if (VDecl->getStorageClass() == SC_Static)
  8173. CheckForConstantInitializer(Init, DclT);
  8174. // C89 is stricter than C99 for non-static aggregate types.
  8175. // C89 6.5.7p3: All the expressions [...] in an initializer list
  8176. // for an object that has aggregate or union type shall be
  8177. // constant expressions.
  8178. else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  8179. isa<InitListExpr>(Init) &&
  8180. !Init->isConstantInitializer(Context, false, &Culprit))
  8181. Diag(Culprit->getExprLoc(),
  8182. diag::ext_aggregate_init_not_constant)
  8183. << Culprit->getSourceRange();
  8184. }
  8185. } else if (VDecl->isStaticDataMember() &&
  8186. VDecl->getLexicalDeclContext()->isRecord()) {
  8187. // This is an in-class initialization for a static data member, e.g.,
  8188. //
  8189. // struct S {
  8190. // static const int value = 17;
  8191. // };
  8192. // C++ [class.mem]p4:
  8193. // A member-declarator can contain a constant-initializer only
  8194. // if it declares a static member (9.4) of const integral or
  8195. // const enumeration type, see 9.4.2.
  8196. //
  8197. // C++11 [class.static.data]p3:
  8198. // If a non-volatile const static data member is of integral or
  8199. // enumeration type, its declaration in the class definition can
  8200. // specify a brace-or-equal-initializer in which every initalizer-clause
  8201. // that is an assignment-expression is a constant expression. A static
  8202. // data member of literal type can be declared in the class definition
  8203. // with the constexpr specifier; if so, its declaration shall specify a
  8204. // brace-or-equal-initializer in which every initializer-clause that is
  8205. // an assignment-expression is a constant expression.
  8206. // Do nothing on dependent types.
  8207. if (DclT->isDependentType()) {
  8208. // Allow any 'static constexpr' members, whether or not they are of literal
  8209. // type. We separately check that every constexpr variable is of literal
  8210. // type.
  8211. } else if (VDecl->isConstexpr()) {
  8212. // Require constness.
  8213. } else if (!DclT.isConstQualified()) {
  8214. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  8215. << Init->getSourceRange();
  8216. VDecl->setInvalidDecl();
  8217. // We allow integer constant expressions in all cases.
  8218. } else if (DclT->isIntegralOrEnumerationType()) {
  8219. // Check whether the expression is a constant expression.
  8220. SourceLocation Loc;
  8221. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  8222. // In C++11, a non-constexpr const static data member with an
  8223. // in-class initializer cannot be volatile.
  8224. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  8225. else if (Init->isValueDependent())
  8226. ; // Nothing to check.
  8227. else if (Init->isIntegerConstantExpr(Context, &Loc))
  8228. ; // Ok, it's an ICE!
  8229. else if (Init->isEvaluatable(Context)) {
  8230. // If we can constant fold the initializer through heroics, accept it,
  8231. // but report this as a use of an extension for -pedantic.
  8232. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  8233. << Init->getSourceRange();
  8234. } else {
  8235. // Otherwise, this is some crazy unknown case. Report the issue at the
  8236. // location provided by the isIntegerConstantExpr failed check.
  8237. Diag(Loc, diag::err_in_class_initializer_non_constant)
  8238. << Init->getSourceRange();
  8239. VDecl->setInvalidDecl();
  8240. }
  8241. // We allow foldable floating-point constants as an extension.
  8242. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  8243. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  8244. // it anyway and provide a fixit to add the 'constexpr'.
  8245. if (getLangOpts().CPlusPlus11) {
  8246. Diag(VDecl->getLocation(),
  8247. diag::ext_in_class_initializer_float_type_cxx11)
  8248. << DclT << Init->getSourceRange();
  8249. Diag(VDecl->getLocStart(),
  8250. diag::note_in_class_initializer_float_type_cxx11)
  8251. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8252. } else {
  8253. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  8254. << DclT << Init->getSourceRange();
  8255. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  8256. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  8257. << Init->getSourceRange();
  8258. VDecl->setInvalidDecl();
  8259. }
  8260. }
  8261. // Suggest adding 'constexpr' in C++11 for literal types.
  8262. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  8263. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  8264. << DclT << Init->getSourceRange()
  8265. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8266. VDecl->setConstexpr(true);
  8267. } else {
  8268. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  8269. << DclT << Init->getSourceRange();
  8270. VDecl->setInvalidDecl();
  8271. }
  8272. } else if (VDecl->isFileVarDecl()) {
  8273. if (VDecl->getStorageClass() == SC_Extern &&
  8274. (!getLangOpts().CPlusPlus ||
  8275. !VDecl->isExternC()) &&
  8276. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  8277. Diag(VDecl->getLocation(), diag::warn_extern_init);
  8278. // C99 6.7.8p4. All file scoped initializers need to be constant.
  8279. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  8280. CheckForConstantInitializer(Init, DclT);
  8281. }
  8282. // We will represent direct-initialization similarly to copy-initialization:
  8283. // int x(1); -as-> int x = 1;
  8284. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  8285. //
  8286. // Clients that want to distinguish between the two forms, can check for
  8287. // direct initializer using VarDecl::getInitStyle().
  8288. // A major benefit is that clients that don't particularly care about which
  8289. // exactly form was it (like the CodeGen) can handle both cases without
  8290. // special case code.
  8291. // C++ 8.5p11:
  8292. // The form of initialization (using parentheses or '=') is generally
  8293. // insignificant, but does matter when the entity being initialized has a
  8294. // class type.
  8295. if (CXXDirectInit) {
  8296. assert(DirectInit && "Call-style initializer must be direct init.");
  8297. VDecl->setInitStyle(VarDecl::CallInit);
  8298. } else if (DirectInit) {
  8299. // This must be list-initialization. No other way is direct-initialization.
  8300. VDecl->setInitStyle(VarDecl::ListInit);
  8301. }
  8302. CheckCompleteVariableDeclaration(VDecl);
  8303. }
  8304. /// ActOnInitializerError - Given that there was an error parsing an
  8305. /// initializer for the given declaration, try to return to some form
  8306. /// of sanity.
  8307. void Sema::ActOnInitializerError(Decl *D) {
  8308. // Our main concern here is re-establishing invariants like "a
  8309. // variable's type is either dependent or complete".
  8310. if (!D || D->isInvalidDecl()) return;
  8311. VarDecl *VD = dyn_cast<VarDecl>(D);
  8312. if (!VD) return;
  8313. // Auto types are meaningless if we can't make sense of the initializer.
  8314. if (ParsingInitForAutoVars.count(D)) {
  8315. D->setInvalidDecl();
  8316. return;
  8317. }
  8318. QualType Ty = VD->getType();
  8319. if (Ty->isDependentType()) return;
  8320. // Require a complete type.
  8321. if (RequireCompleteType(VD->getLocation(),
  8322. Context.getBaseElementType(Ty),
  8323. diag::err_typecheck_decl_incomplete_type)) {
  8324. VD->setInvalidDecl();
  8325. return;
  8326. }
  8327. // Require a non-abstract type.
  8328. if (RequireNonAbstractType(VD->getLocation(), Ty,
  8329. diag::err_abstract_type_in_decl,
  8330. AbstractVariableType)) {
  8331. VD->setInvalidDecl();
  8332. return;
  8333. }
  8334. // Don't bother complaining about constructors or destructors,
  8335. // though.
  8336. }
  8337. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  8338. bool TypeMayContainAuto) {
  8339. // If there is no declaration, there was an error parsing it. Just ignore it.
  8340. if (!RealDecl)
  8341. return;
  8342. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  8343. QualType Type = Var->getType();
  8344. // C++11 [dcl.spec.auto]p3
  8345. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  8346. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  8347. << Var->getDeclName() << Type;
  8348. Var->setInvalidDecl();
  8349. return;
  8350. }
  8351. // C++11 [class.static.data]p3: A static data member can be declared with
  8352. // the constexpr specifier; if so, its declaration shall specify
  8353. // a brace-or-equal-initializer.
  8354. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  8355. // the definition of a variable [...] or the declaration of a static data
  8356. // member.
  8357. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  8358. if (Var->isStaticDataMember())
  8359. Diag(Var->getLocation(),
  8360. diag::err_constexpr_static_mem_var_requires_init)
  8361. << Var->getDeclName();
  8362. else
  8363. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  8364. Var->setInvalidDecl();
  8365. return;
  8366. }
  8367. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  8368. // be initialized.
  8369. if (!Var->isInvalidDecl() &&
  8370. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  8371. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  8372. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  8373. Var->setInvalidDecl();
  8374. return;
  8375. }
  8376. switch (Var->isThisDeclarationADefinition()) {
  8377. case VarDecl::Definition:
  8378. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  8379. break;
  8380. // We have an out-of-line definition of a static data member
  8381. // that has an in-class initializer, so we type-check this like
  8382. // a declaration.
  8383. //
  8384. // Fall through
  8385. case VarDecl::DeclarationOnly:
  8386. // It's only a declaration.
  8387. // Block scope. C99 6.7p7: If an identifier for an object is
  8388. // declared with no linkage (C99 6.2.2p6), the type for the
  8389. // object shall be complete.
  8390. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  8391. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  8392. RequireCompleteType(Var->getLocation(), Type,
  8393. diag::err_typecheck_decl_incomplete_type))
  8394. Var->setInvalidDecl();
  8395. // Make sure that the type is not abstract.
  8396. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  8397. RequireNonAbstractType(Var->getLocation(), Type,
  8398. diag::err_abstract_type_in_decl,
  8399. AbstractVariableType))
  8400. Var->setInvalidDecl();
  8401. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  8402. Var->getStorageClass() == SC_PrivateExtern) {
  8403. Diag(Var->getLocation(), diag::warn_private_extern);
  8404. Diag(Var->getLocation(), diag::note_private_extern);
  8405. }
  8406. return;
  8407. case VarDecl::TentativeDefinition:
  8408. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  8409. // object that has file scope without an initializer, and without a
  8410. // storage-class specifier or with the storage-class specifier "static",
  8411. // constitutes a tentative definition. Note: A tentative definition with
  8412. // external linkage is valid (C99 6.2.2p5).
  8413. if (!Var->isInvalidDecl()) {
  8414. if (const IncompleteArrayType *ArrayT
  8415. = Context.getAsIncompleteArrayType(Type)) {
  8416. if (RequireCompleteType(Var->getLocation(),
  8417. ArrayT->getElementType(),
  8418. diag::err_illegal_decl_array_incomplete_type))
  8419. Var->setInvalidDecl();
  8420. } else if (Var->getStorageClass() == SC_Static) {
  8421. // C99 6.9.2p3: If the declaration of an identifier for an object is
  8422. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  8423. // declared type shall not be an incomplete type.
  8424. // NOTE: code such as the following
  8425. // static struct s;
  8426. // struct s { int a; };
  8427. // is accepted by gcc. Hence here we issue a warning instead of
  8428. // an error and we do not invalidate the static declaration.
  8429. // NOTE: to avoid multiple warnings, only check the first declaration.
  8430. if (Var->isFirstDecl())
  8431. RequireCompleteType(Var->getLocation(), Type,
  8432. diag::ext_typecheck_decl_incomplete_type);
  8433. }
  8434. }
  8435. // Record the tentative definition; we're done.
  8436. if (!Var->isInvalidDecl())
  8437. TentativeDefinitions.push_back(Var);
  8438. return;
  8439. }
  8440. // Provide a specific diagnostic for uninitialized variable
  8441. // definitions with incomplete array type.
  8442. if (Type->isIncompleteArrayType()
  8443. // HLSL Change Starts
  8444. // Allow incomplete resource array.
  8445. && !hlsl::IsIncompleteHLSLResourceArrayType(getASTContext(), Type)
  8446. // Allow incomplete ConstantBufferView array.
  8447. && !(IsOnHLSLBufferView())
  8448. // HLSL Change Ends
  8449. ) {
  8450. Diag(Var->getLocation(),
  8451. diag::err_typecheck_incomplete_array_needs_initializer);
  8452. Var->setInvalidDecl();
  8453. return;
  8454. }
  8455. // Provide a specific diagnostic for uninitialized variable
  8456. // definitions with reference type.
  8457. if (Type->isReferenceType()) {
  8458. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  8459. << Var->getDeclName()
  8460. << SourceRange(Var->getLocation(), Var->getLocation());
  8461. Var->setInvalidDecl();
  8462. return;
  8463. }
  8464. // Do not attempt to type-check the default initializer for a
  8465. // variable with dependent type.
  8466. if (Type->isDependentType())
  8467. return;
  8468. if (Var->isInvalidDecl())
  8469. return;
  8470. if (!Var->hasAttr<AliasAttr>()) {
  8471. if (RequireCompleteType(Var->getLocation(),
  8472. Context.getBaseElementType(Type),
  8473. diag::err_typecheck_decl_incomplete_type)) {
  8474. Var->setInvalidDecl();
  8475. return;
  8476. }
  8477. } else {
  8478. return;
  8479. }
  8480. // The variable can not have an abstract class type.
  8481. if (RequireNonAbstractType(Var->getLocation(), Type,
  8482. diag::err_abstract_type_in_decl,
  8483. AbstractVariableType)) {
  8484. Var->setInvalidDecl();
  8485. return;
  8486. }
  8487. // Check for jumps past the implicit initializer. C++0x
  8488. // clarifies that this applies to a "variable with automatic
  8489. // storage duration", not a "local variable".
  8490. // C++11 [stmt.dcl]p3
  8491. // A program that jumps from a point where a variable with automatic
  8492. // storage duration is not in scope to a point where it is in scope is
  8493. // ill-formed unless the variable has scalar type, class type with a
  8494. // trivial default constructor and a trivial destructor, a cv-qualified
  8495. // version of one of these types, or an array of one of the preceding
  8496. // types and is declared without an initializer.
  8497. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  8498. if (const RecordType *Record
  8499. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  8500. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  8501. // Mark the function for further checking even if the looser rules of
  8502. // C++11 do not require such checks, so that we can diagnose
  8503. // incompatibilities with C++98.
  8504. if (!CXXRecord->isPOD())
  8505. getCurFunction()->setHasBranchProtectedScope();
  8506. }
  8507. }
  8508. // C++03 [dcl.init]p9:
  8509. // If no initializer is specified for an object, and the
  8510. // object is of (possibly cv-qualified) non-POD class type (or
  8511. // array thereof), the object shall be default-initialized; if
  8512. // the object is of const-qualified type, the underlying class
  8513. // type shall have a user-declared default
  8514. // constructor. Otherwise, if no initializer is specified for
  8515. // a non- static object, the object and its subobjects, if
  8516. // any, have an indeterminate initial value); if the object
  8517. // or any of its subobjects are of const-qualified type, the
  8518. // program is ill-formed.
  8519. // C++0x [dcl.init]p11:
  8520. // If no initializer is specified for an object, the object is
  8521. // default-initialized; [...].
  8522. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  8523. InitializationKind Kind
  8524. = InitializationKind::CreateDefault(Var->getLocation());
  8525. InitializationSequence InitSeq(*this, Entity, Kind, None);
  8526. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  8527. if (Init.isInvalid())
  8528. Var->setInvalidDecl();
  8529. else if (Init.get()) {
  8530. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  8531. // This is important for template substitution.
  8532. Var->setInitStyle(VarDecl::CallInit);
  8533. }
  8534. CheckCompleteVariableDeclaration(Var);
  8535. }
  8536. }
  8537. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  8538. VarDecl *VD = dyn_cast<VarDecl>(D);
  8539. if (!VD) {
  8540. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  8541. D->setInvalidDecl();
  8542. return;
  8543. }
  8544. VD->setCXXForRangeDecl(true);
  8545. // for-range-declaration cannot be given a storage class specifier.
  8546. int Error = -1;
  8547. switch (VD->getStorageClass()) {
  8548. case SC_None:
  8549. break;
  8550. case SC_Extern:
  8551. Error = 0;
  8552. break;
  8553. case SC_Static:
  8554. Error = 1;
  8555. break;
  8556. case SC_PrivateExtern:
  8557. Error = 2;
  8558. break;
  8559. case SC_Auto:
  8560. Error = 3;
  8561. break;
  8562. case SC_Register:
  8563. Error = 4;
  8564. break;
  8565. case SC_OpenCLWorkGroupLocal:
  8566. llvm_unreachable("Unexpected storage class");
  8567. }
  8568. if (Error != -1) {
  8569. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  8570. << VD->getDeclName() << Error;
  8571. D->setInvalidDecl();
  8572. }
  8573. }
  8574. StmtResult
  8575. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  8576. IdentifierInfo *Ident,
  8577. ParsedAttributes &Attrs,
  8578. SourceLocation AttrEnd) {
  8579. // C++1y [stmt.iter]p1:
  8580. // A range-based for statement of the form
  8581. // for ( for-range-identifier : for-range-initializer ) statement
  8582. // is equivalent to
  8583. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  8584. DeclSpec DS(Attrs.getPool().getFactory());
  8585. const char *PrevSpec;
  8586. unsigned DiagID;
  8587. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  8588. getPrintingPolicy());
  8589. Declarator D(DS, Declarator::ForContext);
  8590. D.SetIdentifier(Ident, IdentLoc);
  8591. D.takeAttributes(Attrs, AttrEnd);
  8592. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  8593. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  8594. EmptyAttrs, IdentLoc);
  8595. Decl *Var = ActOnDeclarator(S, D);
  8596. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  8597. FinalizeDeclaration(Var);
  8598. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  8599. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  8600. }
  8601. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  8602. if (var->isInvalidDecl()) return;
  8603. // In ARC, don't allow jumps past the implicit initialization of a
  8604. // local retaining variable.
  8605. if (getLangOpts().ObjCAutoRefCount &&
  8606. var->hasLocalStorage()) {
  8607. switch (var->getType().getObjCLifetime()) {
  8608. case Qualifiers::OCL_None:
  8609. case Qualifiers::OCL_ExplicitNone:
  8610. case Qualifiers::OCL_Autoreleasing:
  8611. break;
  8612. case Qualifiers::OCL_Weak:
  8613. case Qualifiers::OCL_Strong:
  8614. getCurFunction()->setHasBranchProtectedScope();
  8615. break;
  8616. }
  8617. }
  8618. // Warn about externally-visible variables being defined without a
  8619. // prior declaration. We only want to do this for global
  8620. // declarations, but we also specifically need to avoid doing it for
  8621. // class members because the linkage of an anonymous class can
  8622. // change if it's later given a typedef name.
  8623. if (var->isThisDeclarationADefinition() &&
  8624. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  8625. var->isExternallyVisible() && var->hasLinkage() &&
  8626. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  8627. var->getLocation())) {
  8628. // Find a previous declaration that's not a definition.
  8629. VarDecl *prev = var->getPreviousDecl();
  8630. while (prev && prev->isThisDeclarationADefinition())
  8631. prev = prev->getPreviousDecl();
  8632. if (!prev)
  8633. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  8634. }
  8635. if (var->getTLSKind() == VarDecl::TLS_Static) {
  8636. const Expr *Culprit;
  8637. if (var->getType().isDestructedType()) {
  8638. // GNU C++98 edits for __thread, [basic.start.term]p3:
  8639. // The type of an object with thread storage duration shall not
  8640. // have a non-trivial destructor.
  8641. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  8642. if (getLangOpts().CPlusPlus11)
  8643. Diag(var->getLocation(), diag::note_use_thread_local);
  8644. } else if (getLangOpts().CPlusPlus && var->hasInit() &&
  8645. !var->getInit()->isConstantInitializer(
  8646. Context, var->getType()->isReferenceType(), &Culprit)) {
  8647. // GNU C++98 edits for __thread, [basic.start.init]p4:
  8648. // An object of thread storage duration shall not require dynamic
  8649. // initialization.
  8650. // FIXME: Need strict checking here.
  8651. Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
  8652. << Culprit->getSourceRange();
  8653. if (getLangOpts().CPlusPlus11)
  8654. Diag(var->getLocation(), diag::note_use_thread_local);
  8655. }
  8656. }
  8657. // Apply section attributes and pragmas to global variables.
  8658. bool GlobalStorage = var->hasGlobalStorage();
  8659. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  8660. ActiveTemplateInstantiations.empty()) {
  8661. PragmaStack<StringLiteral *> *Stack = nullptr;
  8662. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  8663. if (var->getType().isConstQualified())
  8664. Stack = &ConstSegStack;
  8665. else if (!var->getInit()) {
  8666. Stack = &BSSSegStack;
  8667. SectionFlags |= ASTContext::PSF_Write;
  8668. } else {
  8669. Stack = &DataSegStack;
  8670. SectionFlags |= ASTContext::PSF_Write;
  8671. }
  8672. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  8673. var->addAttr(SectionAttr::CreateImplicit(
  8674. Context, SectionAttr::Declspec_allocate,
  8675. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  8676. }
  8677. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  8678. if (UnifySection(SA->getName(), SectionFlags, var))
  8679. var->dropAttr<SectionAttr>();
  8680. // Apply the init_seg attribute if this has an initializer. If the
  8681. // initializer turns out to not be dynamic, we'll end up ignoring this
  8682. // attribute.
  8683. if (CurInitSeg && var->getInit())
  8684. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  8685. CurInitSegLoc));
  8686. }
  8687. // All the following checks are C++ only.
  8688. if (!getLangOpts().CPlusPlus) return;
  8689. QualType type = var->getType();
  8690. if (type->isDependentType()) return;
  8691. // __block variables might require us to capture a copy-initializer.
  8692. if (var->hasAttr<BlocksAttr>()) {
  8693. // It's currently invalid to ever have a __block variable with an
  8694. // array type; should we diagnose that here?
  8695. // Regardless, we don't want to ignore array nesting when
  8696. // constructing this copy.
  8697. if (type->isStructureOrClassType()) {
  8698. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  8699. SourceLocation poi = var->getLocation();
  8700. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  8701. ExprResult result
  8702. = PerformMoveOrCopyInitialization(
  8703. InitializedEntity::InitializeBlock(poi, type, false),
  8704. var, var->getType(), varRef, /*AllowNRVO=*/true);
  8705. if (!result.isInvalid()) {
  8706. result = MaybeCreateExprWithCleanups(result);
  8707. Expr *init = result.getAs<Expr>();
  8708. Context.setBlockVarCopyInits(var, init);
  8709. }
  8710. }
  8711. }
  8712. Expr *Init = var->getInit();
  8713. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  8714. QualType baseType = Context.getBaseElementType(type);
  8715. if (!var->getDeclContext()->isDependentContext() &&
  8716. Init && !Init->isValueDependent()) {
  8717. if (IsGlobal && !var->isConstexpr() &&
  8718. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  8719. var->getLocation())) {
  8720. // Warn about globals which don't have a constant initializer. Don't
  8721. // warn about globals with a non-trivial destructor because we already
  8722. // warned about them.
  8723. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  8724. if (!(RD && !RD->hasTrivialDestructor()) &&
  8725. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  8726. Diag(var->getLocation(), diag::warn_global_constructor)
  8727. << Init->getSourceRange();
  8728. }
  8729. if (var->isConstexpr()) {
  8730. SmallVector<PartialDiagnosticAt, 8> Notes;
  8731. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  8732. SourceLocation DiagLoc = var->getLocation();
  8733. // If the note doesn't add any useful information other than a source
  8734. // location, fold it into the primary diagnostic.
  8735. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  8736. diag::note_invalid_subexpr_in_const_expr) {
  8737. DiagLoc = Notes[0].first;
  8738. Notes.clear();
  8739. }
  8740. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  8741. << var << Init->getSourceRange();
  8742. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  8743. Diag(Notes[I].first, Notes[I].second);
  8744. }
  8745. } else if (var->isUsableInConstantExpressions(Context)) {
  8746. // Check whether the initializer of a const variable of integral or
  8747. // enumeration type is an ICE now, since we can't tell whether it was
  8748. // initialized by a constant expression if we check later.
  8749. var->checkInitIsICE();
  8750. }
  8751. }
  8752. // Require the destructor.
  8753. if (const RecordType *recordType = baseType->getAs<RecordType>())
  8754. FinalizeVarWithDestructor(var, recordType);
  8755. }
  8756. /// \brief Determines if a variable's alignment is dependent.
  8757. static bool hasDependentAlignment(VarDecl *VD) {
  8758. if (VD->getType()->isDependentType())
  8759. return true;
  8760. for (auto *I : VD->specific_attrs<AlignedAttr>())
  8761. if (I->isAlignmentDependent())
  8762. return true;
  8763. return false;
  8764. }
  8765. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  8766. /// any semantic actions necessary after any initializer has been attached.
  8767. void
  8768. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  8769. // Note that we are no longer parsing the initializer for this declaration.
  8770. ParsingInitForAutoVars.erase(ThisDecl);
  8771. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  8772. if (!VD)
  8773. return;
  8774. checkAttributesAfterMerging(*this, *VD);
  8775. // Perform TLS alignment check here after attributes attached to the variable
  8776. // which may affect the alignment have been processed. Only perform the check
  8777. // if the target has a maximum TLS alignment (zero means no constraints).
  8778. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  8779. // Protect the check so that it's not performed on dependent types and
  8780. // dependent alignments (we can't determine the alignment in that case).
  8781. if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
  8782. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  8783. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  8784. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  8785. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  8786. << (unsigned)MaxAlignChars.getQuantity();
  8787. }
  8788. }
  8789. }
  8790. // Static locals inherit dll attributes from their function.
  8791. if (VD->isStaticLocal()) {
  8792. if (FunctionDecl *FD =
  8793. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  8794. if (Attr *A = getDLLAttr(FD)) {
  8795. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  8796. NewAttr->setInherited(true);
  8797. VD->addAttr(NewAttr);
  8798. }
  8799. }
  8800. }
  8801. // Grab the dllimport or dllexport attribute off of the VarDecl.
  8802. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  8803. // Imported static data members cannot be defined out-of-line.
  8804. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  8805. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  8806. VD->isThisDeclarationADefinition()) {
  8807. // We allow definitions of dllimport class template static data members
  8808. // with a warning.
  8809. CXXRecordDecl *Context =
  8810. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  8811. bool IsClassTemplateMember =
  8812. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  8813. Context->getDescribedClassTemplate();
  8814. Diag(VD->getLocation(),
  8815. IsClassTemplateMember
  8816. ? diag::warn_attribute_dllimport_static_field_definition
  8817. : diag::err_attribute_dllimport_static_field_definition);
  8818. Diag(IA->getLocation(), diag::note_attribute);
  8819. if (!IsClassTemplateMember)
  8820. VD->setInvalidDecl();
  8821. }
  8822. }
  8823. // dllimport/dllexport variables cannot be thread local, their TLS index
  8824. // isn't exported with the variable.
  8825. if (DLLAttr && VD->getTLSKind()) {
  8826. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  8827. << DLLAttr;
  8828. VD->setInvalidDecl();
  8829. }
  8830. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  8831. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  8832. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  8833. VD->dropAttr<UsedAttr>();
  8834. }
  8835. }
  8836. const DeclContext *DC = VD->getDeclContext();
  8837. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8838. // member, set the visibility of this variable.
  8839. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  8840. AddPushedVisibilityAttribute(VD);
  8841. // FIXME: Warn on unused templates.
  8842. if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
  8843. !isa<VarTemplatePartialSpecializationDecl>(VD))
  8844. MarkUnusedFileScopedDecl(VD);
  8845. // Now we have parsed the initializer and can update the table of magic
  8846. // tag values.
  8847. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  8848. !VD->getType()->isIntegralOrEnumerationType())
  8849. return;
  8850. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  8851. const Expr *MagicValueExpr = VD->getInit();
  8852. if (!MagicValueExpr) {
  8853. continue;
  8854. }
  8855. llvm::APSInt MagicValueInt;
  8856. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  8857. Diag(I->getRange().getBegin(),
  8858. diag::err_type_tag_for_datatype_not_ice)
  8859. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  8860. continue;
  8861. }
  8862. if (MagicValueInt.getActiveBits() > 64) {
  8863. Diag(I->getRange().getBegin(),
  8864. diag::err_type_tag_for_datatype_too_large)
  8865. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  8866. continue;
  8867. }
  8868. uint64_t MagicValue = MagicValueInt.getZExtValue();
  8869. RegisterTypeTagForDatatype(I->getArgumentKind(),
  8870. MagicValue,
  8871. I->getMatchingCType(),
  8872. I->getLayoutCompatible(),
  8873. I->getMustBeNull());
  8874. }
  8875. }
  8876. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  8877. ArrayRef<Decl *> Group) {
  8878. SmallVector<Decl*, 8> Decls;
  8879. if (DS.isTypeSpecOwned())
  8880. Decls.push_back(DS.getRepAsDecl());
  8881. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  8882. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8883. if (Decl *D = Group[i]) {
  8884. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
  8885. if (!FirstDeclaratorInGroup)
  8886. FirstDeclaratorInGroup = DD;
  8887. Decls.push_back(D);
  8888. }
  8889. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  8890. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  8891. handleTagNumbering(Tag, S);
  8892. if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
  8893. Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
  8894. }
  8895. }
  8896. return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
  8897. }
  8898. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  8899. /// group, performing any necessary semantic checking.
  8900. Sema::DeclGroupPtrTy
  8901. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
  8902. bool TypeMayContainAuto) {
  8903. // C++0x [dcl.spec.auto]p7:
  8904. // If the type deduced for the template parameter U is not the same in each
  8905. // deduction, the program is ill-formed.
  8906. // FIXME: When initializer-list support is added, a distinction is needed
  8907. // between the deduced type U and the deduced type which 'auto' stands for.
  8908. // auto a = 0, b = { 1, 2, 3 };
  8909. // is legal because the deduced type U is 'int' in both cases.
  8910. if (TypeMayContainAuto && Group.size() > 1) {
  8911. QualType Deduced;
  8912. CanQualType DeducedCanon;
  8913. VarDecl *DeducedDecl = nullptr;
  8914. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  8915. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  8916. AutoType *AT = D->getType()->getContainedAutoType();
  8917. // Don't reissue diagnostics when instantiating a template.
  8918. if (AT && D->isInvalidDecl())
  8919. break;
  8920. QualType U = AT ? AT->getDeducedType() : QualType();
  8921. if (!U.isNull()) {
  8922. CanQualType UCanon = Context.getCanonicalType(U);
  8923. if (Deduced.isNull()) {
  8924. Deduced = U;
  8925. DeducedCanon = UCanon;
  8926. DeducedDecl = D;
  8927. } else if (DeducedCanon != UCanon) {
  8928. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  8929. diag::err_auto_different_deductions)
  8930. << (AT->isDecltypeAuto() ? 1 : 0)
  8931. << Deduced << DeducedDecl->getDeclName()
  8932. << U << D->getDeclName()
  8933. << DeducedDecl->getInit()->getSourceRange()
  8934. << D->getInit()->getSourceRange();
  8935. D->setInvalidDecl();
  8936. break;
  8937. }
  8938. }
  8939. }
  8940. }
  8941. }
  8942. ActOnDocumentableDecls(Group);
  8943. return DeclGroupPtrTy::make(
  8944. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  8945. }
  8946. void Sema::ActOnDocumentableDecl(Decl *D) {
  8947. ActOnDocumentableDecls(D);
  8948. }
  8949. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  8950. // Don't parse the comment if Doxygen diagnostics are ignored.
  8951. if (Group.empty() || !Group[0])
  8952. return;
  8953. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  8954. Group[0]->getLocation()) &&
  8955. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  8956. Group[0]->getLocation()))
  8957. return;
  8958. if (Group.size() >= 2) {
  8959. // This is a decl group. Normally it will contain only declarations
  8960. // produced from declarator list. But in case we have any definitions or
  8961. // additional declaration references:
  8962. // 'typedef struct S {} S;'
  8963. // 'typedef struct S *S;'
  8964. // 'struct S *pS;'
  8965. // FinalizeDeclaratorGroup adds these as separate declarations.
  8966. Decl *MaybeTagDecl = Group[0];
  8967. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  8968. Group = Group.slice(1);
  8969. }
  8970. }
  8971. // See if there are any new comments that are not attached to a decl.
  8972. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  8973. if (!Comments.empty() &&
  8974. !Comments.back()->isAttached()) {
  8975. // There is at least one comment that not attached to a decl.
  8976. // Maybe it should be attached to one of these decls?
  8977. //
  8978. // Note that this way we pick up not only comments that precede the
  8979. // declaration, but also comments that *follow* the declaration -- thanks to
  8980. // the lookahead in the lexer: we've consumed the semicolon and looked
  8981. // ahead through comments.
  8982. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8983. Context.getCommentForDecl(Group[i], &PP);
  8984. }
  8985. }
  8986. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  8987. /// to introduce parameters into function prototype scope.
  8988. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  8989. const DeclSpec &DS = D.getDeclSpec();
  8990. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  8991. // C++03 [dcl.stc]p2 also permits 'auto'.
  8992. StorageClass SC = SC_None;
  8993. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  8994. SC = SC_Register;
  8995. } else if (getLangOpts().CPlusPlus &&
  8996. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  8997. SC = SC_Auto;
  8998. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  8999. Diag(DS.getStorageClassSpecLoc(),
  9000. diag::err_invalid_storage_class_in_func_decl);
  9001. D.getMutableDeclSpec().ClearStorageClassSpecs();
  9002. }
  9003. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  9004. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  9005. << DeclSpec::getSpecifierName(TSCS);
  9006. if (DS.isConstexprSpecified())
  9007. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  9008. << 0;
  9009. DiagnoseFunctionSpecifiers(DS);
  9010. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  9011. QualType parmDeclType = TInfo->getType();
  9012. if (getLangOpts().CPlusPlus) {
  9013. // Check that there are no default arguments inside the type of this
  9014. // parameter.
  9015. CheckExtraCXXDefaultArguments(D);
  9016. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  9017. if (D.getCXXScopeSpec().isSet()) {
  9018. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  9019. << D.getCXXScopeSpec().getRange();
  9020. D.getCXXScopeSpec().clear();
  9021. }
  9022. }
  9023. // Ensure we have a valid name
  9024. IdentifierInfo *II = nullptr;
  9025. if (D.hasName()) {
  9026. II = D.getIdentifier();
  9027. if (!II) {
  9028. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  9029. << GetNameForDeclarator(D).getName();
  9030. D.setInvalidType(true);
  9031. }
  9032. }
  9033. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  9034. if (II) {
  9035. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  9036. ForRedeclaration);
  9037. LookupName(R, S);
  9038. if (R.isSingleResult()) {
  9039. NamedDecl *PrevDecl = R.getFoundDecl();
  9040. if (PrevDecl->isTemplateParameter()) {
  9041. // Maybe we will complain about the shadowed template parameter.
  9042. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  9043. // Just pretend that we didn't see the previous declaration.
  9044. PrevDecl = nullptr;
  9045. } else if (S->isDeclScope(PrevDecl)) {
  9046. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  9047. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  9048. // Recover by removing the name
  9049. II = nullptr;
  9050. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  9051. D.setInvalidType(true);
  9052. }
  9053. }
  9054. }
  9055. // HLSL Change Starts
  9056. if (getLangOpts().HLSL) {
  9057. const bool IsParm = true;
  9058. if (!DiagnoseHLSLDecl(D, Context.getTranslationUnitDecl(), 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, 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. }