SemaDeclCXX.cpp 525 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837
  1. //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ 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 C++ declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/AST/RecursiveASTVisitor.h"
  24. #include "clang/AST/StmtVisitor.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/AST/TypeOrdering.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/LiteralSupport.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Sema/CXXFieldCollector.h"
  32. #include "clang/Sema/DeclSpec.h"
  33. #include "clang/Sema/Initialization.h"
  34. #include "clang/Sema/Lookup.h"
  35. #include "clang/Sema/ParsedTemplate.h"
  36. #include "clang/Sema/Scope.h"
  37. #include "clang/Sema/ScopeInfo.h"
  38. #include "clang/Sema/Template.h"
  39. #include "llvm/ADT/STLExtras.h"
  40. #include "llvm/ADT/SmallString.h"
  41. #include <map>
  42. #include <set>
  43. #include "clang/Basic/Specifiers.h" // HLSL Change
  44. using namespace clang;
  45. //===----------------------------------------------------------------------===//
  46. // CheckDefaultArgumentVisitor
  47. //===----------------------------------------------------------------------===//
  48. namespace {
  49. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  50. /// the default argument of a parameter to determine whether it
  51. /// contains any ill-formed subexpressions. For example, this will
  52. /// diagnose the use of local variables or parameters within the
  53. /// default argument expression.
  54. class CheckDefaultArgumentVisitor
  55. : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
  56. Expr *DefaultArg;
  57. Sema *S;
  58. public:
  59. CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
  60. : DefaultArg(defarg), S(s) {}
  61. bool VisitExpr(Expr *Node);
  62. bool VisitDeclRefExpr(DeclRefExpr *DRE);
  63. bool VisitCXXThisExpr(CXXThisExpr *ThisE);
  64. bool VisitLambdaExpr(LambdaExpr *Lambda);
  65. bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
  66. };
  67. /// VisitExpr - Visit all of the children of this expression.
  68. bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
  69. bool IsInvalid = false;
  70. for (Stmt *SubStmt : Node->children())
  71. IsInvalid |= Visit(SubStmt);
  72. return IsInvalid;
  73. }
  74. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  75. /// determine whether this declaration can be used in the default
  76. /// argument expression.
  77. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
  78. NamedDecl *Decl = DRE->getDecl();
  79. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
  80. // C++ [dcl.fct.default]p9
  81. // Default arguments are evaluated each time the function is
  82. // called. The order of evaluation of function arguments is
  83. // unspecified. Consequently, parameters of a function shall not
  84. // be used in default argument expressions, even if they are not
  85. // evaluated. Parameters of a function declared before a default
  86. // argument expression are in scope and can hide namespace and
  87. // class member names.
  88. return S->Diag(DRE->getLocStart(),
  89. diag::err_param_default_argument_references_param)
  90. << Param->getDeclName() << DefaultArg->getSourceRange();
  91. } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
  92. // C++ [dcl.fct.default]p7
  93. // Local variables shall not be used in default argument
  94. // expressions.
  95. if (VDecl->isLocalVarDecl())
  96. return S->Diag(DRE->getLocStart(),
  97. diag::err_param_default_argument_references_local)
  98. << VDecl->getDeclName() << DefaultArg->getSourceRange();
  99. }
  100. return false;
  101. }
  102. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  103. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
  104. // C++ [dcl.fct.default]p8:
  105. // The keyword this shall not be used in a default argument of a
  106. // member function.
  107. return S->Diag(ThisE->getLocStart(),
  108. diag::err_param_default_argument_references_this)
  109. << ThisE->getSourceRange();
  110. }
  111. bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
  112. bool Invalid = false;
  113. for (PseudoObjectExpr::semantics_iterator
  114. i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
  115. Expr *E = *i;
  116. // Look through bindings.
  117. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  118. E = OVE->getSourceExpr();
  119. assert(E && "pseudo-object binding without source expression?");
  120. }
  121. Invalid |= Visit(E);
  122. }
  123. return Invalid;
  124. }
  125. bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
  126. // C++11 [expr.lambda.prim]p13:
  127. // A lambda-expression appearing in a default argument shall not
  128. // implicitly or explicitly capture any entity.
  129. if (Lambda->capture_begin() == Lambda->capture_end())
  130. return false;
  131. return S->Diag(Lambda->getLocStart(),
  132. diag::err_lambda_capture_default_arg);
  133. }
  134. }
  135. void
  136. Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
  137. const CXXMethodDecl *Method) {
  138. // If we have an MSAny spec already, don't bother.
  139. if (!Method || ComputedEST == EST_MSAny)
  140. return;
  141. const FunctionProtoType *Proto
  142. = Method->getType()->getAs<FunctionProtoType>();
  143. Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
  144. if (!Proto)
  145. return;
  146. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  147. // If this function can throw any exceptions, make a note of that.
  148. if (EST == EST_MSAny || EST == EST_None) {
  149. ClearExceptions();
  150. ComputedEST = EST;
  151. return;
  152. }
  153. // FIXME: If the call to this decl is using any of its default arguments, we
  154. // need to search them for potentially-throwing calls.
  155. // If this function has a basic noexcept, it doesn't affect the outcome.
  156. if (EST == EST_BasicNoexcept)
  157. return;
  158. // If we have a throw-all spec at this point, ignore the function.
  159. if (ComputedEST == EST_None)
  160. return;
  161. // If we're still at noexcept(true) and there's a nothrow() callee,
  162. // change to that specification.
  163. if (EST == EST_DynamicNone) {
  164. if (ComputedEST == EST_BasicNoexcept)
  165. ComputedEST = EST_DynamicNone;
  166. return;
  167. }
  168. // Check out noexcept specs.
  169. if (EST == EST_ComputedNoexcept) {
  170. FunctionProtoType::NoexceptResult NR =
  171. Proto->getNoexceptSpec(Self->Context);
  172. assert(NR != FunctionProtoType::NR_NoNoexcept &&
  173. "Must have noexcept result for EST_ComputedNoexcept.");
  174. assert(NR != FunctionProtoType::NR_Dependent &&
  175. "Should not generate implicit declarations for dependent cases, "
  176. "and don't know how to handle them anyway.");
  177. // noexcept(false) -> no spec on the new function
  178. if (NR == FunctionProtoType::NR_Throw) {
  179. ClearExceptions();
  180. ComputedEST = EST_None;
  181. }
  182. // noexcept(true) won't change anything either.
  183. return;
  184. }
  185. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  186. assert(ComputedEST != EST_None &&
  187. "Shouldn't collect exceptions when throw-all is guaranteed.");
  188. ComputedEST = EST_Dynamic;
  189. // Record the exceptions in this function's exception specification.
  190. for (const auto &E : Proto->exceptions())
  191. if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
  192. Exceptions.push_back(E);
  193. }
  194. void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
  195. if (!E || ComputedEST == EST_MSAny)
  196. return;
  197. // FIXME:
  198. //
  199. // C++0x [except.spec]p14:
  200. // [An] implicit exception-specification specifies the type-id T if and
  201. // only if T is allowed by the exception-specification of a function directly
  202. // invoked by f's implicit definition; f shall allow all exceptions if any
  203. // function it directly invokes allows all exceptions, and f shall allow no
  204. // exceptions if every function it directly invokes allows no exceptions.
  205. //
  206. // Note in particular that if an implicit exception-specification is generated
  207. // for a function containing a throw-expression, that specification can still
  208. // be noexcept(true).
  209. //
  210. // Note also that 'directly invoked' is not defined in the standard, and there
  211. // is no indication that we should only consider potentially-evaluated calls.
  212. //
  213. // Ultimately we should implement the intent of the standard: the exception
  214. // specification should be the set of exceptions which can be thrown by the
  215. // implicit definition. For now, we assume that any non-nothrow expression can
  216. // throw any exception.
  217. if (Self->canThrow(E))
  218. ComputedEST = EST_None;
  219. }
  220. bool
  221. Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  222. SourceLocation EqualLoc) {
  223. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  224. diag::err_typecheck_decl_incomplete_type)) {
  225. Param->setInvalidDecl();
  226. return true;
  227. }
  228. // C++ [dcl.fct.default]p5
  229. // A default argument expression is implicitly converted (clause
  230. // 4) to the parameter type. The default argument expression has
  231. // the same semantic constraints as the initializer expression in
  232. // a declaration of a variable of the parameter type, using the
  233. // copy-initialization semantics (8.5).
  234. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  235. Param);
  236. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  237. EqualLoc);
  238. InitializationSequence InitSeq(*this, Entity, Kind, Arg);
  239. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
  240. if (Result.isInvalid())
  241. return true;
  242. Arg = Result.getAs<Expr>();
  243. CheckCompletedExpr(Arg, EqualLoc);
  244. Arg = MaybeCreateExprWithCleanups(Arg);
  245. // Okay: add the default argument to the parameter
  246. Param->setDefaultArg(Arg);
  247. // We have already instantiated this parameter; provide each of the
  248. // instantiations with the uninstantiated default argument.
  249. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  250. = UnparsedDefaultArgInstantiations.find(Param);
  251. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  252. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  253. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  254. // We're done tracking this parameter's instantiations.
  255. UnparsedDefaultArgInstantiations.erase(InstPos);
  256. }
  257. return false;
  258. }
  259. /// ActOnParamDefaultArgument - Check whether the default argument
  260. /// provided for a function parameter is well-formed. If so, attach it
  261. /// to the parameter declaration.
  262. void
  263. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  264. Expr *DefaultArg) {
  265. if (!param || !DefaultArg)
  266. return;
  267. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  268. UnparsedDefaultArgLocs.erase(Param);
  269. // Default arguments are only permitted in C++
  270. if (!getLangOpts().CPlusPlus) {
  271. Diag(EqualLoc, diag::err_param_default_argument)
  272. << DefaultArg->getSourceRange();
  273. Param->setInvalidDecl();
  274. return;
  275. }
  276. // Check for unexpanded parameter packs.
  277. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  278. Param->setInvalidDecl();
  279. return;
  280. }
  281. // C++11 [dcl.fct.default]p3
  282. // A default argument expression [...] shall not be specified for a
  283. // parameter pack.
  284. if (Param->isParameterPack()) {
  285. Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
  286. << DefaultArg->getSourceRange();
  287. return;
  288. }
  289. // Check that the default argument is well-formed
  290. CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
  291. if (DefaultArgChecker.Visit(DefaultArg)) {
  292. Param->setInvalidDecl();
  293. return;
  294. }
  295. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  296. }
  297. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  298. /// argument for a function parameter, but we can't parse it yet
  299. /// because we're inside a class definition. Note that this default
  300. /// argument will be parsed later.
  301. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  302. SourceLocation EqualLoc,
  303. SourceLocation ArgLoc) {
  304. if (!param)
  305. return;
  306. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  307. Param->setUnparsedDefaultArg();
  308. UnparsedDefaultArgLocs[Param] = ArgLoc;
  309. }
  310. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  311. /// the default argument for the parameter param failed.
  312. void Sema::ActOnParamDefaultArgumentError(Decl *param,
  313. SourceLocation EqualLoc) {
  314. if (!param)
  315. return;
  316. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  317. Param->setInvalidDecl();
  318. UnparsedDefaultArgLocs.erase(Param);
  319. Param->setDefaultArg(new(Context)
  320. OpaqueValueExpr(EqualLoc,
  321. Param->getType().getNonReferenceType(),
  322. VK_RValue));
  323. }
  324. /// CheckExtraCXXDefaultArguments - Check for any extra default
  325. /// arguments in the declarator, which is not a function declaration
  326. /// or definition and therefore is not permitted to have default
  327. /// arguments. This routine should be invoked for every declarator
  328. /// that is not a function declaration or definition.
  329. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  330. // C++ [dcl.fct.default]p3
  331. // A default argument expression shall be specified only in the
  332. // parameter-declaration-clause of a function declaration or in a
  333. // template-parameter (14.1). It shall not be specified for a
  334. // parameter pack. If it is specified in a
  335. // parameter-declaration-clause, it shall not occur within a
  336. // declarator or abstract-declarator of a parameter-declaration.
  337. bool MightBeFunction = D.isFunctionDeclarationContext();
  338. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  339. DeclaratorChunk &chunk = D.getTypeObject(i);
  340. if (chunk.Kind == DeclaratorChunk::Function) {
  341. if (MightBeFunction) {
  342. // This is a function declaration. It can have default arguments, but
  343. // keep looking in case its return type is a function type with default
  344. // arguments.
  345. MightBeFunction = false;
  346. continue;
  347. }
  348. for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
  349. ++argIdx) {
  350. ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
  351. if (Param->hasUnparsedDefaultArg()) {
  352. CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
  353. SourceRange SR;
  354. if (Toks->size() > 1)
  355. SR = SourceRange((*Toks)[1].getLocation(),
  356. Toks->back().getLocation());
  357. else
  358. SR = UnparsedDefaultArgLocs[Param];
  359. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  360. << SR;
  361. delete Toks;
  362. chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
  363. } else if (Param->getDefaultArg()) {
  364. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  365. << Param->getDefaultArg()->getSourceRange();
  366. Param->setDefaultArg(nullptr);
  367. }
  368. }
  369. } else if (chunk.Kind != DeclaratorChunk::Paren) {
  370. MightBeFunction = false;
  371. }
  372. }
  373. }
  374. static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
  375. for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
  376. const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
  377. if (!PVD->hasDefaultArg())
  378. return false;
  379. if (!PVD->hasInheritedDefaultArg())
  380. return true;
  381. }
  382. return false;
  383. }
  384. /// MergeCXXFunctionDecl - Merge two declarations of the same C++
  385. /// function, once we already know that they have the same
  386. /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
  387. /// error, false otherwise.
  388. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
  389. Scope *S) {
  390. bool Invalid = false;
  391. // The declaration context corresponding to the scope is the semantic
  392. // parent, unless this is a local function declaration, in which case
  393. // it is that surrounding function.
  394. DeclContext *ScopeDC = New->isLocalExternDecl()
  395. ? New->getLexicalDeclContext()
  396. : New->getDeclContext();
  397. // Find the previous declaration for the purpose of default arguments.
  398. FunctionDecl *PrevForDefaultArgs = Old;
  399. for (/**/; PrevForDefaultArgs;
  400. // Don't bother looking back past the latest decl if this is a local
  401. // extern declaration; nothing else could work.
  402. PrevForDefaultArgs = New->isLocalExternDecl()
  403. ? nullptr
  404. : PrevForDefaultArgs->getPreviousDecl()) {
  405. // Ignore hidden declarations.
  406. if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
  407. continue;
  408. if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
  409. !New->isCXXClassMember()) {
  410. // Ignore default arguments of old decl if they are not in
  411. // the same scope and this is not an out-of-line definition of
  412. // a member function.
  413. continue;
  414. }
  415. if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
  416. // If only one of these is a local function declaration, then they are
  417. // declared in different scopes, even though isDeclInScope may think
  418. // they're in the same scope. (If both are local, the scope check is
  419. // sufficent, and if neither is local, then they are in the same scope.)
  420. continue;
  421. }
  422. // We found our guy.
  423. break;
  424. }
  425. // C++ [dcl.fct.default]p4:
  426. // For non-template functions, default arguments can be added in
  427. // later declarations of a function in the same
  428. // scope. Declarations in different scopes have completely
  429. // distinct sets of default arguments. That is, declarations in
  430. // inner scopes do not acquire default arguments from
  431. // declarations in outer scopes, and vice versa. In a given
  432. // function declaration, all parameters subsequent to a
  433. // parameter with a default argument shall have default
  434. // arguments supplied in this or previous declarations. A
  435. // default argument shall not be redefined by a later
  436. // declaration (not even to the same value).
  437. //
  438. // C++ [dcl.fct.default]p6:
  439. // Except for member functions of class templates, the default arguments
  440. // in a member function definition that appears outside of the class
  441. // definition are added to the set of default arguments provided by the
  442. // member function declaration in the class definition.
  443. for (unsigned p = 0, NumParams = PrevForDefaultArgs
  444. ? PrevForDefaultArgs->getNumParams()
  445. : 0;
  446. p < NumParams; ++p) {
  447. ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
  448. ParmVarDecl *NewParam = New->getParamDecl(p);
  449. bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
  450. bool NewParamHasDfl = NewParam->hasDefaultArg();
  451. if (OldParamHasDfl && NewParamHasDfl) {
  452. unsigned DiagDefaultParamID =
  453. diag::err_param_default_argument_redefinition;
  454. // MSVC accepts that default parameters be redefined for member functions
  455. // of template class. The new default parameter's value is ignored.
  456. Invalid = true;
  457. if (getLangOpts().MicrosoftExt) {
  458. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
  459. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  460. // Merge the old default argument into the new parameter.
  461. NewParam->setHasInheritedDefaultArg();
  462. if (OldParam->hasUninstantiatedDefaultArg())
  463. NewParam->setUninstantiatedDefaultArg(
  464. OldParam->getUninstantiatedDefaultArg());
  465. else
  466. NewParam->setDefaultArg(OldParam->getInit());
  467. DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
  468. Invalid = false;
  469. }
  470. }
  471. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  472. // hint here. Alternatively, we could walk the type-source information
  473. // for NewParam to find the last source location in the type... but it
  474. // isn't worth the effort right now. This is the kind of test case that
  475. // is hard to get right:
  476. // int f(int);
  477. // void g(int (*fp)(int) = f);
  478. // void g(int (*fp)(int) = &f);
  479. Diag(NewParam->getLocation(), DiagDefaultParamID)
  480. << NewParam->getDefaultArgRange();
  481. // Look for the function declaration where the default argument was
  482. // actually written, which may be a declaration prior to Old.
  483. for (auto Older = PrevForDefaultArgs;
  484. OldParam->hasInheritedDefaultArg(); /**/) {
  485. Older = Older->getPreviousDecl();
  486. OldParam = Older->getParamDecl(p);
  487. }
  488. Diag(OldParam->getLocation(), diag::note_previous_definition)
  489. << OldParam->getDefaultArgRange();
  490. } else if (OldParamHasDfl) {
  491. // Merge the old default argument into the new parameter.
  492. // It's important to use getInit() here; getDefaultArg()
  493. // strips off any top-level ExprWithCleanups.
  494. NewParam->setHasInheritedDefaultArg();
  495. if (OldParam->hasUnparsedDefaultArg())
  496. NewParam->setUnparsedDefaultArg();
  497. else if (OldParam->hasUninstantiatedDefaultArg())
  498. NewParam->setUninstantiatedDefaultArg(
  499. OldParam->getUninstantiatedDefaultArg());
  500. else
  501. NewParam->setDefaultArg(OldParam->getInit());
  502. } else if (NewParamHasDfl) {
  503. if (New->getDescribedFunctionTemplate()) {
  504. // Paragraph 4, quoted above, only applies to non-template functions.
  505. Diag(NewParam->getLocation(),
  506. diag::err_param_default_argument_template_redecl)
  507. << NewParam->getDefaultArgRange();
  508. Diag(PrevForDefaultArgs->getLocation(),
  509. diag::note_template_prev_declaration)
  510. << false;
  511. } else if (New->getTemplateSpecializationKind()
  512. != TSK_ImplicitInstantiation &&
  513. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  514. // C++ [temp.expr.spec]p21:
  515. // Default function arguments shall not be specified in a declaration
  516. // or a definition for one of the following explicit specializations:
  517. // - the explicit specialization of a function template;
  518. // - the explicit specialization of a member function template;
  519. // - the explicit specialization of a member function of a class
  520. // template where the class template specialization to which the
  521. // member function specialization belongs is implicitly
  522. // instantiated.
  523. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  524. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  525. << New->getDeclName()
  526. << NewParam->getDefaultArgRange();
  527. } else if (New->getDeclContext()->isDependentContext()) {
  528. // C++ [dcl.fct.default]p6 (DR217):
  529. // Default arguments for a member function of a class template shall
  530. // be specified on the initial declaration of the member function
  531. // within the class template.
  532. //
  533. // Reading the tea leaves a bit in DR217 and its reference to DR205
  534. // leads me to the conclusion that one cannot add default function
  535. // arguments for an out-of-line definition of a member function of a
  536. // dependent type.
  537. int WhichKind = 2;
  538. if (CXXRecordDecl *Record
  539. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  540. if (Record->getDescribedClassTemplate())
  541. WhichKind = 0;
  542. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  543. WhichKind = 1;
  544. else
  545. WhichKind = 2;
  546. }
  547. Diag(NewParam->getLocation(),
  548. diag::err_param_default_argument_member_template_redecl)
  549. << WhichKind
  550. << NewParam->getDefaultArgRange();
  551. }
  552. }
  553. }
  554. // DR1344: If a default argument is added outside a class definition and that
  555. // default argument makes the function a special member function, the program
  556. // is ill-formed. This can only happen for constructors.
  557. if (isa<CXXConstructorDecl>(New) &&
  558. New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
  559. CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
  560. OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
  561. if (NewSM != OldSM) {
  562. ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
  563. assert(NewParam->hasDefaultArg());
  564. Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
  565. << NewParam->getDefaultArgRange() << NewSM;
  566. Diag(Old->getLocation(), diag::note_previous_declaration);
  567. }
  568. }
  569. const FunctionDecl *Def;
  570. // C++11 [dcl.constexpr]p1: If any declaration of a function or function
  571. // template has a constexpr specifier then all its declarations shall
  572. // contain the constexpr specifier.
  573. if (New->isConstexpr() != Old->isConstexpr()) {
  574. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  575. << New << New->isConstexpr();
  576. Diag(Old->getLocation(), diag::note_previous_declaration);
  577. Invalid = true;
  578. } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
  579. Old->isDefined(Def)) {
  580. // C++11 [dcl.fcn.spec]p4:
  581. // If the definition of a function appears in a translation unit before its
  582. // first declaration as inline, the program is ill-formed.
  583. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  584. Diag(Def->getLocation(), diag::note_previous_definition);
  585. Invalid = true;
  586. }
  587. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
  588. // argument expression, that declaration shall be a definition and shall be
  589. // the only declaration of the function or function template in the
  590. // translation unit.
  591. if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
  592. functionDeclHasDefaultArgument(Old)) {
  593. Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  594. Diag(Old->getLocation(), diag::note_previous_declaration);
  595. Invalid = true;
  596. }
  597. if (CheckEquivalentExceptionSpec(Old, New))
  598. Invalid = true;
  599. return Invalid;
  600. }
  601. /// \brief Merge the exception specifications of two variable declarations.
  602. ///
  603. /// This is called when there's a redeclaration of a VarDecl. The function
  604. /// checks if the redeclaration might have an exception specification and
  605. /// validates compatibility and merges the specs if necessary.
  606. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  607. // Shortcut if exceptions are disabled.
  608. if (!getLangOpts().CXXExceptions)
  609. return;
  610. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  611. "Should only be called if types are otherwise the same.");
  612. QualType NewType = New->getType();
  613. QualType OldType = Old->getType();
  614. // We're only interested in pointers and references to functions, as well
  615. // as pointers to member functions.
  616. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  617. NewType = R->getPointeeType();
  618. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  619. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  620. NewType = P->getPointeeType();
  621. OldType = OldType->getAs<PointerType>()->getPointeeType();
  622. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  623. NewType = M->getPointeeType();
  624. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  625. }
  626. if (!NewType->isFunctionProtoType())
  627. return;
  628. // There's lots of special cases for functions. For function pointers, system
  629. // libraries are hopefully not as broken so that we don't need these
  630. // workarounds.
  631. if (CheckEquivalentExceptionSpec(
  632. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  633. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  634. New->setInvalidDecl();
  635. }
  636. }
  637. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  638. /// function declaration are well-formed according to C++
  639. /// [dcl.fct.default].
  640. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  641. unsigned NumParams = FD->getNumParams();
  642. unsigned p;
  643. // Find first parameter with a default argument
  644. for (p = 0; p < NumParams; ++p) {
  645. ParmVarDecl *Param = FD->getParamDecl(p);
  646. if (Param->hasDefaultArg())
  647. break;
  648. }
  649. // C++11 [dcl.fct.default]p4:
  650. // In a given function declaration, each parameter subsequent to a parameter
  651. // with a default argument shall have a default argument supplied in this or
  652. // a previous declaration or shall be a function parameter pack. A default
  653. // argument shall not be redefined by a later declaration (not even to the
  654. // same value).
  655. unsigned LastMissingDefaultArg = 0;
  656. for (; p < NumParams; ++p) {
  657. ParmVarDecl *Param = FD->getParamDecl(p);
  658. if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
  659. if (Param->isInvalidDecl())
  660. /* We already complained about this parameter. */;
  661. else if (Param->getIdentifier())
  662. Diag(Param->getLocation(),
  663. diag::err_param_default_argument_missing_name)
  664. << Param->getIdentifier();
  665. else
  666. Diag(Param->getLocation(),
  667. diag::err_param_default_argument_missing);
  668. LastMissingDefaultArg = p;
  669. }
  670. }
  671. if (LastMissingDefaultArg > 0) {
  672. // Some default arguments were missing. Clear out all of the
  673. // default arguments up to (and including) the last missing
  674. // default argument, so that we leave the function parameters
  675. // in a semantically valid state.
  676. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  677. ParmVarDecl *Param = FD->getParamDecl(p);
  678. if (Param->hasDefaultArg()) {
  679. Param->setDefaultArg(nullptr);
  680. }
  681. }
  682. }
  683. }
  684. // CheckConstexprParameterTypes - Check whether a function's parameter types
  685. // are all literal types. If so, return true. If not, produce a suitable
  686. // diagnostic and return false.
  687. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  688. const FunctionDecl *FD) {
  689. unsigned ArgIndex = 0;
  690. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  691. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  692. e = FT->param_type_end();
  693. i != e; ++i, ++ArgIndex) {
  694. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  695. SourceLocation ParamLoc = PD->getLocation();
  696. if (!(*i)->isDependentType() &&
  697. SemaRef.RequireLiteralType(ParamLoc, *i,
  698. diag::err_constexpr_non_literal_param,
  699. ArgIndex+1, PD->getSourceRange(),
  700. isa<CXXConstructorDecl>(FD)))
  701. return false;
  702. }
  703. return true;
  704. }
  705. /// \brief Get diagnostic %select index for tag kind for
  706. /// record diagnostic message.
  707. /// WARNING: Indexes apply to particular diagnostics only!
  708. ///
  709. /// \returns diagnostic %select index.
  710. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  711. switch (Tag) {
  712. case TTK_Struct: return 0;
  713. case TTK_Interface: return 1;
  714. case TTK_Class: return 2;
  715. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  716. }
  717. }
  718. // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
  719. // the requirements of a constexpr function definition or a constexpr
  720. // constructor definition. If so, return true. If not, produce appropriate
  721. // diagnostics and return false.
  722. //
  723. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  724. bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
  725. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  726. if (MD && MD->isInstance()) {
  727. // C++11 [dcl.constexpr]p4:
  728. // The definition of a constexpr constructor shall satisfy the following
  729. // constraints:
  730. // - the class shall not have any virtual base classes;
  731. const CXXRecordDecl *RD = MD->getParent();
  732. if (RD->getNumVBases()) {
  733. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  734. << isa<CXXConstructorDecl>(NewFD)
  735. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  736. for (const auto &I : RD->vbases())
  737. Diag(I.getLocStart(),
  738. diag::note_constexpr_virtual_base_here) << I.getSourceRange();
  739. return false;
  740. }
  741. }
  742. if (!isa<CXXConstructorDecl>(NewFD)) {
  743. // C++11 [dcl.constexpr]p3:
  744. // The definition of a constexpr function shall satisfy the following
  745. // constraints:
  746. // - it shall not be virtual;
  747. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  748. if (Method && Method->isVirtual()) {
  749. Method = Method->getCanonicalDecl();
  750. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  751. // If it's not obvious why this function is virtual, find an overridden
  752. // function which uses the 'virtual' keyword.
  753. const CXXMethodDecl *WrittenVirtual = Method;
  754. while (!WrittenVirtual->isVirtualAsWritten())
  755. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  756. if (WrittenVirtual != Method)
  757. Diag(WrittenVirtual->getLocation(),
  758. diag::note_overridden_virtual_function);
  759. return false;
  760. }
  761. // - its return type shall be a literal type;
  762. QualType RT = NewFD->getReturnType();
  763. if (!RT->isDependentType() &&
  764. RequireLiteralType(NewFD->getLocation(), RT,
  765. diag::err_constexpr_non_literal_return))
  766. return false;
  767. }
  768. // - each of its parameter types shall be a literal type;
  769. if (!CheckConstexprParameterTypes(*this, NewFD))
  770. return false;
  771. return true;
  772. }
  773. /// Check the given declaration statement is legal within a constexpr function
  774. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  775. ///
  776. /// \return true if the body is OK (maybe only as an extension), false if we
  777. /// have diagnosed a problem.
  778. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  779. DeclStmt *DS, SourceLocation &Cxx1yLoc) {
  780. // C++11 [dcl.constexpr]p3 and p4:
  781. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  782. // contain only
  783. for (const auto *DclIt : DS->decls()) {
  784. switch (DclIt->getKind()) {
  785. case Decl::StaticAssert:
  786. case Decl::Using:
  787. case Decl::UsingShadow:
  788. case Decl::UsingDirective:
  789. case Decl::UnresolvedUsingTypename:
  790. case Decl::UnresolvedUsingValue:
  791. // - static_assert-declarations
  792. // - using-declarations,
  793. // - using-directives,
  794. continue;
  795. case Decl::Typedef:
  796. case Decl::TypeAlias: {
  797. // - typedef declarations and alias-declarations that do not define
  798. // classes or enumerations,
  799. const auto *TN = cast<TypedefNameDecl>(DclIt);
  800. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  801. // Don't allow variably-modified types in constexpr functions.
  802. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  803. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  804. << TL.getSourceRange() << TL.getType()
  805. << isa<CXXConstructorDecl>(Dcl);
  806. return false;
  807. }
  808. continue;
  809. }
  810. case Decl::Enum:
  811. case Decl::CXXRecord:
  812. // C++1y allows types to be defined, not just declared.
  813. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
  814. SemaRef.Diag(DS->getLocStart(),
  815. SemaRef.getLangOpts().CPlusPlus14
  816. ? diag::warn_cxx11_compat_constexpr_type_definition
  817. : diag::ext_constexpr_type_definition)
  818. << isa<CXXConstructorDecl>(Dcl);
  819. continue;
  820. case Decl::EnumConstant:
  821. case Decl::IndirectField:
  822. case Decl::ParmVar:
  823. // These can only appear with other declarations which are banned in
  824. // C++11 and permitted in C++1y, so ignore them.
  825. continue;
  826. case Decl::Var: {
  827. // C++1y [dcl.constexpr]p3 allows anything except:
  828. // a definition of a variable of non-literal type or of static or
  829. // thread storage duration or for which no initialization is performed.
  830. const auto *VD = cast<VarDecl>(DclIt);
  831. if (VD->isThisDeclarationADefinition()) {
  832. if (VD->isStaticLocal()) {
  833. SemaRef.Diag(VD->getLocation(),
  834. diag::err_constexpr_local_var_static)
  835. << isa<CXXConstructorDecl>(Dcl)
  836. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  837. return false;
  838. }
  839. if (!VD->getType()->isDependentType() &&
  840. SemaRef.RequireLiteralType(
  841. VD->getLocation(), VD->getType(),
  842. diag::err_constexpr_local_var_non_literal_type,
  843. isa<CXXConstructorDecl>(Dcl)))
  844. return false;
  845. if (!VD->getType()->isDependentType() &&
  846. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  847. SemaRef.Diag(VD->getLocation(),
  848. diag::err_constexpr_local_var_no_init)
  849. << isa<CXXConstructorDecl>(Dcl);
  850. return false;
  851. }
  852. }
  853. SemaRef.Diag(VD->getLocation(),
  854. SemaRef.getLangOpts().CPlusPlus14
  855. ? diag::warn_cxx11_compat_constexpr_local_var
  856. : diag::ext_constexpr_local_var)
  857. << isa<CXXConstructorDecl>(Dcl);
  858. continue;
  859. }
  860. case Decl::NamespaceAlias:
  861. case Decl::Function:
  862. // These are disallowed in C++11 and permitted in C++1y. Allow them
  863. // everywhere as an extension.
  864. if (!Cxx1yLoc.isValid())
  865. Cxx1yLoc = DS->getLocStart();
  866. continue;
  867. default:
  868. SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
  869. << isa<CXXConstructorDecl>(Dcl);
  870. return false;
  871. }
  872. }
  873. return true;
  874. }
  875. /// Check that the given field is initialized within a constexpr constructor.
  876. ///
  877. /// \param Dcl The constexpr constructor being checked.
  878. /// \param Field The field being checked. This may be a member of an anonymous
  879. /// struct or union nested within the class being checked.
  880. /// \param Inits All declarations, including anonymous struct/union members and
  881. /// indirect members, for which any initialization was provided.
  882. /// \param Diagnosed Set to true if an error is produced.
  883. static void CheckConstexprCtorInitializer(Sema &SemaRef,
  884. const FunctionDecl *Dcl,
  885. FieldDecl *Field,
  886. llvm::SmallSet<Decl*, 16> &Inits,
  887. bool &Diagnosed) {
  888. if (Field->isInvalidDecl())
  889. return;
  890. if (Field->isUnnamedBitfield())
  891. return;
  892. // Anonymous unions with no variant members and empty anonymous structs do not
  893. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  894. // indirect fields don't need initializing.
  895. if (Field->isAnonymousStructOrUnion() &&
  896. (Field->getType()->isUnionType()
  897. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  898. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  899. return;
  900. if (!Inits.count(Field)) {
  901. if (!Diagnosed) {
  902. SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
  903. Diagnosed = true;
  904. }
  905. SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
  906. } else if (Field->isAnonymousStructOrUnion()) {
  907. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  908. for (auto *I : RD->fields())
  909. // If an anonymous union contains an anonymous struct of which any member
  910. // is initialized, all members must be initialized.
  911. if (!RD->isUnion() || Inits.count(I))
  912. CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
  913. }
  914. }
  915. /// Check the provided statement is allowed in a constexpr function
  916. /// definition.
  917. static bool
  918. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  919. SmallVectorImpl<SourceLocation> &ReturnStmts,
  920. SourceLocation &Cxx1yLoc) {
  921. // - its function-body shall be [...] a compound-statement that contains only
  922. switch (S->getStmtClass()) {
  923. case Stmt::NullStmtClass:
  924. // - null statements,
  925. return true;
  926. case Stmt::DeclStmtClass:
  927. // - static_assert-declarations
  928. // - using-declarations,
  929. // - using-directives,
  930. // - typedef declarations and alias-declarations that do not define
  931. // classes or enumerations,
  932. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
  933. return false;
  934. return true;
  935. case Stmt::ReturnStmtClass:
  936. // - and exactly one return statement;
  937. if (isa<CXXConstructorDecl>(Dcl)) {
  938. // C++1y allows return statements in constexpr constructors.
  939. if (!Cxx1yLoc.isValid())
  940. Cxx1yLoc = S->getLocStart();
  941. return true;
  942. }
  943. ReturnStmts.push_back(S->getLocStart());
  944. return true;
  945. case Stmt::CompoundStmtClass: {
  946. // C++1y allows compound-statements.
  947. if (!Cxx1yLoc.isValid())
  948. Cxx1yLoc = S->getLocStart();
  949. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  950. for (auto *BodyIt : CompStmt->body()) {
  951. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  952. Cxx1yLoc))
  953. return false;
  954. }
  955. return true;
  956. }
  957. case Stmt::AttributedStmtClass:
  958. if (!Cxx1yLoc.isValid())
  959. Cxx1yLoc = S->getLocStart();
  960. return true;
  961. case Stmt::IfStmtClass: {
  962. // C++1y allows if-statements.
  963. if (!Cxx1yLoc.isValid())
  964. Cxx1yLoc = S->getLocStart();
  965. IfStmt *If = cast<IfStmt>(S);
  966. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  967. Cxx1yLoc))
  968. return false;
  969. if (If->getElse() &&
  970. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  971. Cxx1yLoc))
  972. return false;
  973. return true;
  974. }
  975. case Stmt::WhileStmtClass:
  976. case Stmt::DoStmtClass:
  977. case Stmt::ForStmtClass:
  978. case Stmt::CXXForRangeStmtClass:
  979. case Stmt::ContinueStmtClass:
  980. // C++1y allows all of these. We don't allow them as extensions in C++11,
  981. // because they don't make sense without variable mutation.
  982. if (!SemaRef.getLangOpts().CPlusPlus14)
  983. break;
  984. if (!Cxx1yLoc.isValid())
  985. Cxx1yLoc = S->getLocStart();
  986. for (Stmt *SubStmt : S->children())
  987. if (SubStmt &&
  988. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  989. Cxx1yLoc))
  990. return false;
  991. return true;
  992. case Stmt::SwitchStmtClass:
  993. case Stmt::CaseStmtClass:
  994. case Stmt::DefaultStmtClass:
  995. case Stmt::BreakStmtClass:
  996. // C++1y allows switch-statements, and since they don't need variable
  997. // mutation, we can reasonably allow them in C++11 as an extension.
  998. if (!Cxx1yLoc.isValid())
  999. Cxx1yLoc = S->getLocStart();
  1000. for (Stmt *SubStmt : S->children())
  1001. if (SubStmt &&
  1002. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1003. Cxx1yLoc))
  1004. return false;
  1005. return true;
  1006. default:
  1007. if (!isa<Expr>(S))
  1008. break;
  1009. // C++1y allows expression-statements.
  1010. if (!Cxx1yLoc.isValid())
  1011. Cxx1yLoc = S->getLocStart();
  1012. return true;
  1013. }
  1014. SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
  1015. << isa<CXXConstructorDecl>(Dcl);
  1016. return false;
  1017. }
  1018. /// Check the body for the given constexpr function declaration only contains
  1019. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1020. ///
  1021. /// \return true if the body is OK, false if we have diagnosed a problem.
  1022. bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
  1023. if (isa<CXXTryStmt>(Body)) {
  1024. // C++11 [dcl.constexpr]p3:
  1025. // The definition of a constexpr function shall satisfy the following
  1026. // constraints: [...]
  1027. // - its function-body shall be = delete, = default, or a
  1028. // compound-statement
  1029. //
  1030. // C++11 [dcl.constexpr]p4:
  1031. // In the definition of a constexpr constructor, [...]
  1032. // - its function-body shall not be a function-try-block;
  1033. Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
  1034. << isa<CXXConstructorDecl>(Dcl);
  1035. return false;
  1036. }
  1037. SmallVector<SourceLocation, 4> ReturnStmts;
  1038. // - its function-body shall be [...] a compound-statement that contains only
  1039. // [... list of cases ...]
  1040. CompoundStmt *CompBody = cast<CompoundStmt>(Body);
  1041. SourceLocation Cxx1yLoc;
  1042. for (auto *BodyIt : CompBody->body()) {
  1043. if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
  1044. return false;
  1045. }
  1046. if (Cxx1yLoc.isValid())
  1047. Diag(Cxx1yLoc,
  1048. getLangOpts().CPlusPlus14
  1049. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1050. : diag::ext_constexpr_body_invalid_stmt)
  1051. << isa<CXXConstructorDecl>(Dcl);
  1052. if (const CXXConstructorDecl *Constructor
  1053. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1054. const CXXRecordDecl *RD = Constructor->getParent();
  1055. // DR1359:
  1056. // - every non-variant non-static data member and base class sub-object
  1057. // shall be initialized;
  1058. // DR1460:
  1059. // - if the class is a union having variant members, exactly one of them
  1060. // shall be initialized;
  1061. if (RD->isUnion()) {
  1062. if (Constructor->getNumCtorInitializers() == 0 &&
  1063. RD->hasVariantMembers()) {
  1064. Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
  1065. return false;
  1066. }
  1067. } else if (!Constructor->isDependentContext() &&
  1068. !Constructor->isDelegatingConstructor()) {
  1069. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1070. // Skip detailed checking if we have enough initializers, and we would
  1071. // allow at most one initializer per member.
  1072. bool AnyAnonStructUnionMembers = false;
  1073. unsigned Fields = 0;
  1074. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1075. E = RD->field_end(); I != E; ++I, ++Fields) {
  1076. if (I->isAnonymousStructOrUnion()) {
  1077. AnyAnonStructUnionMembers = true;
  1078. break;
  1079. }
  1080. }
  1081. // DR1460:
  1082. // - if the class is a union-like class, but is not a union, for each of
  1083. // its anonymous union members having variant members, exactly one of
  1084. // them shall be initialized;
  1085. if (AnyAnonStructUnionMembers ||
  1086. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1087. // Check initialization of non-static data members. Base classes are
  1088. // always initialized so do not need to be checked. Dependent bases
  1089. // might not have initializers in the member initializer list.
  1090. llvm::SmallSet<Decl*, 16> Inits;
  1091. for (const auto *I: Constructor->inits()) {
  1092. if (FieldDecl *FD = I->getMember())
  1093. Inits.insert(FD);
  1094. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1095. Inits.insert(ID->chain_begin(), ID->chain_end());
  1096. }
  1097. bool Diagnosed = false;
  1098. for (auto *I : RD->fields())
  1099. CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
  1100. if (Diagnosed)
  1101. return false;
  1102. }
  1103. }
  1104. } else {
  1105. if (ReturnStmts.empty()) {
  1106. // C++1y doesn't require constexpr functions to contain a 'return'
  1107. // statement. We still do, unless the return type might be void, because
  1108. // otherwise if there's no return statement, the function cannot
  1109. // be used in a core constant expression.
  1110. bool OK = getLangOpts().CPlusPlus14 &&
  1111. (Dcl->getReturnType()->isVoidType() ||
  1112. Dcl->getReturnType()->isDependentType());
  1113. Diag(Dcl->getLocation(),
  1114. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  1115. : diag::err_constexpr_body_no_return);
  1116. return OK;
  1117. }
  1118. if (ReturnStmts.size() > 1) {
  1119. Diag(ReturnStmts.back(),
  1120. getLangOpts().CPlusPlus14
  1121. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  1122. : diag::ext_constexpr_body_multiple_return);
  1123. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  1124. Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
  1125. }
  1126. }
  1127. // C++11 [dcl.constexpr]p5:
  1128. // if no function argument values exist such that the function invocation
  1129. // substitution would produce a constant expression, the program is
  1130. // ill-formed; no diagnostic required.
  1131. // C++11 [dcl.constexpr]p3:
  1132. // - every constructor call and implicit conversion used in initializing the
  1133. // return value shall be one of those allowed in a constant expression.
  1134. // C++11 [dcl.constexpr]p4:
  1135. // - every constructor involved in initializing non-static data members and
  1136. // base class sub-objects shall be a constexpr constructor.
  1137. SmallVector<PartialDiagnosticAt, 8> Diags;
  1138. if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
  1139. Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
  1140. << isa<CXXConstructorDecl>(Dcl);
  1141. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  1142. Diag(Diags[I].first, Diags[I].second);
  1143. // Don't return false here: we allow this for compatibility in
  1144. // system headers.
  1145. }
  1146. return true;
  1147. }
  1148. /// isCurrentClassName - Determine whether the identifier II is the
  1149. /// name of the class type currently being defined. In the case of
  1150. /// nested classes, this will only return true if II is the name of
  1151. /// the innermost class.
  1152. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
  1153. const CXXScopeSpec *SS) {
  1154. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1155. CXXRecordDecl *CurDecl;
  1156. if (SS && SS->isSet() && !SS->isInvalid()) {
  1157. DeclContext *DC = computeDeclContext(*SS, true);
  1158. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1159. } else
  1160. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1161. if (CurDecl && CurDecl->getIdentifier())
  1162. return &II == CurDecl->getIdentifier();
  1163. return false;
  1164. }
  1165. /// \brief Determine whether the identifier II is a typo for the name of
  1166. /// the class type currently being defined. If so, update it to the identifier
  1167. /// that should have been used.
  1168. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  1169. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1170. if (!getLangOpts().SpellChecking)
  1171. return false;
  1172. CXXRecordDecl *CurDecl;
  1173. if (SS && SS->isSet() && !SS->isInvalid()) {
  1174. DeclContext *DC = computeDeclContext(*SS, true);
  1175. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1176. } else
  1177. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1178. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  1179. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  1180. < II->getLength()) {
  1181. II = CurDecl->getIdentifier();
  1182. return true;
  1183. }
  1184. return false;
  1185. }
  1186. /// \brief Determine whether the given class is a base class of the given
  1187. /// class, including looking at dependent bases.
  1188. static bool findCircularInheritance(const CXXRecordDecl *Class,
  1189. const CXXRecordDecl *Current) {
  1190. SmallVector<const CXXRecordDecl*, 8> Queue;
  1191. Class = Class->getCanonicalDecl();
  1192. while (true) {
  1193. for (const auto &I : Current->bases()) {
  1194. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  1195. if (!Base)
  1196. continue;
  1197. Base = Base->getDefinition();
  1198. if (!Base)
  1199. continue;
  1200. if (Base->getCanonicalDecl() == Class)
  1201. return true;
  1202. Queue.push_back(Base);
  1203. }
  1204. if (Queue.empty())
  1205. return false;
  1206. Current = Queue.pop_back_val();
  1207. }
  1208. return false;
  1209. }
  1210. /// \brief Check the validity of a C++ base class specifier.
  1211. ///
  1212. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  1213. /// and returns NULL otherwise.
  1214. CXXBaseSpecifier *
  1215. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  1216. SourceRange SpecifierRange,
  1217. bool Virtual, AccessSpecifier Access,
  1218. TypeSourceInfo *TInfo,
  1219. SourceLocation EllipsisLoc) {
  1220. QualType BaseType = TInfo->getType();
  1221. // C++ [class.union]p1:
  1222. // A union shall not have base classes.
  1223. if (Class->isUnion()) {
  1224. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  1225. << SpecifierRange;
  1226. return nullptr;
  1227. }
  1228. if (EllipsisLoc.isValid() &&
  1229. !TInfo->getType()->containsUnexpandedParameterPack()) {
  1230. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1231. << TInfo->getTypeLoc().getSourceRange();
  1232. EllipsisLoc = SourceLocation();
  1233. }
  1234. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  1235. if (BaseType->isDependentType()) {
  1236. // Make sure that we don't have circular inheritance among our dependent
  1237. // bases. For non-dependent bases, the check for completeness below handles
  1238. // this.
  1239. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  1240. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  1241. ((BaseDecl = BaseDecl->getDefinition()) &&
  1242. findCircularInheritance(Class, BaseDecl))) {
  1243. Diag(BaseLoc, diag::err_circular_inheritance)
  1244. << BaseType << Context.getTypeDeclType(Class);
  1245. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  1246. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  1247. << BaseType;
  1248. return nullptr;
  1249. }
  1250. }
  1251. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  1252. Class->getTagKind() == TTK_Class,
  1253. Access, TInfo, EllipsisLoc);
  1254. }
  1255. // Base specifiers must be record types.
  1256. if (!BaseType->isRecordType()) {
  1257. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  1258. return nullptr;
  1259. }
  1260. // C++ [class.union]p1:
  1261. // A union shall not be used as a base class.
  1262. if (BaseType->isUnionType()) {
  1263. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  1264. return nullptr;
  1265. }
  1266. // For the MS ABI, propagate DLL attributes to base class templates.
  1267. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1268. if (Attr *ClassAttr = getDLLAttr(Class)) {
  1269. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  1270. BaseType->getAsCXXRecordDecl())) {
  1271. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  1272. BaseLoc);
  1273. }
  1274. }
  1275. }
  1276. // C++ [class.derived]p2:
  1277. // The class-name in a base-specifier shall not be an incompletely
  1278. // defined class.
  1279. if (RequireCompleteType(BaseLoc, BaseType,
  1280. diag::err_incomplete_base_class, SpecifierRange)) {
  1281. Class->setInvalidDecl();
  1282. return nullptr;
  1283. }
  1284. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  1285. RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
  1286. assert(BaseDecl && "Record type has no declaration");
  1287. BaseDecl = BaseDecl->getDefinition();
  1288. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  1289. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  1290. assert(CXXBaseDecl && "Base type is not a C++ type");
  1291. // A class which contains a flexible array member is not suitable for use as a
  1292. // base class:
  1293. // - If the layout determines that a base comes before another base,
  1294. // the flexible array member would index into the subsequent base.
  1295. // - If the layout determines that base comes before the derived class,
  1296. // the flexible array member would index into the derived class.
  1297. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  1298. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  1299. << CXXBaseDecl->getDeclName();
  1300. return nullptr;
  1301. }
  1302. // C++ [class]p3:
  1303. // If a class is marked final and it appears as a base-type-specifier in
  1304. // base-clause, the program is ill-formed.
  1305. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  1306. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  1307. << CXXBaseDecl->getDeclName()
  1308. << FA->isSpelledAsSealed();
  1309. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  1310. << CXXBaseDecl->getDeclName() << FA->getRange();
  1311. return nullptr;
  1312. }
  1313. if (BaseDecl->isInvalidDecl())
  1314. Class->setInvalidDecl();
  1315. // Create the base specifier.
  1316. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  1317. Class->getTagKind() == TTK_Class,
  1318. Access, TInfo, EllipsisLoc);
  1319. }
  1320. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  1321. /// one entry in the base class list of a class specifier, for
  1322. /// example:
  1323. /// class foo : public bar, virtual private baz {
  1324. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  1325. BaseResult
  1326. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  1327. ParsedAttributes &Attributes,
  1328. bool Virtual, AccessSpecifier Access,
  1329. ParsedType basetype, SourceLocation BaseLoc,
  1330. SourceLocation EllipsisLoc) {
  1331. if (!classdecl)
  1332. return true;
  1333. AdjustDeclIfTemplate(classdecl);
  1334. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  1335. if (!Class)
  1336. return true;
  1337. // We haven't yet attached the base specifiers.
  1338. Class->setIsParsingBaseSpecifiers();
  1339. // We do not support any C++11 attributes on base-specifiers yet.
  1340. // Diagnose any attributes we see.
  1341. if (!Attributes.empty()) {
  1342. for (AttributeList *Attr = Attributes.getList(); Attr;
  1343. Attr = Attr->getNext()) {
  1344. if (Attr->isInvalid() ||
  1345. Attr->getKind() == AttributeList::IgnoredAttribute)
  1346. continue;
  1347. Diag(Attr->getLoc(),
  1348. Attr->getKind() == AttributeList::UnknownAttribute
  1349. ? diag::warn_unknown_attribute_ignored
  1350. : diag::err_base_specifier_attribute)
  1351. << Attr->getName();
  1352. }
  1353. }
  1354. TypeSourceInfo *TInfo = nullptr;
  1355. GetTypeFromParser(basetype, &TInfo);
  1356. if (EllipsisLoc.isInvalid() &&
  1357. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  1358. UPPC_BaseType))
  1359. return true;
  1360. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  1361. Virtual, Access, TInfo,
  1362. EllipsisLoc))
  1363. return BaseSpec;
  1364. else
  1365. Class->setInvalidDecl();
  1366. return true;
  1367. }
  1368. /// Use small set to collect indirect bases. As this is only used
  1369. /// locally, there's no need to abstract the small size parameter.
  1370. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  1371. /// \brief Recursively add the bases of Type. Don't add Type itself.
  1372. static void
  1373. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  1374. const QualType &Type)
  1375. {
  1376. // Even though the incoming type is a base, it might not be
  1377. // a class -- it could be a template parm, for instance.
  1378. if (auto Rec = Type->getAs<RecordType>()) {
  1379. auto Decl = Rec->getAsCXXRecordDecl();
  1380. // Iterate over its bases.
  1381. for (const auto &BaseSpec : Decl->bases()) {
  1382. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  1383. .getUnqualifiedType();
  1384. if (Set.insert(Base).second)
  1385. // If we've not already seen it, recurse.
  1386. NoteIndirectBases(Context, Set, Base);
  1387. }
  1388. }
  1389. }
  1390. // HLSL Change Starts
  1391. static bool isConcreteBaseType(const QualType& t)
  1392. {
  1393. // Other than interfaces, all base types are concrete.
  1394. const Type* type = t.getTypePtr();
  1395. if (!type->isRecordType()) return true; // Likely should have been rejected before.
  1396. return !(type->getAsCXXRecordDecl()->getTagKind() == TagTypeKind::TTK_Interface);
  1397. }
  1398. // HLSL Change Ends
  1399. /// \brief Performs the actual work of attaching the given base class
  1400. /// specifiers to a C++ class.
  1401. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
  1402. unsigned NumBases) {
  1403. if (NumBases == 0)
  1404. return false;
  1405. // HLSL Change Starts
  1406. if (Class->getTagKind() == TagTypeKind::TTK_Interface) {
  1407. Diag(Bases[0]->getLocStart(), diag::err_hlsl_interfaces_cannot_inherit);
  1408. return true;
  1409. }
  1410. // HLSL Change Ends
  1411. // Used to keep track of which base types we have already seen, so
  1412. // that we can properly diagnose redundant direct base types. Note
  1413. // that the key is always the unqualified canonical type of the base
  1414. // class.
  1415. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  1416. // Used to track indirect bases so we can see if a direct base is
  1417. // ambiguous.
  1418. IndirectBaseSet IndirectBaseTypes;
  1419. // Copy non-redundant base specifiers into permanent storage.
  1420. bool ConcreteBaseTypeFound = false; // HLSL Change
  1421. bool ConcreteBaseTypeReported = false; // HLSL Change
  1422. unsigned NumGoodBases = 0;
  1423. bool Invalid = false;
  1424. for (unsigned idx = 0; idx < NumBases; ++idx) {
  1425. QualType NewBaseType
  1426. = Context.getCanonicalType(Bases[idx]->getType());
  1427. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  1428. // HLSL Change Starts
  1429. if (!ConcreteBaseTypeReported) {
  1430. if (isConcreteBaseType(NewBaseType)) {
  1431. if (ConcreteBaseTypeFound) {
  1432. Diag(Bases[idx]->getLocStart(), diag::err_hlsl_multiple_concrete_bases);
  1433. Invalid = true;
  1434. ConcreteBaseTypeReported = true;
  1435. } else {
  1436. ConcreteBaseTypeFound = true;
  1437. }
  1438. }
  1439. }
  1440. // HLSL Change Ends
  1441. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  1442. if (KnownBase) {
  1443. // C++ [class.mi]p3:
  1444. // A class shall not be specified as a direct base class of a
  1445. // derived class more than once.
  1446. Diag(Bases[idx]->getLocStart(),
  1447. diag::err_duplicate_base_class)
  1448. << KnownBase->getType()
  1449. << Bases[idx]->getSourceRange();
  1450. // Delete the duplicate base class specifier; we're going to
  1451. // overwrite its pointer later.
  1452. Context.Deallocate(Bases[idx]);
  1453. Invalid = true;
  1454. } else {
  1455. // Okay, add this new base class.
  1456. KnownBase = Bases[idx];
  1457. Bases[NumGoodBases++] = Bases[idx];
  1458. // Note this base's direct & indirect bases, if there could be ambiguity.
  1459. if (NumBases > 1)
  1460. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  1461. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  1462. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  1463. if (Class->isInterface() &&
  1464. (!RD->isInterface() ||
  1465. KnownBase->getAccessSpecifier() != AS_public)) {
  1466. // The Microsoft extension __interface does not permit bases that
  1467. // are not themselves public interfaces.
  1468. Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
  1469. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
  1470. << RD->getSourceRange();
  1471. Invalid = true;
  1472. }
  1473. if (RD->hasAttr<WeakAttr>())
  1474. Class->addAttr(WeakAttr::CreateImplicit(Context));
  1475. }
  1476. }
  1477. }
  1478. // Attach the remaining base class specifiers to the derived class.
  1479. Class->setBases(Bases, NumGoodBases);
  1480. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  1481. // Check whether this direct base is inaccessible due to ambiguity.
  1482. QualType BaseType = Bases[idx]->getType();
  1483. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  1484. .getUnqualifiedType();
  1485. if (IndirectBaseTypes.count(CanonicalBase)) {
  1486. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1487. /*DetectVirtual=*/true);
  1488. bool found
  1489. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  1490. assert(found);
  1491. (void)found;
  1492. if (Paths.isAmbiguous(CanonicalBase))
  1493. Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
  1494. << BaseType << getAmbiguousPathsDisplayString(Paths)
  1495. << Bases[idx]->getSourceRange();
  1496. else
  1497. assert(Bases[idx]->isVirtual());
  1498. }
  1499. // Delete the base class specifier, since its data has been copied
  1500. // into the CXXRecordDecl.
  1501. Context.Deallocate(Bases[idx]);
  1502. }
  1503. return Invalid;
  1504. }
  1505. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  1506. /// class, after checking whether there are any duplicate base
  1507. /// classes.
  1508. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
  1509. unsigned NumBases) {
  1510. if (!ClassDecl || !Bases || !NumBases)
  1511. return;
  1512. AdjustDeclIfTemplate(ClassDecl);
  1513. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
  1514. }
  1515. /// \brief Determine whether the type \p Derived is a C++ class that is
  1516. /// derived from the type \p Base.
  1517. bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
  1518. if (!getLangOpts().CPlusPlus)
  1519. return false;
  1520. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  1521. if (!DerivedRD)
  1522. return false;
  1523. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  1524. if (!BaseRD)
  1525. return false;
  1526. // If either the base or the derived type is invalid, don't try to
  1527. // check whether one is derived from the other.
  1528. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  1529. return false;
  1530. // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
  1531. return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
  1532. }
  1533. /// \brief Determine whether the type \p Derived is a C++ class that is
  1534. /// derived from the type \p Base.
  1535. bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
  1536. if (!getLangOpts().CPlusPlus)
  1537. return false;
  1538. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  1539. if (!DerivedRD)
  1540. return false;
  1541. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  1542. if (!BaseRD)
  1543. return false;
  1544. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  1545. }
  1546. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  1547. CXXCastPath &BasePathArray) {
  1548. assert(BasePathArray.empty() && "Base path array must be empty!");
  1549. assert(Paths.isRecordingPaths() && "Must record paths!");
  1550. const CXXBasePath &Path = Paths.front();
  1551. // We first go backward and check if we have a virtual base.
  1552. // FIXME: It would be better if CXXBasePath had the base specifier for
  1553. // the nearest virtual base.
  1554. unsigned Start = 0;
  1555. for (unsigned I = Path.size(); I != 0; --I) {
  1556. if (Path[I - 1].Base->isVirtual()) {
  1557. Start = I - 1;
  1558. break;
  1559. }
  1560. }
  1561. // Now add all bases.
  1562. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  1563. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  1564. }
  1565. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  1566. /// conversion (where Derived and Base are class types) is
  1567. /// well-formed, meaning that the conversion is unambiguous (and
  1568. /// that all of the base classes are accessible). Returns true
  1569. /// and emits a diagnostic if the code is ill-formed, returns false
  1570. /// otherwise. Loc is the location where this routine should point to
  1571. /// if there is an error, and Range is the source range to highlight
  1572. /// if there is an error.
  1573. bool
  1574. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  1575. unsigned InaccessibleBaseID,
  1576. unsigned AmbigiousBaseConvID,
  1577. SourceLocation Loc, SourceRange Range,
  1578. DeclarationName Name,
  1579. CXXCastPath *BasePath) {
  1580. // First, determine whether the path from Derived to Base is
  1581. // ambiguous. This is slightly more expensive than checking whether
  1582. // the Derived to Base conversion exists, because here we need to
  1583. // explore multiple paths to determine if there is an ambiguity.
  1584. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1585. /*DetectVirtual=*/false);
  1586. bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
  1587. assert(DerivationOkay &&
  1588. "Can only be used with a derived-to-base conversion");
  1589. (void)DerivationOkay;
  1590. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
  1591. if (InaccessibleBaseID) {
  1592. // Check that the base class can be accessed.
  1593. switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
  1594. InaccessibleBaseID)) {
  1595. case AR_inaccessible:
  1596. return true;
  1597. case AR_accessible:
  1598. case AR_dependent:
  1599. case AR_delayed:
  1600. break;
  1601. }
  1602. }
  1603. // Build a base path if necessary.
  1604. if (BasePath)
  1605. BuildBasePathArray(Paths, *BasePath);
  1606. return false;
  1607. }
  1608. if (AmbigiousBaseConvID) {
  1609. // We know that the derived-to-base conversion is ambiguous, and
  1610. // we're going to produce a diagnostic. Perform the derived-to-base
  1611. // search just one more time to compute all of the possible paths so
  1612. // that we can print them out. This is more expensive than any of
  1613. // the previous derived-to-base checks we've done, but at this point
  1614. // performance isn't as much of an issue.
  1615. Paths.clear();
  1616. Paths.setRecordingPaths(true);
  1617. bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
  1618. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  1619. (void)StillOkay;
  1620. // Build up a textual representation of the ambiguous paths, e.g.,
  1621. // D -> B -> A, that will be used to illustrate the ambiguous
  1622. // conversions in the diagnostic. We only print one of the paths
  1623. // to each base class subobject.
  1624. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  1625. Diag(Loc, AmbigiousBaseConvID)
  1626. << Derived << Base << PathDisplayStr << Range << Name;
  1627. }
  1628. return true;
  1629. }
  1630. bool
  1631. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  1632. SourceLocation Loc, SourceRange Range,
  1633. CXXCastPath *BasePath,
  1634. bool IgnoreAccess) {
  1635. return CheckDerivedToBaseConversion(Derived, Base,
  1636. IgnoreAccess ? 0
  1637. : diag::err_upcast_to_inaccessible_base,
  1638. diag::err_ambiguous_derived_to_base_conv,
  1639. Loc, Range, DeclarationName(),
  1640. BasePath);
  1641. }
  1642. /// @brief Builds a string representing ambiguous paths from a
  1643. /// specific derived class to different subobjects of the same base
  1644. /// class.
  1645. ///
  1646. /// This function builds a string that can be used in error messages
  1647. /// to show the different paths that one can take through the
  1648. /// inheritance hierarchy to go from the derived class to different
  1649. /// subobjects of a base class. The result looks something like this:
  1650. /// @code
  1651. /// struct D -> struct B -> struct A
  1652. /// struct D -> struct C -> struct A
  1653. /// @endcode
  1654. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  1655. std::string PathDisplayStr;
  1656. std::set<unsigned> DisplayedPaths;
  1657. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  1658. Path != Paths.end(); ++Path) {
  1659. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  1660. // We haven't displayed a path to this particular base
  1661. // class subobject yet.
  1662. PathDisplayStr += "\n ";
  1663. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  1664. for (CXXBasePath::const_iterator Element = Path->begin();
  1665. Element != Path->end(); ++Element)
  1666. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  1667. }
  1668. }
  1669. return PathDisplayStr;
  1670. }
  1671. //===----------------------------------------------------------------------===//
  1672. // C++ class member Handling
  1673. //===----------------------------------------------------------------------===//
  1674. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  1675. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
  1676. SourceLocation ASLoc,
  1677. SourceLocation ColonLoc,
  1678. AttributeList *Attrs) {
  1679. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  1680. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  1681. ASLoc, ColonLoc);
  1682. CurContext->addHiddenDecl(ASDecl);
  1683. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  1684. }
  1685. /// CheckOverrideControl - Check C++11 override control semantics.
  1686. void Sema::CheckOverrideControl(NamedDecl *D) {
  1687. if (D->isInvalidDecl())
  1688. return;
  1689. // We only care about "override" and "final" declarations.
  1690. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  1691. return;
  1692. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  1693. // We can't check dependent instance methods.
  1694. if (MD && MD->isInstance() &&
  1695. (MD->getParent()->hasAnyDependentBases() ||
  1696. MD->getType()->isDependentType()))
  1697. return;
  1698. if (MD && !MD->isVirtual()) {
  1699. // If we have a non-virtual method, check if if hides a virtual method.
  1700. // (In that case, it's most likely the method has the wrong type.)
  1701. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  1702. FindHiddenVirtualMethods(MD, OverloadedMethods);
  1703. if (!OverloadedMethods.empty()) {
  1704. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  1705. Diag(OA->getLocation(),
  1706. diag::override_keyword_hides_virtual_member_function)
  1707. << "override" << (OverloadedMethods.size() > 1);
  1708. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  1709. Diag(FA->getLocation(),
  1710. diag::override_keyword_hides_virtual_member_function)
  1711. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  1712. << (OverloadedMethods.size() > 1);
  1713. }
  1714. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  1715. MD->setInvalidDecl();
  1716. return;
  1717. }
  1718. // Fall through into the general case diagnostic.
  1719. // FIXME: We might want to attempt typo correction here.
  1720. }
  1721. if (!MD || !MD->isVirtual()) {
  1722. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  1723. Diag(OA->getLocation(),
  1724. diag::override_keyword_only_allowed_on_virtual_member_functions)
  1725. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  1726. D->dropAttr<OverrideAttr>();
  1727. }
  1728. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  1729. Diag(FA->getLocation(),
  1730. diag::override_keyword_only_allowed_on_virtual_member_functions)
  1731. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  1732. << FixItHint::CreateRemoval(FA->getLocation());
  1733. D->dropAttr<FinalAttr>();
  1734. }
  1735. return;
  1736. }
  1737. // C++11 [class.virtual]p5:
  1738. // If a function is marked with the virt-specifier override and
  1739. // does not override a member function of a base class, the program is
  1740. // ill-formed.
  1741. bool HasOverriddenMethods =
  1742. MD->begin_overridden_methods() != MD->end_overridden_methods();
  1743. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  1744. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  1745. << MD->getDeclName();
  1746. }
  1747. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  1748. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  1749. return;
  1750. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  1751. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
  1752. isa<CXXDestructorDecl>(MD))
  1753. return;
  1754. SourceLocation Loc = MD->getLocation();
  1755. SourceLocation SpellingLoc = Loc;
  1756. if (getSourceManager().isMacroArgExpansion(Loc))
  1757. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
  1758. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  1759. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  1760. return;
  1761. if (MD->size_overridden_methods() > 0) {
  1762. Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
  1763. << MD->getDeclName();
  1764. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  1765. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  1766. }
  1767. }
  1768. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  1769. /// function overrides a virtual member function marked 'final', according to
  1770. /// C++11 [class.virtual]p4.
  1771. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  1772. const CXXMethodDecl *Old) {
  1773. FinalAttr *FA = Old->getAttr<FinalAttr>();
  1774. if (!FA)
  1775. return false;
  1776. Diag(New->getLocation(), diag::err_final_function_overridden)
  1777. << New->getDeclName()
  1778. << FA->isSpelledAsSealed();
  1779. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  1780. return true;
  1781. }
  1782. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  1783. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  1784. // FIXME: Destruction of ObjC lifetime types has side-effects.
  1785. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  1786. return !RD->isCompleteDefinition() ||
  1787. !RD->hasTrivialDefaultConstructor() ||
  1788. !RD->hasTrivialDestructor();
  1789. return false;
  1790. }
  1791. static AttributeList *getMSPropertyAttr(AttributeList *list) {
  1792. for (AttributeList *it = list; it != nullptr; it = it->getNext())
  1793. if (it->isDeclspecPropertyAttribute())
  1794. return it;
  1795. return nullptr;
  1796. }
  1797. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  1798. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  1799. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  1800. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  1801. /// present (but parsing it has been deferred).
  1802. NamedDecl *
  1803. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  1804. MultiTemplateParamsArg TemplateParameterLists,
  1805. Expr *BW, const VirtSpecifiers &VS,
  1806. InClassInitStyle InitStyle) {
  1807. const DeclSpec &DS = D.getDeclSpec();
  1808. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  1809. DeclarationName Name = NameInfo.getName();
  1810. SourceLocation Loc = NameInfo.getLoc();
  1811. // For anonymous bitfields, the location should point to the type.
  1812. if (Loc.isInvalid())
  1813. Loc = D.getLocStart();
  1814. Expr *BitWidth = static_cast<Expr*>(BW);
  1815. assert(isa<CXXRecordDecl>(CurContext));
  1816. assert(!DS.isFriendSpecified());
  1817. bool isFunc = D.isDeclarationOfFunction();
  1818. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  1819. // The Microsoft extension __interface only permits public member functions
  1820. // and prohibits constructors, destructors, operators, non-public member
  1821. // functions, static methods and data members.
  1822. unsigned InvalidDecl;
  1823. bool ShowDeclName = true;
  1824. if (!isFunc)
  1825. InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
  1826. else if (AS != AS_public)
  1827. InvalidDecl = 2;
  1828. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  1829. InvalidDecl = 3;
  1830. else switch (Name.getNameKind()) {
  1831. case DeclarationName::CXXConstructorName:
  1832. InvalidDecl = 4;
  1833. ShowDeclName = false;
  1834. break;
  1835. case DeclarationName::CXXDestructorName:
  1836. InvalidDecl = 5;
  1837. ShowDeclName = false;
  1838. break;
  1839. case DeclarationName::CXXOperatorName:
  1840. case DeclarationName::CXXConversionFunctionName:
  1841. InvalidDecl = 6;
  1842. break;
  1843. default:
  1844. InvalidDecl = 0;
  1845. break;
  1846. }
  1847. if (InvalidDecl) {
  1848. if (ShowDeclName)
  1849. Diag(Loc, diag::err_invalid_member_in_interface)
  1850. << (InvalidDecl-1) << Name;
  1851. else
  1852. Diag(Loc, diag::err_invalid_member_in_interface)
  1853. << (InvalidDecl-1) << "";
  1854. return nullptr;
  1855. }
  1856. }
  1857. // C++ 9.2p6: A member shall not be declared to have automatic storage
  1858. // duration (auto, register) or with the extern storage-class-specifier.
  1859. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  1860. // data members and cannot be applied to names declared const or static,
  1861. // and cannot be applied to reference members.
  1862. switch (DS.getStorageClassSpec()) {
  1863. case DeclSpec::SCS_unspecified:
  1864. case DeclSpec::SCS_typedef:
  1865. case DeclSpec::SCS_static:
  1866. break;
  1867. case DeclSpec::SCS_mutable:
  1868. if (isFunc) {
  1869. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  1870. // FIXME: It would be nicer if the keyword was ignored only for this
  1871. // declarator. Otherwise we could get follow-up errors.
  1872. D.getMutableDeclSpec().ClearStorageClassSpecs();
  1873. }
  1874. break;
  1875. default:
  1876. Diag(DS.getStorageClassSpecLoc(),
  1877. diag::err_storageclass_invalid_for_member);
  1878. D.getMutableDeclSpec().ClearStorageClassSpecs();
  1879. break;
  1880. }
  1881. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  1882. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  1883. !isFunc);
  1884. if (DS.isConstexprSpecified() && isInstField) {
  1885. SemaDiagnosticBuilder B =
  1886. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  1887. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  1888. if (InitStyle == ICIS_NoInit) {
  1889. B << 0 << 0;
  1890. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  1891. B << FixItHint::CreateRemoval(ConstexprLoc);
  1892. else {
  1893. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  1894. D.getMutableDeclSpec().ClearConstexprSpec();
  1895. const char *PrevSpec;
  1896. unsigned DiagID;
  1897. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  1898. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  1899. (void)Failed;
  1900. assert(!Failed && "Making a constexpr member const shouldn't fail");
  1901. }
  1902. } else {
  1903. B << 1;
  1904. const char *PrevSpec;
  1905. unsigned DiagID;
  1906. if (D.getMutableDeclSpec().SetStorageClassSpec(
  1907. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  1908. Context.getPrintingPolicy())) {
  1909. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  1910. "This is the only DeclSpec that should fail to be applied");
  1911. B << 1;
  1912. } else {
  1913. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  1914. isInstField = false;
  1915. }
  1916. }
  1917. }
  1918. NamedDecl *Member;
  1919. if (isInstField) {
  1920. CXXScopeSpec &SS = D.getCXXScopeSpec();
  1921. // Data members must have identifiers for names.
  1922. if (!Name.isIdentifier()) {
  1923. Diag(Loc, diag::err_bad_variable_name)
  1924. << Name;
  1925. return nullptr;
  1926. }
  1927. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1928. // Member field could not be with "template" keyword.
  1929. // So TemplateParameterLists should be empty in this case.
  1930. if (TemplateParameterLists.size()) {
  1931. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  1932. if (TemplateParams->size()) {
  1933. // There is no such thing as a member field template.
  1934. Diag(D.getIdentifierLoc(), diag::err_template_member)
  1935. << II
  1936. << SourceRange(TemplateParams->getTemplateLoc(),
  1937. TemplateParams->getRAngleLoc());
  1938. } else {
  1939. // There is an extraneous 'template<>' for this member.
  1940. Diag(TemplateParams->getTemplateLoc(),
  1941. diag::err_template_member_noparams)
  1942. << II
  1943. << SourceRange(TemplateParams->getTemplateLoc(),
  1944. TemplateParams->getRAngleLoc());
  1945. }
  1946. return nullptr;
  1947. }
  1948. if (SS.isSet() && !SS.isInvalid()) {
  1949. // The user provided a superfluous scope specifier inside a class
  1950. // definition:
  1951. //
  1952. // class X {
  1953. // int X::member;
  1954. // };
  1955. if (DeclContext *DC = computeDeclContext(SS, false))
  1956. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
  1957. else
  1958. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  1959. << Name << SS.getRange();
  1960. SS.clear();
  1961. }
  1962. AttributeList *MSPropertyAttr =
  1963. getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
  1964. if (MSPropertyAttr) {
  1965. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  1966. BitWidth, InitStyle, AS, MSPropertyAttr);
  1967. if (!Member)
  1968. return nullptr;
  1969. isInstField = false;
  1970. } else {
  1971. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  1972. BitWidth, InitStyle, AS);
  1973. assert(Member && "HandleField never returns null");
  1974. }
  1975. } else {
  1976. Member = HandleDeclarator(S, D, TemplateParameterLists);
  1977. if (!Member)
  1978. return nullptr;
  1979. // Non-instance-fields can't have a bitfield.
  1980. if (BitWidth) {
  1981. if (Member->isInvalidDecl()) {
  1982. // don't emit another diagnostic.
  1983. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  1984. // C++ 9.6p3: A bit-field shall not be a static member.
  1985. // "static member 'A' cannot be a bit-field"
  1986. Diag(Loc, diag::err_static_not_bitfield)
  1987. << Name << BitWidth->getSourceRange();
  1988. } else if (isa<TypedefDecl>(Member)) {
  1989. // "typedef member 'x' cannot be a bit-field"
  1990. Diag(Loc, diag::err_typedef_not_bitfield)
  1991. << Name << BitWidth->getSourceRange();
  1992. } else {
  1993. // A function typedef ("typedef int f(); f a;").
  1994. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  1995. Diag(Loc, diag::err_not_integral_type_bitfield)
  1996. << Name << cast<ValueDecl>(Member)->getType()
  1997. << BitWidth->getSourceRange();
  1998. }
  1999. BitWidth = nullptr;
  2000. Member->setInvalidDecl();
  2001. }
  2002. Member->setAccess(AS);
  2003. // If we have declared a member function template or static data member
  2004. // template, set the access of the templated declaration as well.
  2005. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  2006. FunTmpl->getTemplatedDecl()->setAccess(AS);
  2007. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  2008. VarTmpl->getTemplatedDecl()->setAccess(AS);
  2009. }
  2010. if (VS.isOverrideSpecified())
  2011. Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
  2012. if (VS.isFinalSpecified())
  2013. Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
  2014. VS.isFinalSpelledSealed()));
  2015. if (VS.getLastLocation().isValid()) {
  2016. // Update the end location of a method that has a virt-specifiers.
  2017. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  2018. MD->setRangeEnd(VS.getLastLocation());
  2019. }
  2020. CheckOverrideControl(Member);
  2021. assert((Name || isInstField) && "No identifier for non-field ?");
  2022. if (isInstField) {
  2023. FieldDecl *FD = cast<FieldDecl>(Member);
  2024. FieldCollector->Add(FD);
  2025. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  2026. // Remember all explicit private FieldDecls that have a name, no side
  2027. // effects and are not part of a dependent type declaration.
  2028. if (!FD->isImplicit() && FD->getDeclName() &&
  2029. FD->getAccess() == AS_private &&
  2030. !FD->hasAttr<UnusedAttr>() &&
  2031. !FD->getParent()->isDependentContext() &&
  2032. !InitializationHasSideEffects(*FD))
  2033. UnusedPrivateFields.insert(FD);
  2034. }
  2035. }
  2036. return Member;
  2037. }
  2038. namespace {
  2039. class UninitializedFieldVisitor
  2040. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  2041. Sema &S;
  2042. // List of Decls to generate a warning on. Also remove Decls that become
  2043. // initialized.
  2044. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  2045. // List of base classes of the record. Classes are removed after their
  2046. // initializers.
  2047. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  2048. // Vector of decls to be removed from the Decl set prior to visiting the
  2049. // nodes. These Decls may have been initialized in the prior initializer.
  2050. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  2051. // If non-null, add a note to the warning pointing back to the constructor.
  2052. const CXXConstructorDecl *Constructor;
  2053. // Variables to hold state when processing an initializer list. When
  2054. // InitList is true, special case initialization of FieldDecls matching
  2055. // InitListFieldDecl.
  2056. bool InitList;
  2057. FieldDecl *InitListFieldDecl;
  2058. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  2059. public:
  2060. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  2061. UninitializedFieldVisitor(Sema &S,
  2062. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  2063. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  2064. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  2065. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  2066. // Returns true if the use of ME is not an uninitialized use.
  2067. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  2068. bool CheckReferenceOnly) {
  2069. llvm::SmallVector<FieldDecl*, 4> Fields;
  2070. bool ReferenceField = false;
  2071. while (ME) {
  2072. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  2073. if (!FD)
  2074. return false;
  2075. Fields.push_back(FD);
  2076. if (FD->getType()->isReferenceType())
  2077. ReferenceField = true;
  2078. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  2079. }
  2080. // Binding a reference to an unintialized field is not an
  2081. // uninitialized use.
  2082. if (CheckReferenceOnly && !ReferenceField)
  2083. return true;
  2084. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  2085. // Discard the first field since it is the field decl that is being
  2086. // initialized.
  2087. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  2088. UsedFieldIndex.push_back((*I)->getFieldIndex());
  2089. }
  2090. for (auto UsedIter = UsedFieldIndex.begin(),
  2091. UsedEnd = UsedFieldIndex.end(),
  2092. OrigIter = InitFieldIndex.begin(),
  2093. OrigEnd = InitFieldIndex.end();
  2094. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  2095. if (*UsedIter < *OrigIter)
  2096. return true;
  2097. if (*UsedIter > *OrigIter)
  2098. break;
  2099. }
  2100. return false;
  2101. }
  2102. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  2103. bool AddressOf) {
  2104. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  2105. return;
  2106. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  2107. // or union.
  2108. MemberExpr *FieldME = ME;
  2109. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  2110. Expr *Base = ME;
  2111. while (MemberExpr *SubME =
  2112. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  2113. if (isa<VarDecl>(SubME->getMemberDecl()))
  2114. return;
  2115. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  2116. if (!FD->isAnonymousStructOrUnion())
  2117. FieldME = SubME;
  2118. if (!FieldME->getType().isPODType(S.Context))
  2119. AllPODFields = false;
  2120. Base = SubME->getBase();
  2121. }
  2122. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  2123. return;
  2124. if (AddressOf && AllPODFields)
  2125. return;
  2126. ValueDecl* FoundVD = FieldME->getMemberDecl();
  2127. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  2128. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  2129. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  2130. }
  2131. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  2132. QualType T = BaseCast->getType();
  2133. if (T->isPointerType() &&
  2134. BaseClasses.count(T->getPointeeType())) {
  2135. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  2136. << T->getPointeeType() << FoundVD;
  2137. }
  2138. }
  2139. }
  2140. if (!Decls.count(FoundVD))
  2141. return;
  2142. const bool IsReference = FoundVD->getType()->isReferenceType();
  2143. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  2144. // Special checking for initializer lists.
  2145. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  2146. return;
  2147. }
  2148. } else {
  2149. // Prevent double warnings on use of unbounded references.
  2150. if (CheckReferenceOnly && !IsReference)
  2151. return;
  2152. }
  2153. unsigned diag = IsReference
  2154. ? diag::warn_reference_field_is_uninit
  2155. : diag::warn_field_is_uninit;
  2156. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  2157. if (Constructor)
  2158. S.Diag(Constructor->getLocation(),
  2159. diag::note_uninit_in_this_constructor)
  2160. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  2161. }
  2162. void HandleValue(Expr *E, bool AddressOf) {
  2163. E = E->IgnoreParens();
  2164. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  2165. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  2166. AddressOf /*AddressOf*/);
  2167. return;
  2168. }
  2169. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  2170. Visit(CO->getCond());
  2171. HandleValue(CO->getTrueExpr(), AddressOf);
  2172. HandleValue(CO->getFalseExpr(), AddressOf);
  2173. return;
  2174. }
  2175. if (BinaryConditionalOperator *BCO =
  2176. dyn_cast<BinaryConditionalOperator>(E)) {
  2177. Visit(BCO->getCond());
  2178. HandleValue(BCO->getFalseExpr(), AddressOf);
  2179. return;
  2180. }
  2181. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  2182. HandleValue(OVE->getSourceExpr(), AddressOf);
  2183. return;
  2184. }
  2185. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  2186. switch (BO->getOpcode()) {
  2187. default:
  2188. break;
  2189. case(BO_PtrMemD):
  2190. case(BO_PtrMemI):
  2191. HandleValue(BO->getLHS(), AddressOf);
  2192. Visit(BO->getRHS());
  2193. return;
  2194. case(BO_Comma):
  2195. Visit(BO->getLHS());
  2196. HandleValue(BO->getRHS(), AddressOf);
  2197. return;
  2198. }
  2199. }
  2200. Visit(E);
  2201. }
  2202. void CheckInitListExpr(InitListExpr *ILE) {
  2203. InitFieldIndex.push_back(0);
  2204. for (auto Child : ILE->children()) {
  2205. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  2206. CheckInitListExpr(SubList);
  2207. } else {
  2208. Visit(Child);
  2209. }
  2210. ++InitFieldIndex.back();
  2211. }
  2212. InitFieldIndex.pop_back();
  2213. }
  2214. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  2215. FieldDecl *Field, const Type *BaseClass) {
  2216. // Remove Decls that may have been initialized in the previous
  2217. // initializer.
  2218. for (ValueDecl* VD : DeclsToRemove)
  2219. Decls.erase(VD);
  2220. DeclsToRemove.clear();
  2221. Constructor = FieldConstructor;
  2222. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  2223. if (ILE && Field) {
  2224. InitList = true;
  2225. InitListFieldDecl = Field;
  2226. InitFieldIndex.clear();
  2227. CheckInitListExpr(ILE);
  2228. } else {
  2229. InitList = false;
  2230. Visit(E);
  2231. }
  2232. if (Field)
  2233. Decls.erase(Field);
  2234. if (BaseClass)
  2235. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  2236. }
  2237. void VisitMemberExpr(MemberExpr *ME) {
  2238. // All uses of unbounded reference fields will warn.
  2239. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  2240. }
  2241. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  2242. if (E->getCastKind() == CK_LValueToRValue) {
  2243. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  2244. return;
  2245. }
  2246. Inherited::VisitImplicitCastExpr(E);
  2247. }
  2248. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  2249. if (E->getConstructor()->isCopyConstructor()) {
  2250. Expr *ArgExpr = E->getArg(0);
  2251. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  2252. if (ILE->getNumInits() == 1)
  2253. ArgExpr = ILE->getInit(0);
  2254. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  2255. if (ICE->getCastKind() == CK_NoOp)
  2256. ArgExpr = ICE->getSubExpr();
  2257. HandleValue(ArgExpr, false /*AddressOf*/);
  2258. return;
  2259. }
  2260. Inherited::VisitCXXConstructExpr(E);
  2261. }
  2262. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  2263. Expr *Callee = E->getCallee();
  2264. if (isa<MemberExpr>(Callee)) {
  2265. HandleValue(Callee, false /*AddressOf*/);
  2266. for (auto Arg : E->arguments())
  2267. Visit(Arg);
  2268. return;
  2269. }
  2270. Inherited::VisitCXXMemberCallExpr(E);
  2271. }
  2272. void VisitCallExpr(CallExpr *E) {
  2273. // Treat std::move as a use.
  2274. if (E->getNumArgs() == 1) {
  2275. if (FunctionDecl *FD = E->getDirectCallee()) {
  2276. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  2277. FD->getIdentifier()->isStr("move")) {
  2278. HandleValue(E->getArg(0), false /*AddressOf*/);
  2279. return;
  2280. }
  2281. }
  2282. }
  2283. Inherited::VisitCallExpr(E);
  2284. }
  2285. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  2286. Expr *Callee = E->getCallee();
  2287. if (isa<UnresolvedLookupExpr>(Callee))
  2288. return Inherited::VisitCXXOperatorCallExpr(E);
  2289. Visit(Callee);
  2290. for (auto Arg : E->arguments())
  2291. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  2292. }
  2293. void VisitBinaryOperator(BinaryOperator *E) {
  2294. // If a field assignment is detected, remove the field from the
  2295. // uninitiailized field set.
  2296. if (E->getOpcode() == BO_Assign)
  2297. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  2298. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  2299. if (!FD->getType()->isReferenceType())
  2300. DeclsToRemove.push_back(FD);
  2301. if (E->isCompoundAssignmentOp()) {
  2302. HandleValue(E->getLHS(), false /*AddressOf*/);
  2303. Visit(E->getRHS());
  2304. return;
  2305. }
  2306. Inherited::VisitBinaryOperator(E);
  2307. }
  2308. void VisitUnaryOperator(UnaryOperator *E) {
  2309. if (E->isIncrementDecrementOp()) {
  2310. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  2311. return;
  2312. }
  2313. if (E->getOpcode() == UO_AddrOf) {
  2314. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  2315. HandleValue(ME->getBase(), true /*AddressOf*/);
  2316. return;
  2317. }
  2318. }
  2319. Inherited::VisitUnaryOperator(E);
  2320. }
  2321. };
  2322. // Diagnose value-uses of fields to initialize themselves, e.g.
  2323. // foo(foo)
  2324. // where foo is not also a parameter to the constructor.
  2325. // Also diagnose across field uninitialized use such as
  2326. // x(y), y(x)
  2327. // TODO: implement -Wuninitialized and fold this into that framework.
  2328. static void DiagnoseUninitializedFields(
  2329. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  2330. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  2331. Constructor->getLocation())) {
  2332. return;
  2333. }
  2334. if (Constructor->isInvalidDecl())
  2335. return;
  2336. const CXXRecordDecl *RD = Constructor->getParent();
  2337. if (RD->getDescribedClassTemplate())
  2338. return;
  2339. // Holds fields that are uninitialized.
  2340. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  2341. // At the beginning, all fields are uninitialized.
  2342. for (auto *I : RD->decls()) {
  2343. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  2344. UninitializedFields.insert(FD);
  2345. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  2346. UninitializedFields.insert(IFD->getAnonField());
  2347. }
  2348. }
  2349. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  2350. for (auto I : RD->bases())
  2351. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  2352. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  2353. return;
  2354. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  2355. UninitializedFields,
  2356. UninitializedBaseClasses);
  2357. for (const auto *FieldInit : Constructor->inits()) {
  2358. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  2359. break;
  2360. Expr *InitExpr = FieldInit->getInit();
  2361. if (!InitExpr)
  2362. continue;
  2363. if (CXXDefaultInitExpr *Default =
  2364. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  2365. InitExpr = Default->getExpr();
  2366. if (!InitExpr)
  2367. continue;
  2368. // In class initializers will point to the constructor.
  2369. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  2370. FieldInit->getAnyMember(),
  2371. FieldInit->getBaseClass());
  2372. } else {
  2373. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  2374. FieldInit->getAnyMember(),
  2375. FieldInit->getBaseClass());
  2376. }
  2377. }
  2378. }
  2379. } // namespace
  2380. /// \brief Enter a new C++ default initializer scope. After calling this, the
  2381. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  2382. /// parsing or instantiating the initializer failed.
  2383. void Sema::ActOnStartCXXInClassMemberInitializer() {
  2384. // Create a synthetic function scope to represent the call to the constructor
  2385. // that notionally surrounds a use of this initializer.
  2386. PushFunctionScope();
  2387. }
  2388. /// \brief This is invoked after parsing an in-class initializer for a
  2389. /// non-static C++ class member, and after instantiating an in-class initializer
  2390. /// in a class template. Such actions are deferred until the class is complete.
  2391. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  2392. SourceLocation InitLoc,
  2393. Expr *InitExpr) {
  2394. // Pop the notional constructor scope we created earlier.
  2395. PopFunctionScopeInfo(nullptr, D);
  2396. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  2397. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  2398. "must set init style when field is created");
  2399. if (!InitExpr) {
  2400. D->setInvalidDecl();
  2401. if (FD)
  2402. FD->removeInClassInitializer();
  2403. return;
  2404. }
  2405. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  2406. FD->setInvalidDecl();
  2407. FD->removeInClassInitializer();
  2408. return;
  2409. }
  2410. ExprResult Init = InitExpr;
  2411. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  2412. InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
  2413. InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
  2414. ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
  2415. : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
  2416. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  2417. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  2418. if (Init.isInvalid()) {
  2419. FD->setInvalidDecl();
  2420. return;
  2421. }
  2422. }
  2423. // C++11 [class.base.init]p7:
  2424. // The initialization of each base and member constitutes a
  2425. // full-expression.
  2426. Init = ActOnFinishFullExpr(Init.get(), InitLoc);
  2427. if (Init.isInvalid()) {
  2428. FD->setInvalidDecl();
  2429. return;
  2430. }
  2431. InitExpr = Init.get();
  2432. FD->setInClassInitializer(InitExpr);
  2433. }
  2434. /// \brief Find the direct and/or virtual base specifiers that
  2435. /// correspond to the given base type, for use in base initialization
  2436. /// within a constructor.
  2437. static bool FindBaseInitializer(Sema &SemaRef,
  2438. CXXRecordDecl *ClassDecl,
  2439. QualType BaseType,
  2440. const CXXBaseSpecifier *&DirectBaseSpec,
  2441. const CXXBaseSpecifier *&VirtualBaseSpec) {
  2442. // First, check for a direct base class.
  2443. DirectBaseSpec = nullptr;
  2444. for (const auto &Base : ClassDecl->bases()) {
  2445. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  2446. // We found a direct base of this type. That's what we're
  2447. // initializing.
  2448. DirectBaseSpec = &Base;
  2449. break;
  2450. }
  2451. }
  2452. // Check for a virtual base class.
  2453. // FIXME: We might be able to short-circuit this if we know in advance that
  2454. // there are no virtual bases.
  2455. VirtualBaseSpec = nullptr;
  2456. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  2457. // We haven't found a base yet; search the class hierarchy for a
  2458. // virtual base class.
  2459. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2460. /*DetectVirtual=*/false);
  2461. if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
  2462. BaseType, Paths)) {
  2463. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2464. Path != Paths.end(); ++Path) {
  2465. if (Path->back().Base->isVirtual()) {
  2466. VirtualBaseSpec = Path->back().Base;
  2467. break;
  2468. }
  2469. }
  2470. }
  2471. }
  2472. return DirectBaseSpec || VirtualBaseSpec;
  2473. }
  2474. /// \brief Handle a C++ member initializer using braced-init-list syntax.
  2475. MemInitResult
  2476. Sema::ActOnMemInitializer(Decl *ConstructorD,
  2477. Scope *S,
  2478. CXXScopeSpec &SS,
  2479. IdentifierInfo *MemberOrBase,
  2480. ParsedType TemplateTypeTy,
  2481. const DeclSpec &DS,
  2482. SourceLocation IdLoc,
  2483. Expr *InitList,
  2484. SourceLocation EllipsisLoc) {
  2485. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  2486. DS, IdLoc, InitList,
  2487. EllipsisLoc);
  2488. }
  2489. /// \brief Handle a C++ member initializer using parentheses syntax.
  2490. MemInitResult
  2491. Sema::ActOnMemInitializer(Decl *ConstructorD,
  2492. Scope *S,
  2493. CXXScopeSpec &SS,
  2494. IdentifierInfo *MemberOrBase,
  2495. ParsedType TemplateTypeTy,
  2496. const DeclSpec &DS,
  2497. SourceLocation IdLoc,
  2498. SourceLocation LParenLoc,
  2499. ArrayRef<Expr *> Args,
  2500. SourceLocation RParenLoc,
  2501. SourceLocation EllipsisLoc) {
  2502. Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
  2503. Args, RParenLoc);
  2504. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  2505. DS, IdLoc, List, EllipsisLoc);
  2506. }
  2507. namespace {
  2508. // Callback to only accept typo corrections that can be a valid C++ member
  2509. // intializer: either a non-static field member or a base class.
  2510. class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
  2511. public:
  2512. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  2513. : ClassDecl(ClassDecl) {}
  2514. bool ValidateCandidate(const TypoCorrection &candidate) override {
  2515. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  2516. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  2517. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  2518. return isa<TypeDecl>(ND);
  2519. }
  2520. return false;
  2521. }
  2522. private:
  2523. CXXRecordDecl *ClassDecl;
  2524. };
  2525. }
  2526. /// \brief Handle a C++ member initializer.
  2527. MemInitResult
  2528. Sema::BuildMemInitializer(Decl *ConstructorD,
  2529. Scope *S,
  2530. CXXScopeSpec &SS,
  2531. IdentifierInfo *MemberOrBase,
  2532. ParsedType TemplateTypeTy,
  2533. const DeclSpec &DS,
  2534. SourceLocation IdLoc,
  2535. Expr *Init,
  2536. SourceLocation EllipsisLoc) {
  2537. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  2538. if (!Res.isUsable())
  2539. return true;
  2540. Init = Res.get();
  2541. if (!ConstructorD)
  2542. return true;
  2543. AdjustDeclIfTemplate(ConstructorD);
  2544. CXXConstructorDecl *Constructor
  2545. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  2546. if (!Constructor) {
  2547. // The user wrote a constructor initializer on a function that is
  2548. // not a C++ constructor. Ignore the error for now, because we may
  2549. // have more member initializers coming; we'll diagnose it just
  2550. // once in ActOnMemInitializers.
  2551. return true;
  2552. }
  2553. CXXRecordDecl *ClassDecl = Constructor->getParent();
  2554. // C++ [class.base.init]p2:
  2555. // Names in a mem-initializer-id are looked up in the scope of the
  2556. // constructor's class and, if not found in that scope, are looked
  2557. // up in the scope containing the constructor's definition.
  2558. // [Note: if the constructor's class contains a member with the
  2559. // same name as a direct or virtual base class of the class, a
  2560. // mem-initializer-id naming the member or base class and composed
  2561. // of a single identifier refers to the class member. A
  2562. // mem-initializer-id for the hidden base class may be specified
  2563. // using a qualified name. ]
  2564. if (!SS.getScopeRep() && !TemplateTypeTy) {
  2565. // Look for a member, first.
  2566. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  2567. if (!Result.empty()) {
  2568. ValueDecl *Member;
  2569. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  2570. (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
  2571. if (EllipsisLoc.isValid())
  2572. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  2573. << MemberOrBase
  2574. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  2575. return BuildMemberInitializer(Member, Init, IdLoc);
  2576. }
  2577. }
  2578. }
  2579. // It didn't name a member, so see if it names a class.
  2580. QualType BaseType;
  2581. TypeSourceInfo *TInfo = nullptr;
  2582. if (TemplateTypeTy) {
  2583. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  2584. } else if (DS.getTypeSpecType() == TST_decltype) {
  2585. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  2586. } else {
  2587. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  2588. LookupParsedName(R, S, &SS);
  2589. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  2590. if (!TyD) {
  2591. if (R.isAmbiguous()) return true;
  2592. // We don't want access-control diagnostics here.
  2593. R.suppressDiagnostics();
  2594. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  2595. bool NotUnknownSpecialization = false;
  2596. DeclContext *DC = computeDeclContext(SS, false);
  2597. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  2598. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  2599. if (!NotUnknownSpecialization) {
  2600. // When the scope specifier can refer to a member of an unknown
  2601. // specialization, we take it as a type name.
  2602. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  2603. SS.getWithLocInContext(Context),
  2604. *MemberOrBase, IdLoc);
  2605. if (BaseType.isNull())
  2606. return true;
  2607. R.clear();
  2608. R.setLookupName(MemberOrBase);
  2609. }
  2610. }
  2611. // If no results were found, try to correct typos.
  2612. TypoCorrection Corr;
  2613. if (R.empty() && BaseType.isNull() &&
  2614. (Corr = CorrectTypo(
  2615. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  2616. llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
  2617. CTK_ErrorRecovery, ClassDecl))) {
  2618. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  2619. // We have found a non-static data member with a similar
  2620. // name to what was typed; complain and initialize that
  2621. // member.
  2622. diagnoseTypo(Corr,
  2623. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  2624. << MemberOrBase << true);
  2625. return BuildMemberInitializer(Member, Init, IdLoc);
  2626. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  2627. const CXXBaseSpecifier *DirectBaseSpec;
  2628. const CXXBaseSpecifier *VirtualBaseSpec;
  2629. if (FindBaseInitializer(*this, ClassDecl,
  2630. Context.getTypeDeclType(Type),
  2631. DirectBaseSpec, VirtualBaseSpec)) {
  2632. // We have found a direct or virtual base class with a
  2633. // similar name to what was typed; complain and initialize
  2634. // that base class.
  2635. diagnoseTypo(Corr,
  2636. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  2637. << MemberOrBase << false,
  2638. PDiag() /*Suppress note, we provide our own.*/);
  2639. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  2640. : VirtualBaseSpec;
  2641. Diag(BaseSpec->getLocStart(),
  2642. diag::note_base_class_specified_here)
  2643. << BaseSpec->getType()
  2644. << BaseSpec->getSourceRange();
  2645. TyD = Type;
  2646. }
  2647. }
  2648. }
  2649. if (!TyD && BaseType.isNull()) {
  2650. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  2651. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  2652. return true;
  2653. }
  2654. }
  2655. if (BaseType.isNull()) {
  2656. BaseType = Context.getTypeDeclType(TyD);
  2657. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  2658. if (SS.isSet())
  2659. // FIXME: preserve source range information
  2660. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  2661. BaseType);
  2662. }
  2663. }
  2664. if (!TInfo)
  2665. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  2666. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  2667. }
  2668. /// Checks a member initializer expression for cases where reference (or
  2669. /// pointer) members are bound to by-value parameters (or their addresses).
  2670. static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
  2671. Expr *Init,
  2672. SourceLocation IdLoc) {
  2673. QualType MemberTy = Member->getType();
  2674. // We only handle pointers and references currently.
  2675. // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
  2676. if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
  2677. return;
  2678. const bool IsPointer = MemberTy->isPointerType();
  2679. if (IsPointer) {
  2680. if (const UnaryOperator *Op
  2681. = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
  2682. // The only case we're worried about with pointers requires taking the
  2683. // address.
  2684. if (Op->getOpcode() != UO_AddrOf)
  2685. return;
  2686. Init = Op->getSubExpr();
  2687. } else {
  2688. // We only handle address-of expression initializers for pointers.
  2689. return;
  2690. }
  2691. }
  2692. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
  2693. // We only warn when referring to a non-reference parameter declaration.
  2694. const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
  2695. if (!Parameter || Parameter->getType()->isReferenceType())
  2696. return;
  2697. S.Diag(Init->getExprLoc(),
  2698. IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
  2699. : diag::warn_bind_ref_member_to_parameter)
  2700. << Member << Parameter << Init->getSourceRange();
  2701. } else {
  2702. // Other initializers are fine.
  2703. return;
  2704. }
  2705. S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
  2706. << (unsigned)IsPointer;
  2707. }
  2708. MemInitResult
  2709. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  2710. SourceLocation IdLoc) {
  2711. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  2712. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  2713. assert((DirectMember || IndirectMember) &&
  2714. "Member must be a FieldDecl or IndirectFieldDecl");
  2715. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  2716. return true;
  2717. if (Member->isInvalidDecl())
  2718. return true;
  2719. MultiExprArg Args;
  2720. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  2721. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  2722. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  2723. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  2724. } else {
  2725. // Template instantiation doesn't reconstruct ParenListExprs for us.
  2726. Args = Init;
  2727. }
  2728. SourceRange InitRange = Init->getSourceRange();
  2729. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  2730. // Can't check initialization for a member of dependent type or when
  2731. // any of the arguments are type-dependent expressions.
  2732. DiscardCleanupsInEvaluationContext();
  2733. } else {
  2734. bool InitList = false;
  2735. if (isa<InitListExpr>(Init)) {
  2736. InitList = true;
  2737. Args = Init;
  2738. }
  2739. // Initialize the member.
  2740. InitializedEntity MemberEntity =
  2741. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  2742. : InitializedEntity::InitializeMember(IndirectMember,
  2743. nullptr);
  2744. InitializationKind Kind =
  2745. InitList ? InitializationKind::CreateDirectList(IdLoc)
  2746. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  2747. InitRange.getEnd());
  2748. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  2749. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  2750. nullptr);
  2751. if (MemberInit.isInvalid())
  2752. return true;
  2753. CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
  2754. // C++11 [class.base.init]p7:
  2755. // The initialization of each base and member constitutes a
  2756. // full-expression.
  2757. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
  2758. if (MemberInit.isInvalid())
  2759. return true;
  2760. Init = MemberInit.get();
  2761. }
  2762. if (DirectMember) {
  2763. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  2764. InitRange.getBegin(), Init,
  2765. InitRange.getEnd());
  2766. } else {
  2767. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  2768. InitRange.getBegin(), Init,
  2769. InitRange.getEnd());
  2770. }
  2771. }
  2772. MemInitResult
  2773. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  2774. CXXRecordDecl *ClassDecl) {
  2775. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  2776. if (!LangOpts.CPlusPlus11)
  2777. return Diag(NameLoc, diag::err_delegating_ctor)
  2778. << TInfo->getTypeLoc().getLocalSourceRange();
  2779. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  2780. bool InitList = true;
  2781. MultiExprArg Args = Init;
  2782. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  2783. InitList = false;
  2784. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  2785. }
  2786. SourceRange InitRange = Init->getSourceRange();
  2787. // Initialize the object.
  2788. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  2789. QualType(ClassDecl->getTypeForDecl(), 0));
  2790. InitializationKind Kind =
  2791. InitList ? InitializationKind::CreateDirectList(NameLoc)
  2792. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  2793. InitRange.getEnd());
  2794. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  2795. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  2796. Args, nullptr);
  2797. if (DelegationInit.isInvalid())
  2798. return true;
  2799. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  2800. "Delegating constructor with no target?");
  2801. // C++11 [class.base.init]p7:
  2802. // The initialization of each base and member constitutes a
  2803. // full-expression.
  2804. DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
  2805. InitRange.getBegin());
  2806. if (DelegationInit.isInvalid())
  2807. return true;
  2808. // If we are in a dependent context, template instantiation will
  2809. // perform this type-checking again. Just save the arguments that we
  2810. // received in a ParenListExpr.
  2811. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  2812. // of the information that we have about the base
  2813. // initializer. However, deconstructing the ASTs is a dicey process,
  2814. // and this approach is far more likely to get the corner cases right.
  2815. if (CurContext->isDependentContext())
  2816. DelegationInit = Init;
  2817. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  2818. DelegationInit.getAs<Expr>(),
  2819. InitRange.getEnd());
  2820. }
  2821. MemInitResult
  2822. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  2823. Expr *Init, CXXRecordDecl *ClassDecl,
  2824. SourceLocation EllipsisLoc) {
  2825. SourceLocation BaseLoc
  2826. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  2827. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  2828. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  2829. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  2830. // C++ [class.base.init]p2:
  2831. // [...] Unless the mem-initializer-id names a nonstatic data
  2832. // member of the constructor's class or a direct or virtual base
  2833. // of that class, the mem-initializer is ill-formed. A
  2834. // mem-initializer-list can initialize a base class using any
  2835. // name that denotes that base class type.
  2836. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  2837. SourceRange InitRange = Init->getSourceRange();
  2838. if (EllipsisLoc.isValid()) {
  2839. // This is a pack expansion.
  2840. if (!BaseType->containsUnexpandedParameterPack()) {
  2841. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  2842. << SourceRange(BaseLoc, InitRange.getEnd());
  2843. EllipsisLoc = SourceLocation();
  2844. }
  2845. } else {
  2846. // Check for any unexpanded parameter packs.
  2847. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  2848. return true;
  2849. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  2850. return true;
  2851. }
  2852. // Check for direct and virtual base classes.
  2853. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  2854. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  2855. if (!Dependent) {
  2856. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  2857. BaseType))
  2858. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  2859. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  2860. VirtualBaseSpec);
  2861. // C++ [base.class.init]p2:
  2862. // Unless the mem-initializer-id names a nonstatic data member of the
  2863. // constructor's class or a direct or virtual base of that class, the
  2864. // mem-initializer is ill-formed.
  2865. if (!DirectBaseSpec && !VirtualBaseSpec) {
  2866. // If the class has any dependent bases, then it's possible that
  2867. // one of those types will resolve to the same type as
  2868. // BaseType. Therefore, just treat this as a dependent base
  2869. // class initialization. FIXME: Should we try to check the
  2870. // initialization anyway? It seems odd.
  2871. if (ClassDecl->hasAnyDependentBases())
  2872. Dependent = true;
  2873. else
  2874. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  2875. << BaseType << Context.getTypeDeclType(ClassDecl)
  2876. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  2877. }
  2878. }
  2879. if (Dependent) {
  2880. DiscardCleanupsInEvaluationContext();
  2881. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  2882. /*IsVirtual=*/false,
  2883. InitRange.getBegin(), Init,
  2884. InitRange.getEnd(), EllipsisLoc);
  2885. }
  2886. // C++ [base.class.init]p2:
  2887. // If a mem-initializer-id is ambiguous because it designates both
  2888. // a direct non-virtual base class and an inherited virtual base
  2889. // class, the mem-initializer is ill-formed.
  2890. if (DirectBaseSpec && VirtualBaseSpec)
  2891. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  2892. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  2893. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  2894. if (!BaseSpec)
  2895. BaseSpec = VirtualBaseSpec;
  2896. // Initialize the base.
  2897. bool InitList = true;
  2898. MultiExprArg Args = Init;
  2899. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  2900. InitList = false;
  2901. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  2902. }
  2903. InitializedEntity BaseEntity =
  2904. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  2905. InitializationKind Kind =
  2906. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  2907. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  2908. InitRange.getEnd());
  2909. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  2910. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  2911. if (BaseInit.isInvalid())
  2912. return true;
  2913. // C++11 [class.base.init]p7:
  2914. // The initialization of each base and member constitutes a
  2915. // full-expression.
  2916. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
  2917. if (BaseInit.isInvalid())
  2918. return true;
  2919. // If we are in a dependent context, template instantiation will
  2920. // perform this type-checking again. Just save the arguments that we
  2921. // received in a ParenListExpr.
  2922. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  2923. // of the information that we have about the base
  2924. // initializer. However, deconstructing the ASTs is a dicey process,
  2925. // and this approach is far more likely to get the corner cases right.
  2926. if (CurContext->isDependentContext())
  2927. BaseInit = Init;
  2928. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  2929. BaseSpec->isVirtual(),
  2930. InitRange.getBegin(),
  2931. BaseInit.getAs<Expr>(),
  2932. InitRange.getEnd(), EllipsisLoc);
  2933. }
  2934. // Create a static_cast\<T&&>(expr).
  2935. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  2936. if (T.isNull()) T = E->getType();
  2937. QualType TargetType = SemaRef.BuildReferenceType(
  2938. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  2939. SourceLocation ExprLoc = E->getLocStart();
  2940. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  2941. TargetType, ExprLoc);
  2942. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  2943. SourceRange(ExprLoc, ExprLoc),
  2944. E->getSourceRange()).get();
  2945. }
  2946. /// ImplicitInitializerKind - How an implicit base or member initializer should
  2947. /// initialize its base or member.
  2948. enum ImplicitInitializerKind {
  2949. IIK_Default,
  2950. IIK_Copy,
  2951. IIK_Move,
  2952. IIK_Inherit
  2953. };
  2954. static bool
  2955. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  2956. ImplicitInitializerKind ImplicitInitKind,
  2957. CXXBaseSpecifier *BaseSpec,
  2958. bool IsInheritedVirtualBase,
  2959. CXXCtorInitializer *&CXXBaseInit) {
  2960. InitializedEntity InitEntity
  2961. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  2962. IsInheritedVirtualBase);
  2963. ExprResult BaseInit;
  2964. switch (ImplicitInitKind) {
  2965. case IIK_Inherit: {
  2966. const CXXRecordDecl *Inherited =
  2967. Constructor->getInheritedConstructor()->getParent();
  2968. const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  2969. if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
  2970. // C++11 [class.inhctor]p8:
  2971. // Each expression in the expression-list is of the form
  2972. // static_cast<T&&>(p), where p is the name of the corresponding
  2973. // constructor parameter and T is the declared type of p.
  2974. SmallVector<Expr*, 16> Args;
  2975. for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
  2976. ParmVarDecl *PD = Constructor->getParamDecl(I);
  2977. ExprResult ArgExpr =
  2978. SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
  2979. VK_LValue, SourceLocation());
  2980. if (ArgExpr.isInvalid())
  2981. return true;
  2982. Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
  2983. }
  2984. InitializationKind InitKind = InitializationKind::CreateDirect(
  2985. Constructor->getLocation(), SourceLocation(), SourceLocation());
  2986. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
  2987. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
  2988. break;
  2989. }
  2990. }
  2991. // Fall through.
  2992. case IIK_Default: {
  2993. InitializationKind InitKind
  2994. = InitializationKind::CreateDefault(Constructor->getLocation());
  2995. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  2996. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  2997. break;
  2998. }
  2999. case IIK_Move:
  3000. case IIK_Copy: {
  3001. bool Moving = ImplicitInitKind == IIK_Move;
  3002. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3003. QualType ParamType = Param->getType().getNonReferenceType();
  3004. Expr *CopyCtorArg =
  3005. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3006. SourceLocation(), Param, false,
  3007. Constructor->getLocation(), ParamType,
  3008. VK_LValue, nullptr);
  3009. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  3010. // Cast to the base class to avoid ambiguities.
  3011. QualType ArgTy =
  3012. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  3013. ParamType.getQualifiers());
  3014. if (Moving) {
  3015. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  3016. }
  3017. CXXCastPath BasePath;
  3018. BasePath.push_back(BaseSpec);
  3019. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  3020. CK_UncheckedDerivedToBase,
  3021. Moving ? VK_XValue : VK_LValue,
  3022. &BasePath).get();
  3023. InitializationKind InitKind
  3024. = InitializationKind::CreateDirect(Constructor->getLocation(),
  3025. SourceLocation(), SourceLocation());
  3026. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3027. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3028. break;
  3029. }
  3030. }
  3031. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  3032. if (BaseInit.isInvalid())
  3033. return true;
  3034. CXXBaseInit =
  3035. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3036. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  3037. SourceLocation()),
  3038. BaseSpec->isVirtual(),
  3039. SourceLocation(),
  3040. BaseInit.getAs<Expr>(),
  3041. SourceLocation(),
  3042. SourceLocation());
  3043. return false;
  3044. }
  3045. static bool RefersToRValueRef(Expr *MemRef) {
  3046. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  3047. return Referenced->getType()->isRValueReferenceType();
  3048. }
  3049. static bool
  3050. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3051. ImplicitInitializerKind ImplicitInitKind,
  3052. FieldDecl *Field, IndirectFieldDecl *Indirect,
  3053. CXXCtorInitializer *&CXXMemberInit) {
  3054. if (Field->isInvalidDecl())
  3055. return true;
  3056. SourceLocation Loc = Constructor->getLocation();
  3057. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  3058. bool Moving = ImplicitInitKind == IIK_Move;
  3059. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3060. QualType ParamType = Param->getType().getNonReferenceType();
  3061. // Suppress copying zero-width bitfields.
  3062. if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
  3063. return false;
  3064. Expr *MemberExprBase =
  3065. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3066. SourceLocation(), Param, false,
  3067. Loc, ParamType, VK_LValue, nullptr);
  3068. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  3069. if (Moving) {
  3070. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  3071. }
  3072. // Build a reference to this field within the parameter.
  3073. CXXScopeSpec SS;
  3074. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  3075. Sema::LookupMemberName);
  3076. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  3077. : cast<ValueDecl>(Field), AS_public);
  3078. MemberLookup.resolveKind();
  3079. ExprResult CtorArg
  3080. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  3081. ParamType, Loc,
  3082. /*IsArrow=*/false,
  3083. SS,
  3084. /*TemplateKWLoc=*/SourceLocation(),
  3085. /*FirstQualifierInScope=*/nullptr,
  3086. MemberLookup,
  3087. /*TemplateArgs=*/nullptr);
  3088. if (CtorArg.isInvalid())
  3089. return true;
  3090. // C++11 [class.copy]p15:
  3091. // - if a member m has rvalue reference type T&&, it is direct-initialized
  3092. // with static_cast<T&&>(x.m);
  3093. if (RefersToRValueRef(CtorArg.get())) {
  3094. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  3095. }
  3096. // When the field we are copying is an array, create index variables for
  3097. // each dimension of the array. We use these index variables to subscript
  3098. // the source array, and other clients (e.g., CodeGen) will perform the
  3099. // necessary iteration with these index variables.
  3100. SmallVector<VarDecl *, 4> IndexVariables;
  3101. QualType BaseType = Field->getType();
  3102. QualType SizeType = SemaRef.Context.getSizeType();
  3103. bool InitializingArray = false;
  3104. while (const ConstantArrayType *Array
  3105. = SemaRef.Context.getAsConstantArrayType(BaseType)) {
  3106. InitializingArray = true;
  3107. // Create the iteration variable for this array index.
  3108. IdentifierInfo *IterationVarName = nullptr;
  3109. {
  3110. SmallString<8> Str;
  3111. llvm::raw_svector_ostream OS(Str);
  3112. OS << "__i" << IndexVariables.size();
  3113. IterationVarName = &SemaRef.Context.Idents.get(OS.str());
  3114. }
  3115. VarDecl *IterationVar
  3116. = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
  3117. IterationVarName, SizeType,
  3118. SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  3119. SC_None);
  3120. IndexVariables.push_back(IterationVar);
  3121. // Create a reference to the iteration variable.
  3122. ExprResult IterationVarRef
  3123. = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
  3124. assert(!IterationVarRef.isInvalid() &&
  3125. "Reference to invented variable cannot fail!");
  3126. IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
  3127. assert(!IterationVarRef.isInvalid() &&
  3128. "Conversion of invented variable cannot fail!");
  3129. // Subscript the array with this iteration variable.
  3130. CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
  3131. IterationVarRef.get(),
  3132. Loc);
  3133. if (CtorArg.isInvalid())
  3134. return true;
  3135. BaseType = Array->getElementType();
  3136. }
  3137. // The array subscript expression is an lvalue, which is wrong for moving.
  3138. if (Moving && InitializingArray)
  3139. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  3140. // Construct the entity that we will be initializing. For an array, this
  3141. // will be first element in the array, which may require several levels
  3142. // of array-subscript entities.
  3143. SmallVector<InitializedEntity, 4> Entities;
  3144. Entities.reserve(1 + IndexVariables.size());
  3145. if (Indirect)
  3146. Entities.push_back(InitializedEntity::InitializeMember(Indirect));
  3147. else
  3148. Entities.push_back(InitializedEntity::InitializeMember(Field));
  3149. for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
  3150. Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
  3151. 0,
  3152. Entities.back()));
  3153. // Direct-initialize to use the copy constructor.
  3154. InitializationKind InitKind =
  3155. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  3156. Expr *CtorArgE = CtorArg.getAs<Expr>();
  3157. InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
  3158. CtorArgE);
  3159. ExprResult MemberInit
  3160. = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
  3161. MultiExprArg(&CtorArgE, 1));
  3162. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3163. if (MemberInit.isInvalid())
  3164. return true;
  3165. if (Indirect) {
  3166. assert(IndexVariables.size() == 0 &&
  3167. "Indirect field improperly initialized");
  3168. CXXMemberInit
  3169. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
  3170. Loc, Loc,
  3171. MemberInit.getAs<Expr>(),
  3172. Loc);
  3173. } else
  3174. CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
  3175. Loc, MemberInit.getAs<Expr>(),
  3176. Loc,
  3177. IndexVariables.data(),
  3178. IndexVariables.size());
  3179. return false;
  3180. }
  3181. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  3182. "Unhandled implicit init kind!");
  3183. QualType FieldBaseElementType =
  3184. SemaRef.Context.getBaseElementType(Field->getType());
  3185. if (FieldBaseElementType->isRecordType()) {
  3186. InitializedEntity InitEntity
  3187. = Indirect? InitializedEntity::InitializeMember(Indirect)
  3188. : InitializedEntity::InitializeMember(Field);
  3189. InitializationKind InitKind =
  3190. InitializationKind::CreateDefault(Loc);
  3191. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3192. ExprResult MemberInit =
  3193. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3194. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3195. if (MemberInit.isInvalid())
  3196. return true;
  3197. if (Indirect)
  3198. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3199. Indirect, Loc,
  3200. Loc,
  3201. MemberInit.get(),
  3202. Loc);
  3203. else
  3204. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3205. Field, Loc, Loc,
  3206. MemberInit.get(),
  3207. Loc);
  3208. return false;
  3209. }
  3210. if (!Field->getParent()->isUnion()) {
  3211. if (FieldBaseElementType->isReferenceType()) {
  3212. SemaRef.Diag(Constructor->getLocation(),
  3213. diag::err_uninitialized_member_in_ctor)
  3214. << (int)Constructor->isImplicit()
  3215. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3216. << 0 << Field->getDeclName();
  3217. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3218. return true;
  3219. }
  3220. if (FieldBaseElementType.isConstQualified()) {
  3221. SemaRef.Diag(Constructor->getLocation(),
  3222. diag::err_uninitialized_member_in_ctor)
  3223. << (int)Constructor->isImplicit()
  3224. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3225. << 1 << Field->getDeclName();
  3226. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3227. return true;
  3228. }
  3229. }
  3230. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  3231. FieldBaseElementType->isObjCRetainableType() &&
  3232. FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
  3233. FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
  3234. // ARC:
  3235. // Default-initialize Objective-C pointers to NULL.
  3236. CXXMemberInit
  3237. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  3238. Loc, Loc,
  3239. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  3240. Loc);
  3241. return false;
  3242. }
  3243. // Nothing to initialize.
  3244. CXXMemberInit = nullptr;
  3245. return false;
  3246. }
  3247. namespace {
  3248. struct BaseAndFieldInfo {
  3249. Sema &S;
  3250. CXXConstructorDecl *Ctor;
  3251. bool AnyErrorsInInits;
  3252. ImplicitInitializerKind IIK;
  3253. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  3254. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  3255. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  3256. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  3257. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  3258. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  3259. if (Generated && Ctor->isCopyConstructor())
  3260. IIK = IIK_Copy;
  3261. else if (Generated && Ctor->isMoveConstructor())
  3262. IIK = IIK_Move;
  3263. else if (Ctor->getInheritedConstructor())
  3264. IIK = IIK_Inherit;
  3265. else
  3266. IIK = IIK_Default;
  3267. }
  3268. bool isImplicitCopyOrMove() const {
  3269. switch (IIK) {
  3270. case IIK_Copy:
  3271. case IIK_Move:
  3272. return true;
  3273. case IIK_Default:
  3274. case IIK_Inherit:
  3275. return false;
  3276. }
  3277. llvm_unreachable("Invalid ImplicitInitializerKind!");
  3278. }
  3279. bool addFieldInitializer(CXXCtorInitializer *Init) {
  3280. AllToInit.push_back(Init);
  3281. // Check whether this initializer makes the field "used".
  3282. if (Init->getInit()->HasSideEffects(S.Context))
  3283. S.UnusedPrivateFields.remove(Init->getAnyMember());
  3284. return false;
  3285. }
  3286. bool isInactiveUnionMember(FieldDecl *Field) {
  3287. RecordDecl *Record = Field->getParent();
  3288. if (!Record->isUnion())
  3289. return false;
  3290. if (FieldDecl *Active =
  3291. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  3292. return Active != Field->getCanonicalDecl();
  3293. // In an implicit copy or move constructor, ignore any in-class initializer.
  3294. if (isImplicitCopyOrMove())
  3295. return true;
  3296. // If there's no explicit initialization, the field is active only if it
  3297. // has an in-class initializer...
  3298. if (Field->hasInClassInitializer())
  3299. return false;
  3300. // ... or it's an anonymous struct or union whose class has an in-class
  3301. // initializer.
  3302. if (!Field->isAnonymousStructOrUnion())
  3303. return true;
  3304. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  3305. return !FieldRD->hasInClassInitializer();
  3306. }
  3307. /// \brief Determine whether the given field is, or is within, a union member
  3308. /// that is inactive (because there was an initializer given for a different
  3309. /// member of the union, or because the union was not initialized at all).
  3310. bool isWithinInactiveUnionMember(FieldDecl *Field,
  3311. IndirectFieldDecl *Indirect) {
  3312. if (!Indirect)
  3313. return isInactiveUnionMember(Field);
  3314. for (auto *C : Indirect->chain()) {
  3315. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  3316. if (Field && isInactiveUnionMember(Field))
  3317. return true;
  3318. }
  3319. return false;
  3320. }
  3321. };
  3322. }
  3323. /// \brief Determine whether the given type is an incomplete or zero-lenfgth
  3324. /// array type.
  3325. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  3326. if (T->isIncompleteArrayType())
  3327. return true;
  3328. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  3329. if (!ArrayT->getSize())
  3330. return true;
  3331. T = ArrayT->getElementType();
  3332. }
  3333. return false;
  3334. }
  3335. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  3336. FieldDecl *Field,
  3337. IndirectFieldDecl *Indirect = nullptr) {
  3338. if (Field->isInvalidDecl())
  3339. return false;
  3340. // Overwhelmingly common case: we have a direct initializer for this field.
  3341. if (CXXCtorInitializer *Init =
  3342. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  3343. return Info.addFieldInitializer(Init);
  3344. // C++11 [class.base.init]p8:
  3345. // if the entity is a non-static data member that has a
  3346. // brace-or-equal-initializer and either
  3347. // -- the constructor's class is a union and no other variant member of that
  3348. // union is designated by a mem-initializer-id or
  3349. // -- the constructor's class is not a union, and, if the entity is a member
  3350. // of an anonymous union, no other member of that union is designated by
  3351. // a mem-initializer-id,
  3352. // the entity is initialized as specified in [dcl.init].
  3353. //
  3354. // We also apply the same rules to handle anonymous structs within anonymous
  3355. // unions.
  3356. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  3357. return false;
  3358. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  3359. ExprResult DIE =
  3360. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  3361. if (DIE.isInvalid())
  3362. return true;
  3363. CXXCtorInitializer *Init;
  3364. if (Indirect)
  3365. Init = new (SemaRef.Context)
  3366. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  3367. SourceLocation(), DIE.get(), SourceLocation());
  3368. else
  3369. Init = new (SemaRef.Context)
  3370. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  3371. SourceLocation(), DIE.get(), SourceLocation());
  3372. return Info.addFieldInitializer(Init);
  3373. }
  3374. // Don't initialize incomplete or zero-length arrays.
  3375. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  3376. return false;
  3377. // Don't try to build an implicit initializer if there were semantic
  3378. // errors in any of the initializers (and therefore we might be
  3379. // missing some that the user actually wrote).
  3380. if (Info.AnyErrorsInInits)
  3381. return false;
  3382. CXXCtorInitializer *Init = nullptr;
  3383. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  3384. Indirect, Init))
  3385. return true;
  3386. if (!Init)
  3387. return false;
  3388. return Info.addFieldInitializer(Init);
  3389. }
  3390. bool
  3391. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  3392. CXXCtorInitializer *Initializer) {
  3393. assert(Initializer->isDelegatingInitializer());
  3394. Constructor->setNumCtorInitializers(1);
  3395. CXXCtorInitializer **initializer =
  3396. new (Context) CXXCtorInitializer*[1];
  3397. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  3398. Constructor->setCtorInitializers(initializer);
  3399. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  3400. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  3401. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  3402. }
  3403. DelegatingCtorDecls.push_back(Constructor);
  3404. DiagnoseUninitializedFields(*this, Constructor);
  3405. return false;
  3406. }
  3407. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  3408. ArrayRef<CXXCtorInitializer *> Initializers) {
  3409. if (Constructor->isDependentContext()) {
  3410. // Just store the initializers as written, they will be checked during
  3411. // instantiation.
  3412. if (!Initializers.empty()) {
  3413. Constructor->setNumCtorInitializers(Initializers.size());
  3414. CXXCtorInitializer **baseOrMemberInitializers =
  3415. new (Context) CXXCtorInitializer*[Initializers.size()];
  3416. memcpy(baseOrMemberInitializers, Initializers.data(),
  3417. Initializers.size() * sizeof(CXXCtorInitializer*));
  3418. Constructor->setCtorInitializers(baseOrMemberInitializers);
  3419. }
  3420. // Let template instantiation know whether we had errors.
  3421. if (AnyErrors)
  3422. Constructor->setInvalidDecl();
  3423. return false;
  3424. }
  3425. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  3426. // We need to build the initializer AST according to order of construction
  3427. // and not what user specified in the Initializers list.
  3428. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  3429. if (!ClassDecl)
  3430. return true;
  3431. bool HadError = false;
  3432. for (unsigned i = 0; i < Initializers.size(); i++) {
  3433. CXXCtorInitializer *Member = Initializers[i];
  3434. if (Member->isBaseInitializer())
  3435. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  3436. else {
  3437. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  3438. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  3439. for (auto *C : F->chain()) {
  3440. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  3441. if (FD && FD->getParent()->isUnion())
  3442. Info.ActiveUnionMember.insert(std::make_pair(
  3443. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  3444. }
  3445. } else if (FieldDecl *FD = Member->getMember()) {
  3446. if (FD->getParent()->isUnion())
  3447. Info.ActiveUnionMember.insert(std::make_pair(
  3448. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  3449. }
  3450. }
  3451. }
  3452. // Keep track of the direct virtual bases.
  3453. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  3454. for (auto &I : ClassDecl->bases()) {
  3455. if (I.isVirtual())
  3456. DirectVBases.insert(&I);
  3457. }
  3458. // Push virtual bases before others.
  3459. for (auto &VBase : ClassDecl->vbases()) {
  3460. if (CXXCtorInitializer *Value
  3461. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  3462. // [class.base.init]p7, per DR257:
  3463. // A mem-initializer where the mem-initializer-id names a virtual base
  3464. // class is ignored during execution of a constructor of any class that
  3465. // is not the most derived class.
  3466. if (ClassDecl->isAbstract()) {
  3467. // FIXME: Provide a fixit to remove the base specifier. This requires
  3468. // tracking the location of the associated comma for a base specifier.
  3469. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  3470. << VBase.getType() << ClassDecl;
  3471. DiagnoseAbstractType(ClassDecl);
  3472. }
  3473. Info.AllToInit.push_back(Value);
  3474. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  3475. // [class.base.init]p8, per DR257:
  3476. // If a given [...] base class is not named by a mem-initializer-id
  3477. // [...] and the entity is not a virtual base class of an abstract
  3478. // class, then [...] the entity is default-initialized.
  3479. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  3480. CXXCtorInitializer *CXXBaseInit;
  3481. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  3482. &VBase, IsInheritedVirtualBase,
  3483. CXXBaseInit)) {
  3484. HadError = true;
  3485. continue;
  3486. }
  3487. Info.AllToInit.push_back(CXXBaseInit);
  3488. }
  3489. }
  3490. // Non-virtual bases.
  3491. for (auto &Base : ClassDecl->bases()) {
  3492. // Virtuals are in the virtual base list and already constructed.
  3493. if (Base.isVirtual())
  3494. continue;
  3495. if (CXXCtorInitializer *Value
  3496. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  3497. Info.AllToInit.push_back(Value);
  3498. } else if (!AnyErrors) {
  3499. CXXCtorInitializer *CXXBaseInit;
  3500. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  3501. &Base, /*IsInheritedVirtualBase=*/false,
  3502. CXXBaseInit)) {
  3503. HadError = true;
  3504. continue;
  3505. }
  3506. Info.AllToInit.push_back(CXXBaseInit);
  3507. }
  3508. }
  3509. // Fields.
  3510. for (auto *Mem : ClassDecl->decls()) {
  3511. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  3512. // C++ [class.bit]p2:
  3513. // A declaration for a bit-field that omits the identifier declares an
  3514. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  3515. // initialized.
  3516. if (F->isUnnamedBitfield())
  3517. continue;
  3518. // If we're not generating the implicit copy/move constructor, then we'll
  3519. // handle anonymous struct/union fields based on their individual
  3520. // indirect fields.
  3521. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  3522. continue;
  3523. if (CollectFieldInitializer(*this, Info, F))
  3524. HadError = true;
  3525. continue;
  3526. }
  3527. // Beyond this point, we only consider default initialization.
  3528. if (Info.isImplicitCopyOrMove())
  3529. continue;
  3530. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  3531. if (F->getType()->isIncompleteArrayType()) {
  3532. assert(ClassDecl->hasFlexibleArrayMember() &&
  3533. "Incomplete array type is not valid");
  3534. continue;
  3535. }
  3536. // Initialize each field of an anonymous struct individually.
  3537. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  3538. HadError = true;
  3539. continue;
  3540. }
  3541. }
  3542. unsigned NumInitializers = Info.AllToInit.size();
  3543. if (NumInitializers > 0) {
  3544. Constructor->setNumCtorInitializers(NumInitializers);
  3545. CXXCtorInitializer **baseOrMemberInitializers =
  3546. new (Context) CXXCtorInitializer*[NumInitializers];
  3547. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  3548. NumInitializers * sizeof(CXXCtorInitializer*));
  3549. Constructor->setCtorInitializers(baseOrMemberInitializers);
  3550. // Constructors implicitly reference the base and member
  3551. // destructors.
  3552. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  3553. Constructor->getParent());
  3554. }
  3555. return HadError;
  3556. }
  3557. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  3558. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  3559. const RecordDecl *RD = RT->getDecl();
  3560. if (RD->isAnonymousStructOrUnion()) {
  3561. for (auto *Field : RD->fields())
  3562. PopulateKeysForFields(Field, IdealInits);
  3563. return;
  3564. }
  3565. }
  3566. IdealInits.push_back(Field->getCanonicalDecl());
  3567. }
  3568. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  3569. return Context.getCanonicalType(BaseType).getTypePtr();
  3570. }
  3571. static const void *GetKeyForMember(ASTContext &Context,
  3572. CXXCtorInitializer *Member) {
  3573. if (!Member->isAnyMemberInitializer())
  3574. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  3575. return Member->getAnyMember()->getCanonicalDecl();
  3576. }
  3577. static void DiagnoseBaseOrMemInitializerOrder(
  3578. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  3579. ArrayRef<CXXCtorInitializer *> Inits) {
  3580. if (Constructor->getDeclContext()->isDependentContext())
  3581. return;
  3582. // Don't check initializers order unless the warning is enabled at the
  3583. // location of at least one initializer.
  3584. bool ShouldCheckOrder = false;
  3585. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  3586. CXXCtorInitializer *Init = Inits[InitIndex];
  3587. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  3588. Init->getSourceLocation())) {
  3589. ShouldCheckOrder = true;
  3590. break;
  3591. }
  3592. }
  3593. if (!ShouldCheckOrder)
  3594. return;
  3595. // Build the list of bases and members in the order that they'll
  3596. // actually be initialized. The explicit initializers should be in
  3597. // this same order but may be missing things.
  3598. SmallVector<const void*, 32> IdealInitKeys;
  3599. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  3600. // 1. Virtual bases.
  3601. for (const auto &VBase : ClassDecl->vbases())
  3602. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  3603. // 2. Non-virtual bases.
  3604. for (const auto &Base : ClassDecl->bases()) {
  3605. if (Base.isVirtual())
  3606. continue;
  3607. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  3608. }
  3609. // 3. Direct fields.
  3610. for (auto *Field : ClassDecl->fields()) {
  3611. if (Field->isUnnamedBitfield())
  3612. continue;
  3613. PopulateKeysForFields(Field, IdealInitKeys);
  3614. }
  3615. unsigned NumIdealInits = IdealInitKeys.size();
  3616. unsigned IdealIndex = 0;
  3617. CXXCtorInitializer *PrevInit = nullptr;
  3618. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  3619. CXXCtorInitializer *Init = Inits[InitIndex];
  3620. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  3621. // Scan forward to try to find this initializer in the idealized
  3622. // initializers list.
  3623. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  3624. if (InitKey == IdealInitKeys[IdealIndex])
  3625. break;
  3626. // If we didn't find this initializer, it must be because we
  3627. // scanned past it on a previous iteration. That can only
  3628. // happen if we're out of order; emit a warning.
  3629. if (IdealIndex == NumIdealInits && PrevInit) {
  3630. Sema::SemaDiagnosticBuilder D =
  3631. SemaRef.Diag(PrevInit->getSourceLocation(),
  3632. diag::warn_initializer_out_of_order);
  3633. if (PrevInit->isAnyMemberInitializer())
  3634. D << 0 << PrevInit->getAnyMember()->getDeclName();
  3635. else
  3636. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  3637. if (Init->isAnyMemberInitializer())
  3638. D << 0 << Init->getAnyMember()->getDeclName();
  3639. else
  3640. D << 1 << Init->getTypeSourceInfo()->getType();
  3641. // Move back to the initializer's location in the ideal list.
  3642. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  3643. if (InitKey == IdealInitKeys[IdealIndex])
  3644. break;
  3645. assert(IdealIndex != NumIdealInits &&
  3646. "initializer not found in initializer list");
  3647. }
  3648. PrevInit = Init;
  3649. }
  3650. }
  3651. namespace {
  3652. bool CheckRedundantInit(Sema &S,
  3653. CXXCtorInitializer *Init,
  3654. CXXCtorInitializer *&PrevInit) {
  3655. if (!PrevInit) {
  3656. PrevInit = Init;
  3657. return false;
  3658. }
  3659. if (FieldDecl *Field = Init->getAnyMember())
  3660. S.Diag(Init->getSourceLocation(),
  3661. diag::err_multiple_mem_initialization)
  3662. << Field->getDeclName()
  3663. << Init->getSourceRange();
  3664. else {
  3665. const Type *BaseClass = Init->getBaseClass();
  3666. assert(BaseClass && "neither field nor base");
  3667. S.Diag(Init->getSourceLocation(),
  3668. diag::err_multiple_base_initialization)
  3669. << QualType(BaseClass, 0)
  3670. << Init->getSourceRange();
  3671. }
  3672. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  3673. << 0 << PrevInit->getSourceRange();
  3674. return true;
  3675. }
  3676. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  3677. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  3678. bool CheckRedundantUnionInit(Sema &S,
  3679. CXXCtorInitializer *Init,
  3680. RedundantUnionMap &Unions) {
  3681. FieldDecl *Field = Init->getAnyMember();
  3682. RecordDecl *Parent = Field->getParent();
  3683. NamedDecl *Child = Field;
  3684. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  3685. if (Parent->isUnion()) {
  3686. UnionEntry &En = Unions[Parent];
  3687. if (En.first && En.first != Child) {
  3688. S.Diag(Init->getSourceLocation(),
  3689. diag::err_multiple_mem_union_initialization)
  3690. << Field->getDeclName()
  3691. << Init->getSourceRange();
  3692. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  3693. << 0 << En.second->getSourceRange();
  3694. return true;
  3695. }
  3696. if (!En.first) {
  3697. En.first = Child;
  3698. En.second = Init;
  3699. }
  3700. if (!Parent->isAnonymousStructOrUnion())
  3701. return false;
  3702. }
  3703. Child = Parent;
  3704. Parent = cast<RecordDecl>(Parent->getDeclContext());
  3705. }
  3706. return false;
  3707. }
  3708. }
  3709. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  3710. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  3711. SourceLocation ColonLoc,
  3712. ArrayRef<CXXCtorInitializer*> MemInits,
  3713. bool AnyErrors) {
  3714. if (!ConstructorDecl)
  3715. return;
  3716. AdjustDeclIfTemplate(ConstructorDecl);
  3717. CXXConstructorDecl *Constructor
  3718. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  3719. if (!Constructor) {
  3720. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  3721. return;
  3722. }
  3723. // Mapping for the duplicate initializers check.
  3724. // For member initializers, this is keyed with a FieldDecl*.
  3725. // For base initializers, this is keyed with a Type*.
  3726. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  3727. // Mapping for the inconsistent anonymous-union initializers check.
  3728. RedundantUnionMap MemberUnions;
  3729. bool HadError = false;
  3730. for (unsigned i = 0; i < MemInits.size(); i++) {
  3731. CXXCtorInitializer *Init = MemInits[i];
  3732. // Set the source order index.
  3733. Init->setSourceOrder(i);
  3734. if (Init->isAnyMemberInitializer()) {
  3735. const void *Key = GetKeyForMember(Context, Init);
  3736. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  3737. CheckRedundantUnionInit(*this, Init, MemberUnions))
  3738. HadError = true;
  3739. } else if (Init->isBaseInitializer()) {
  3740. const void *Key = GetKeyForMember(Context, Init);
  3741. if (CheckRedundantInit(*this, Init, Members[Key]))
  3742. HadError = true;
  3743. } else {
  3744. assert(Init->isDelegatingInitializer());
  3745. // This must be the only initializer
  3746. if (MemInits.size() != 1) {
  3747. Diag(Init->getSourceLocation(),
  3748. diag::err_delegating_initializer_alone)
  3749. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  3750. // We will treat this as being the only initializer.
  3751. }
  3752. SetDelegatingInitializer(Constructor, MemInits[i]);
  3753. // Return immediately as the initializer is set.
  3754. return;
  3755. }
  3756. }
  3757. if (HadError)
  3758. return;
  3759. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  3760. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  3761. DiagnoseUninitializedFields(*this, Constructor);
  3762. }
  3763. void
  3764. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  3765. CXXRecordDecl *ClassDecl) {
  3766. // Ignore dependent contexts. Also ignore unions, since their members never
  3767. // have destructors implicitly called.
  3768. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  3769. return;
  3770. // FIXME: all the access-control diagnostics are positioned on the
  3771. // field/base declaration. That's probably good; that said, the
  3772. // user might reasonably want to know why the destructor is being
  3773. // emitted, and we currently don't say.
  3774. // Non-static data members.
  3775. for (auto *Field : ClassDecl->fields()) {
  3776. if (Field->isInvalidDecl())
  3777. continue;
  3778. // Don't destroy incomplete or zero-length arrays.
  3779. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  3780. continue;
  3781. QualType FieldType = Context.getBaseElementType(Field->getType());
  3782. const RecordType* RT = FieldType->getAs<RecordType>();
  3783. if (!RT)
  3784. continue;
  3785. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  3786. if (FieldClassDecl->isInvalidDecl())
  3787. continue;
  3788. if (FieldClassDecl->hasIrrelevantDestructor())
  3789. continue;
  3790. // The destructor for an implicit anonymous union member is never invoked.
  3791. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  3792. continue;
  3793. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  3794. assert(Dtor && "No dtor found for FieldClassDecl!");
  3795. CheckDestructorAccess(Field->getLocation(), Dtor,
  3796. PDiag(diag::err_access_dtor_field)
  3797. << Field->getDeclName()
  3798. << FieldType);
  3799. MarkFunctionReferenced(Location, Dtor);
  3800. DiagnoseUseOfDecl(Dtor, Location);
  3801. }
  3802. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  3803. // Bases.
  3804. for (const auto &Base : ClassDecl->bases()) {
  3805. // Bases are always records in a well-formed non-dependent class.
  3806. const RecordType *RT = Base.getType()->getAs<RecordType>();
  3807. // Remember direct virtual bases.
  3808. if (Base.isVirtual())
  3809. DirectVirtualBases.insert(RT);
  3810. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  3811. // If our base class is invalid, we probably can't get its dtor anyway.
  3812. if (BaseClassDecl->isInvalidDecl())
  3813. continue;
  3814. if (BaseClassDecl->hasIrrelevantDestructor())
  3815. continue;
  3816. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  3817. assert(Dtor && "No dtor found for BaseClassDecl!");
  3818. // FIXME: caret should be on the start of the class name
  3819. CheckDestructorAccess(Base.getLocStart(), Dtor,
  3820. PDiag(diag::err_access_dtor_base)
  3821. << Base.getType()
  3822. << Base.getSourceRange(),
  3823. Context.getTypeDeclType(ClassDecl));
  3824. MarkFunctionReferenced(Location, Dtor);
  3825. DiagnoseUseOfDecl(Dtor, Location);
  3826. }
  3827. // Virtual bases.
  3828. for (const auto &VBase : ClassDecl->vbases()) {
  3829. // Bases are always records in a well-formed non-dependent class.
  3830. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  3831. // Ignore direct virtual bases.
  3832. if (DirectVirtualBases.count(RT))
  3833. continue;
  3834. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  3835. // If our base class is invalid, we probably can't get its dtor anyway.
  3836. if (BaseClassDecl->isInvalidDecl())
  3837. continue;
  3838. if (BaseClassDecl->hasIrrelevantDestructor())
  3839. continue;
  3840. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  3841. assert(Dtor && "No dtor found for BaseClassDecl!");
  3842. if (CheckDestructorAccess(
  3843. ClassDecl->getLocation(), Dtor,
  3844. PDiag(diag::err_access_dtor_vbase)
  3845. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  3846. Context.getTypeDeclType(ClassDecl)) ==
  3847. AR_accessible) {
  3848. CheckDerivedToBaseConversion(
  3849. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  3850. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  3851. SourceRange(), DeclarationName(), nullptr);
  3852. }
  3853. MarkFunctionReferenced(Location, Dtor);
  3854. DiagnoseUseOfDecl(Dtor, Location);
  3855. }
  3856. }
  3857. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  3858. if (!CDtorDecl)
  3859. return;
  3860. if (CXXConstructorDecl *Constructor
  3861. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  3862. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  3863. DiagnoseUninitializedFields(*this, Constructor);
  3864. }
  3865. }
  3866. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  3867. unsigned DiagID, AbstractDiagSelID SelID) {
  3868. class NonAbstractTypeDiagnoser : public TypeDiagnoser {
  3869. unsigned DiagID;
  3870. AbstractDiagSelID SelID;
  3871. public:
  3872. NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
  3873. : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
  3874. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  3875. if (Suppressed) return;
  3876. if (SelID == -1)
  3877. S.Diag(Loc, DiagID) << T;
  3878. else
  3879. S.Diag(Loc, DiagID) << SelID << T;
  3880. }
  3881. } Diagnoser(DiagID, SelID);
  3882. return RequireNonAbstractType(Loc, T, Diagnoser);
  3883. }
  3884. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  3885. TypeDiagnoser &Diagnoser) {
  3886. if (!getLangOpts().CPlusPlus)
  3887. return false;
  3888. if (const ArrayType *AT = Context.getAsArrayType(T))
  3889. return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
  3890. if (const PointerType *PT = T->getAs<PointerType>()) {
  3891. // Find the innermost pointer type.
  3892. while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
  3893. PT = T;
  3894. if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
  3895. return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
  3896. }
  3897. const RecordType *RT = T->getAs<RecordType>();
  3898. if (!RT)
  3899. return false;
  3900. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  3901. // We can't answer whether something is abstract until it has a
  3902. // definition. If it's currently being defined, we'll walk back
  3903. // over all the declarations when we have a full definition.
  3904. const CXXRecordDecl *Def = RD->getDefinition();
  3905. if (!Def || Def->isBeingDefined())
  3906. return false;
  3907. if (!RD->isAbstract())
  3908. return false;
  3909. Diagnoser.diagnose(*this, Loc, T);
  3910. DiagnoseAbstractType(RD);
  3911. return true;
  3912. }
  3913. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  3914. // Check if we've already emitted the list of pure virtual functions
  3915. // for this class.
  3916. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  3917. return;
  3918. // If the diagnostic is suppressed, don't emit the notes. We're only
  3919. // going to emit them once, so try to attach them to a diagnostic we're
  3920. // actually going to show.
  3921. if (Diags.isLastDiagnosticIgnored())
  3922. return;
  3923. CXXFinalOverriderMap FinalOverriders;
  3924. RD->getFinalOverriders(FinalOverriders);
  3925. // Keep a set of seen pure methods so we won't diagnose the same method
  3926. // more than once.
  3927. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  3928. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  3929. MEnd = FinalOverriders.end();
  3930. M != MEnd;
  3931. ++M) {
  3932. for (OverridingMethods::iterator SO = M->second.begin(),
  3933. SOEnd = M->second.end();
  3934. SO != SOEnd; ++SO) {
  3935. // C++ [class.abstract]p4:
  3936. // A class is abstract if it contains or inherits at least one
  3937. // pure virtual function for which the final overrider is pure
  3938. // virtual.
  3939. //
  3940. if (SO->second.size() != 1)
  3941. continue;
  3942. if (!SO->second.front().Method->isPure())
  3943. continue;
  3944. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  3945. continue;
  3946. Diag(SO->second.front().Method->getLocation(),
  3947. diag::note_pure_virtual_function)
  3948. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  3949. }
  3950. }
  3951. if (!PureVirtualClassDiagSet)
  3952. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  3953. PureVirtualClassDiagSet->insert(RD);
  3954. }
  3955. namespace {
  3956. struct AbstractUsageInfo {
  3957. Sema &S;
  3958. CXXRecordDecl *Record;
  3959. CanQualType AbstractType;
  3960. bool Invalid;
  3961. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  3962. : S(S), Record(Record),
  3963. AbstractType(S.Context.getCanonicalType(
  3964. S.Context.getTypeDeclType(Record))),
  3965. Invalid(false) {}
  3966. void DiagnoseAbstractType() {
  3967. if (Invalid) return;
  3968. S.DiagnoseAbstractType(Record);
  3969. Invalid = true;
  3970. }
  3971. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  3972. };
  3973. struct CheckAbstractUsage {
  3974. AbstractUsageInfo &Info;
  3975. const NamedDecl *Ctx;
  3976. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  3977. : Info(Info), Ctx(Ctx) {}
  3978. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3979. switch (TL.getTypeLocClass()) {
  3980. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  3981. #define TYPELOC(CLASS, PARENT) \
  3982. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  3983. #include "clang/AST/TypeLocNodes.def"
  3984. }
  3985. }
  3986. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3987. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  3988. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  3989. if (!TL.getParam(I))
  3990. continue;
  3991. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  3992. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  3993. }
  3994. }
  3995. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3996. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  3997. }
  3998. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3999. // Visit the type parameters from a permissive context.
  4000. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4001. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4002. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4003. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4004. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4005. // TODO: other template argument types?
  4006. }
  4007. }
  4008. // Visit pointee types from a permissive context.
  4009. #define CheckPolymorphic(Type) \
  4010. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4011. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4012. }
  4013. CheckPolymorphic(PointerTypeLoc)
  4014. CheckPolymorphic(ReferenceTypeLoc)
  4015. CheckPolymorphic(MemberPointerTypeLoc)
  4016. CheckPolymorphic(BlockPointerTypeLoc)
  4017. CheckPolymorphic(AtomicTypeLoc)
  4018. /// Handle all the types we haven't given a more specific
  4019. /// implementation for above.
  4020. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4021. // Every other kind of type that we haven't called out already
  4022. // that has an inner type is either (1) sugar or (2) contains that
  4023. // inner type in some way as a subobject.
  4024. if (TypeLoc Next = TL.getNextTypeLoc())
  4025. return Visit(Next, Sel);
  4026. // If there's no inner type and we're in a permissive context,
  4027. // don't diagnose.
  4028. if (Sel == Sema::AbstractNone) return;
  4029. // Check whether the type matches the abstract type.
  4030. QualType T = TL.getType();
  4031. if (T->isArrayType()) {
  4032. Sel = Sema::AbstractArrayType;
  4033. T = Info.S.Context.getBaseElementType(T);
  4034. }
  4035. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4036. if (CT != Info.AbstractType) return;
  4037. // It matched; do some magic.
  4038. if (Sel == Sema::AbstractArrayType) {
  4039. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4040. << T << TL.getSourceRange();
  4041. } else {
  4042. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4043. << Sel << T << TL.getSourceRange();
  4044. }
  4045. Info.DiagnoseAbstractType();
  4046. }
  4047. };
  4048. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4049. Sema::AbstractDiagSelID Sel) {
  4050. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4051. }
  4052. }
  4053. /// Check for invalid uses of an abstract type in a method declaration.
  4054. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4055. CXXMethodDecl *MD) {
  4056. // No need to do the check on definitions, which require that
  4057. // the return/param types be complete.
  4058. if (MD->doesThisDeclarationHaveABody())
  4059. return;
  4060. // For safety's sake, just ignore it if we don't have type source
  4061. // information. This should never happen for non-implicit methods,
  4062. // but...
  4063. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4064. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4065. }
  4066. /// Check for invalid uses of an abstract type within a class definition.
  4067. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4068. CXXRecordDecl *RD) {
  4069. for (auto *D : RD->decls()) {
  4070. if (D->isImplicit()) continue;
  4071. // Methods and method templates.
  4072. if (isa<CXXMethodDecl>(D)) {
  4073. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4074. } else if (isa<FunctionTemplateDecl>(D)) {
  4075. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4076. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4077. // Fields and static variables.
  4078. } else if (isa<FieldDecl>(D)) {
  4079. FieldDecl *FD = cast<FieldDecl>(D);
  4080. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  4081. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  4082. } else if (isa<VarDecl>(D)) {
  4083. VarDecl *VD = cast<VarDecl>(D);
  4084. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  4085. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  4086. // Nested classes and class templates.
  4087. } else if (isa<CXXRecordDecl>(D)) {
  4088. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  4089. } else if (isa<ClassTemplateDecl>(D)) {
  4090. CheckAbstractClassUsage(Info,
  4091. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  4092. }
  4093. }
  4094. }
  4095. /// \brief Check class-level dllimport/dllexport attribute.
  4096. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  4097. Attr *ClassAttr = getDLLAttr(Class);
  4098. // MSVC inherits DLL attributes to partial class template specializations.
  4099. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  4100. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  4101. if (Attr *TemplateAttr =
  4102. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  4103. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  4104. A->setInherited(true);
  4105. ClassAttr = A;
  4106. }
  4107. }
  4108. }
  4109. if (!ClassAttr)
  4110. return;
  4111. if (!Class->isExternallyVisible()) {
  4112. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  4113. << Class << ClassAttr;
  4114. return;
  4115. }
  4116. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4117. !ClassAttr->isInherited()) {
  4118. // Diagnose dll attributes on members of class with dll attribute.
  4119. for (Decl *Member : Class->decls()) {
  4120. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  4121. continue;
  4122. InheritableAttr *MemberAttr = getDLLAttr(Member);
  4123. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  4124. continue;
  4125. Diag(MemberAttr->getLocation(),
  4126. diag::err_attribute_dll_member_of_dll_class)
  4127. << MemberAttr << ClassAttr;
  4128. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  4129. Member->setInvalidDecl();
  4130. }
  4131. }
  4132. if (Class->getDescribedClassTemplate())
  4133. // Don't inherit dll attribute until the template is instantiated.
  4134. return;
  4135. // The class is either imported or exported.
  4136. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  4137. const bool ClassImported = !ClassExported;
  4138. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4139. // Ignore explicit dllexport on explicit class template instantiation declarations.
  4140. if (ClassExported && !ClassAttr->isInherited() &&
  4141. TSK == TSK_ExplicitInstantiationDeclaration) {
  4142. Class->dropAttr<DLLExportAttr>();
  4143. return;
  4144. }
  4145. // Force declaration of implicit members so they can inherit the attribute.
  4146. ForceDeclarationOfImplicitMembers(Class);
  4147. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  4148. // seem to be true in practice?
  4149. for (Decl *Member : Class->decls()) {
  4150. VarDecl *VD = dyn_cast<VarDecl>(Member);
  4151. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  4152. // Only methods and static fields inherit the attributes.
  4153. if (!VD && !MD)
  4154. continue;
  4155. if (MD) {
  4156. // Don't process deleted methods.
  4157. if (MD->isDeleted())
  4158. continue;
  4159. if (MD->isInlined()) {
  4160. // MinGW does not import or export inline methods.
  4161. if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
  4162. continue;
  4163. // MSVC versions before 2015 don't export the move assignment operators,
  4164. // so don't attempt to import them if we have a definition.
  4165. if (ClassImported && MD->isMoveAssignmentOperator() &&
  4166. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  4167. continue;
  4168. }
  4169. }
  4170. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  4171. continue;
  4172. if (!getDLLAttr(Member)) {
  4173. auto *NewAttr =
  4174. cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4175. NewAttr->setInherited(true);
  4176. Member->addAttr(NewAttr);
  4177. }
  4178. if (MD && ClassExported) {
  4179. if (TSK == TSK_ExplicitInstantiationDeclaration)
  4180. // Don't go any further if this is just an explicit instantiation
  4181. // declaration.
  4182. continue;
  4183. if (MD->isUserProvided()) {
  4184. // Instantiate non-default class member functions ...
  4185. // .. except for certain kinds of template specializations.
  4186. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  4187. continue;
  4188. MarkFunctionReferenced(Class->getLocation(), MD);
  4189. // The function will be passed to the consumer when its definition is
  4190. // encountered.
  4191. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  4192. MD->isCopyAssignmentOperator() ||
  4193. MD->isMoveAssignmentOperator()) {
  4194. // Synthesize and instantiate non-trivial implicit methods, explicitly
  4195. // defaulted methods, and the copy and move assignment operators. The
  4196. // latter are exported even if they are trivial, because the address of
  4197. // an operator can be taken and should compare equal accross libraries.
  4198. DiagnosticErrorTrap Trap(Diags);
  4199. MarkFunctionReferenced(Class->getLocation(), MD);
  4200. if (Trap.hasErrorOccurred()) {
  4201. Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  4202. << Class->getName() << !getLangOpts().CPlusPlus11;
  4203. break;
  4204. }
  4205. // There is no later point when we will see the definition of this
  4206. // function, so pass it to the consumer now.
  4207. Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  4208. }
  4209. }
  4210. }
  4211. }
  4212. /// \brief Perform propagation of DLL attributes from a derived class to a
  4213. /// templated base class for MS compatibility.
  4214. void Sema::propagateDLLAttrToBaseClassTemplate(
  4215. CXXRecordDecl *Class, Attr *ClassAttr,
  4216. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  4217. if (getDLLAttr(
  4218. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  4219. // If the base class template has a DLL attribute, don't try to change it.
  4220. return;
  4221. }
  4222. auto TSK = BaseTemplateSpec->getSpecializationKind();
  4223. if (!getDLLAttr(BaseTemplateSpec) &&
  4224. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  4225. TSK == TSK_ImplicitInstantiation)) {
  4226. // The template hasn't been instantiated yet (or it has, but only as an
  4227. // explicit instantiation declaration or implicit instantiation, which means
  4228. // we haven't codegenned any members yet), so propagate the attribute.
  4229. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4230. NewAttr->setInherited(true);
  4231. BaseTemplateSpec->addAttr(NewAttr);
  4232. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  4233. // needs to be run again to work see the new attribute. Otherwise this will
  4234. // get run whenever the template is instantiated.
  4235. if (TSK != TSK_Undeclared)
  4236. checkClassLevelDLLAttribute(BaseTemplateSpec);
  4237. return;
  4238. }
  4239. if (getDLLAttr(BaseTemplateSpec)) {
  4240. // The template has already been specialized or instantiated with an
  4241. // attribute, explicitly or through propagation. We should not try to change
  4242. // it.
  4243. return;
  4244. }
  4245. // The template was previously instantiated or explicitly specialized without
  4246. // a dll attribute, It's too late for us to add an attribute, so warn that
  4247. // this is unsupported.
  4248. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  4249. << BaseTemplateSpec->isExplicitSpecialization();
  4250. Diag(ClassAttr->getLocation(), diag::note_attribute);
  4251. if (BaseTemplateSpec->isExplicitSpecialization()) {
  4252. Diag(BaseTemplateSpec->getLocation(),
  4253. diag::note_template_class_explicit_specialization_was_here)
  4254. << BaseTemplateSpec;
  4255. } else {
  4256. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  4257. diag::note_template_class_instantiation_was_here)
  4258. << BaseTemplateSpec;
  4259. }
  4260. }
  4261. /// \brief Perform semantic checks on a class definition that has been
  4262. /// completing, introducing implicitly-declared members, checking for
  4263. /// abstract types, etc.
  4264. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  4265. if (!Record)
  4266. return;
  4267. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  4268. AbstractUsageInfo Info(*this, Record);
  4269. CheckAbstractClassUsage(Info, Record);
  4270. }
  4271. // If this is not an aggregate type and has no user-declared constructor,
  4272. // complain about any non-static data members of reference or const scalar
  4273. // type, since they will never get initializers.
  4274. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  4275. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  4276. !Record->isLambda()) {
  4277. bool Complained = false;
  4278. for (const auto *F : Record->fields()) {
  4279. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  4280. continue;
  4281. if (F->getType()->isReferenceType() ||
  4282. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  4283. if (!Complained) {
  4284. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  4285. << Record->getTagKind() << Record;
  4286. Complained = true;
  4287. }
  4288. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  4289. << F->getType()->isReferenceType()
  4290. << F->getDeclName();
  4291. }
  4292. }
  4293. }
  4294. if (Record->getIdentifier()) {
  4295. // C++ [class.mem]p13:
  4296. // If T is the name of a class, then each of the following shall have a
  4297. // name different from T:
  4298. // - every member of every anonymous union that is a member of class T.
  4299. //
  4300. // C++ [class.mem]p14:
  4301. // In addition, if class T has a user-declared constructor (12.1), every
  4302. // non-static data member of class T shall have a name different from T.
  4303. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  4304. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  4305. ++I) {
  4306. NamedDecl *D = *I;
  4307. if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
  4308. isa<IndirectFieldDecl>(D)) {
  4309. Diag(D->getLocation(), diag::err_member_name_of_class)
  4310. << D->getDeclName();
  4311. break;
  4312. }
  4313. }
  4314. }
  4315. // Warn if the class has virtual methods but non-virtual public destructor.
  4316. if (Record->isPolymorphic() && !Record->isDependentType()) {
  4317. CXXDestructorDecl *dtor = Record->getDestructor();
  4318. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  4319. !Record->hasAttr<FinalAttr>())
  4320. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  4321. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  4322. }
  4323. if (Record->isAbstract()) {
  4324. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  4325. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  4326. << FA->isSpelledAsSealed();
  4327. DiagnoseAbstractType(Record);
  4328. }
  4329. }
  4330. bool HasMethodWithOverrideControl = false,
  4331. HasOverridingMethodWithoutOverrideControl = false;
  4332. if (!Record->isDependentType()) {
  4333. for (auto *M : Record->methods()) {
  4334. // See if a method overloads virtual methods in a base
  4335. // class without overriding any.
  4336. if (!M->isStatic())
  4337. DiagnoseHiddenVirtualMethods(M);
  4338. if (M->hasAttr<OverrideAttr>())
  4339. HasMethodWithOverrideControl = true;
  4340. else if (M->size_overridden_methods() > 0)
  4341. HasOverridingMethodWithoutOverrideControl = true;
  4342. // Check whether the explicitly-defaulted special members are valid.
  4343. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  4344. CheckExplicitlyDefaultedSpecialMember(M);
  4345. // For an explicitly defaulted or deleted special member, we defer
  4346. // determining triviality until the class is complete. That time is now!
  4347. if (!M->isImplicit() && !M->isUserProvided()) {
  4348. CXXSpecialMember CSM = getSpecialMember(M);
  4349. if (CSM != CXXInvalid) {
  4350. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  4351. // Inform the class that we've finished declaring this member.
  4352. Record->finishedDefaultedOrDeletedMember(M);
  4353. }
  4354. }
  4355. }
  4356. }
  4357. if (HasMethodWithOverrideControl &&
  4358. HasOverridingMethodWithoutOverrideControl) {
  4359. // At least one method has the 'override' control declared.
  4360. // Diagnose all other overridden methods which do not have 'override' specified on them.
  4361. for (auto *M : Record->methods())
  4362. DiagnoseAbsenceOfOverrideControl(M);
  4363. }
  4364. // ms_struct is a request to use the same ABI rules as MSVC. Check
  4365. // whether this class uses any C++ features that are implemented
  4366. // completely differently in MSVC, and if so, emit a diagnostic.
  4367. // That diagnostic defaults to an error, but we allow projects to
  4368. // map it down to a warning (or ignore it). It's a fairly common
  4369. // practice among users of the ms_struct pragma to mass-annotate
  4370. // headers, sweeping up a bunch of types that the project doesn't
  4371. // really rely on MSVC-compatible layout for. We must therefore
  4372. // support "ms_struct except for C++ stuff" as a secondary ABI.
  4373. if (Record->isMsStruct(Context) &&
  4374. (Record->isPolymorphic() || Record->getNumBases())) {
  4375. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  4376. }
  4377. // Declare inheriting constructors. We do this eagerly here because:
  4378. // - The standard requires an eager diagnostic for conflicting inheriting
  4379. // constructors from different classes.
  4380. // - The lazy declaration of the other implicit constructors is so as to not
  4381. // waste space and performance on classes that are not meant to be
  4382. // instantiated (e.g. meta-functions). This doesn't apply to classes that
  4383. // have inheriting constructors.
  4384. DeclareInheritingConstructors(Record);
  4385. checkClassLevelDLLAttribute(Record);
  4386. }
  4387. /// Look up the special member function that would be called by a special
  4388. /// member function for a subobject of class type.
  4389. ///
  4390. /// \param Class The class type of the subobject.
  4391. /// \param CSM The kind of special member function.
  4392. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  4393. /// \param ConstRHS True if this is a copy operation with a const object
  4394. /// on its RHS, that is, if the argument to the outer special member
  4395. /// function is 'const' and this is not a field marked 'mutable'.
  4396. static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
  4397. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  4398. unsigned FieldQuals, bool ConstRHS) {
  4399. unsigned LHSQuals = 0;
  4400. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  4401. LHSQuals = FieldQuals;
  4402. unsigned RHSQuals = FieldQuals;
  4403. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  4404. RHSQuals = 0;
  4405. else if (ConstRHS)
  4406. RHSQuals |= Qualifiers::Const;
  4407. return S.LookupSpecialMember(Class, CSM,
  4408. RHSQuals & Qualifiers::Const,
  4409. RHSQuals & Qualifiers::Volatile,
  4410. false,
  4411. LHSQuals & Qualifiers::Const,
  4412. LHSQuals & Qualifiers::Volatile);
  4413. }
  4414. /// Is the special member function which would be selected to perform the
  4415. /// specified operation on the specified class type a constexpr constructor?
  4416. static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  4417. Sema::CXXSpecialMember CSM,
  4418. unsigned Quals, bool ConstRHS) {
  4419. Sema::SpecialMemberOverloadResult *SMOR =
  4420. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  4421. if (!SMOR || !SMOR->getMethod())
  4422. // A constructor we wouldn't select can't be "involved in initializing"
  4423. // anything.
  4424. return true;
  4425. return SMOR->getMethod()->isConstexpr();
  4426. }
  4427. /// Determine whether the specified special member function would be constexpr
  4428. /// if it were implicitly defined.
  4429. static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  4430. Sema::CXXSpecialMember CSM,
  4431. bool ConstArg) {
  4432. if (!S.getLangOpts().CPlusPlus11)
  4433. return false;
  4434. // C++11 [dcl.constexpr]p4:
  4435. // In the definition of a constexpr constructor [...]
  4436. bool Ctor = true;
  4437. switch (CSM) {
  4438. case Sema::CXXDefaultConstructor:
  4439. // Since default constructor lookup is essentially trivial (and cannot
  4440. // involve, for instance, template instantiation), we compute whether a
  4441. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  4442. //
  4443. // This is important for performance; we need to know whether the default
  4444. // constructor is constexpr to determine whether the type is a literal type.
  4445. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  4446. case Sema::CXXCopyConstructor:
  4447. case Sema::CXXMoveConstructor:
  4448. // For copy or move constructors, we need to perform overload resolution.
  4449. break;
  4450. case Sema::CXXCopyAssignment:
  4451. case Sema::CXXMoveAssignment:
  4452. if (!S.getLangOpts().CPlusPlus14)
  4453. return false;
  4454. // In C++1y, we need to perform overload resolution.
  4455. Ctor = false;
  4456. break;
  4457. case Sema::CXXDestructor:
  4458. case Sema::CXXInvalid:
  4459. return false;
  4460. }
  4461. // -- if the class is a non-empty union, or for each non-empty anonymous
  4462. // union member of a non-union class, exactly one non-static data member
  4463. // shall be initialized; [DR1359]
  4464. //
  4465. // If we squint, this is guaranteed, since exactly one non-static data member
  4466. // will be initialized (if the constructor isn't deleted), we just don't know
  4467. // which one.
  4468. if (Ctor && ClassDecl->isUnion())
  4469. return true;
  4470. // -- the class shall not have any virtual base classes;
  4471. if (Ctor && ClassDecl->getNumVBases())
  4472. return false;
  4473. // C++1y [class.copy]p26:
  4474. // -- [the class] is a literal type, and
  4475. if (!Ctor && !ClassDecl->isLiteral())
  4476. return false;
  4477. // -- every constructor involved in initializing [...] base class
  4478. // sub-objects shall be a constexpr constructor;
  4479. // -- the assignment operator selected to copy/move each direct base
  4480. // class is a constexpr function, and
  4481. for (const auto &B : ClassDecl->bases()) {
  4482. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  4483. if (!BaseType) continue;
  4484. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  4485. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
  4486. return false;
  4487. }
  4488. // -- every constructor involved in initializing non-static data members
  4489. // [...] shall be a constexpr constructor;
  4490. // -- every non-static data member and base class sub-object shall be
  4491. // initialized
  4492. // -- for each non-static data member of X that is of class type (or array
  4493. // thereof), the assignment operator selected to copy/move that member is
  4494. // a constexpr function
  4495. for (const auto *F : ClassDecl->fields()) {
  4496. if (F->isInvalidDecl())
  4497. continue;
  4498. QualType BaseType = S.Context.getBaseElementType(F->getType());
  4499. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  4500. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  4501. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  4502. BaseType.getCVRQualifiers(),
  4503. ConstArg && !F->isMutable()))
  4504. return false;
  4505. }
  4506. }
  4507. // All OK, it's constexpr!
  4508. return true;
  4509. }
  4510. static Sema::ImplicitExceptionSpecification
  4511. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  4512. switch (S.getSpecialMember(MD)) {
  4513. case Sema::CXXDefaultConstructor:
  4514. return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
  4515. case Sema::CXXCopyConstructor:
  4516. return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
  4517. case Sema::CXXCopyAssignment:
  4518. return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
  4519. case Sema::CXXMoveConstructor:
  4520. return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
  4521. case Sema::CXXMoveAssignment:
  4522. return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
  4523. case Sema::CXXDestructor:
  4524. return S.ComputeDefaultedDtorExceptionSpec(MD);
  4525. case Sema::CXXInvalid:
  4526. break;
  4527. }
  4528. assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
  4529. "only special members have implicit exception specs");
  4530. return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
  4531. }
  4532. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  4533. CXXMethodDecl *MD) {
  4534. FunctionProtoType::ExtProtoInfo EPI;
  4535. // Build an exception specification pointing back at this member.
  4536. EPI.ExceptionSpec.Type = EST_BasicNoexcept; // HLSL Change - EST_Unevaluated to EST_BasicNoexcept
  4537. EPI.ExceptionSpec.SourceDecl = MD;
  4538. // Set the calling convention to the default for C++ instance methods.
  4539. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  4540. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  4541. /*IsCXXMethod=*/true));
  4542. return EPI;
  4543. }
  4544. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  4545. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  4546. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  4547. return;
  4548. // Evaluate the exception specification.
  4549. auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
  4550. // Update the type of the special member to use it.
  4551. UpdateExceptionSpec(MD, ESI);
  4552. // A user-provided destructor can be defined outside the class. When that
  4553. // happens, be sure to update the exception specification on both
  4554. // declarations.
  4555. const FunctionProtoType *CanonicalFPT =
  4556. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  4557. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  4558. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  4559. }
  4560. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  4561. CXXRecordDecl *RD = MD->getParent();
  4562. CXXSpecialMember CSM = getSpecialMember(MD);
  4563. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  4564. "not an explicitly-defaulted special member");
  4565. // Whether this was the first-declared instance of the constructor.
  4566. // This affects whether we implicitly add an exception spec and constexpr.
  4567. bool First = MD == MD->getCanonicalDecl();
  4568. bool HadError = false;
  4569. // C++11 [dcl.fct.def.default]p1:
  4570. // A function that is explicitly defaulted shall
  4571. // -- be a special member function (checked elsewhere),
  4572. // -- have the same type (except for ref-qualifiers, and except that a
  4573. // copy operation can take a non-const reference) as an implicit
  4574. // declaration, and
  4575. // -- not have default arguments.
  4576. unsigned ExpectedParams = 1;
  4577. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  4578. ExpectedParams = 0;
  4579. if (MD->getNumParams() != ExpectedParams) {
  4580. // This also checks for default arguments: a copy or move constructor with a
  4581. // default argument is classified as a default constructor, and assignment
  4582. // operations and destructors can't have default arguments.
  4583. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  4584. << CSM << MD->getSourceRange();
  4585. HadError = true;
  4586. } else if (MD->isVariadic()) {
  4587. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  4588. << CSM << MD->getSourceRange();
  4589. HadError = true;
  4590. }
  4591. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  4592. bool CanHaveConstParam = false;
  4593. if (CSM == CXXCopyConstructor)
  4594. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  4595. else if (CSM == CXXCopyAssignment)
  4596. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  4597. QualType ReturnType = Context.VoidTy;
  4598. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  4599. // Check for return type matching.
  4600. ReturnType = Type->getReturnType();
  4601. QualType ExpectedReturnType =
  4602. Context.getLValueReferenceType(Context.getTypeDeclType(RD));
  4603. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  4604. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  4605. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  4606. HadError = true;
  4607. }
  4608. // A defaulted special member cannot have cv-qualifiers.
  4609. if (Type->getTypeQuals()) {
  4610. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  4611. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  4612. HadError = true;
  4613. }
  4614. }
  4615. // Check for parameter type matching.
  4616. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  4617. bool HasConstParam = false;
  4618. if (ExpectedParams && ArgType->isReferenceType()) {
  4619. // Argument must be reference to possibly-const T.
  4620. QualType ReferentType = ArgType->getPointeeType();
  4621. HasConstParam = ReferentType.isConstQualified();
  4622. if (ReferentType.isVolatileQualified()) {
  4623. Diag(MD->getLocation(),
  4624. diag::err_defaulted_special_member_volatile_param) << CSM;
  4625. HadError = true;
  4626. }
  4627. if (HasConstParam && !CanHaveConstParam) {
  4628. if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  4629. Diag(MD->getLocation(),
  4630. diag::err_defaulted_special_member_copy_const_param)
  4631. << (CSM == CXXCopyAssignment);
  4632. // FIXME: Explain why this special member can't be const.
  4633. } else {
  4634. Diag(MD->getLocation(),
  4635. diag::err_defaulted_special_member_move_const_param)
  4636. << (CSM == CXXMoveAssignment);
  4637. }
  4638. HadError = true;
  4639. }
  4640. } else if (ExpectedParams) {
  4641. // A copy assignment operator can take its argument by value, but a
  4642. // defaulted one cannot.
  4643. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  4644. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  4645. HadError = true;
  4646. }
  4647. // C++11 [dcl.fct.def.default]p2:
  4648. // An explicitly-defaulted function may be declared constexpr only if it
  4649. // would have been implicitly declared as constexpr,
  4650. // Do not apply this rule to members of class templates, since core issue 1358
  4651. // makes such functions always instantiate to constexpr functions. For
  4652. // functions which cannot be constexpr (for non-constructors in C++11 and for
  4653. // destructors in C++1y), this is checked elsewhere.
  4654. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  4655. HasConstParam);
  4656. if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  4657. : isa<CXXConstructorDecl>(MD)) &&
  4658. MD->isConstexpr() && !Constexpr &&
  4659. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  4660. Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
  4661. // FIXME: Explain why the special member can't be constexpr.
  4662. HadError = true;
  4663. }
  4664. // and may have an explicit exception-specification only if it is compatible
  4665. // with the exception-specification on the implicit declaration.
  4666. if (Type->hasExceptionSpec()) {
  4667. // Delay the check if this is the first declaration of the special member,
  4668. // since we may not have parsed some necessary in-class initializers yet.
  4669. if (First) {
  4670. // If the exception specification needs to be instantiated, do so now,
  4671. // before we clobber it with an EST_Unevaluated specification below.
  4672. if (Type->getExceptionSpecType() == EST_Uninstantiated) {
  4673. InstantiateExceptionSpec(MD->getLocStart(), MD);
  4674. Type = MD->getType()->getAs<FunctionProtoType>();
  4675. }
  4676. DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
  4677. } else
  4678. CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
  4679. }
  4680. // If a function is explicitly defaulted on its first declaration,
  4681. if (First) {
  4682. // -- it is implicitly considered to be constexpr if the implicit
  4683. // definition would be,
  4684. MD->setConstexpr(Constexpr);
  4685. // -- it is implicitly considered to have the same exception-specification
  4686. // as if it had been implicitly declared,
  4687. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  4688. EPI.ExceptionSpec.Type = EST_Unevaluated;
  4689. EPI.ExceptionSpec.SourceDecl = MD;
  4690. MD->setType(Context.getFunctionType(ReturnType,
  4691. llvm::makeArrayRef(&ArgType,
  4692. ExpectedParams),
  4693. EPI, None)); // HLSL Change - special members are all-in params
  4694. }
  4695. if (ShouldDeleteSpecialMember(MD, CSM)) {
  4696. if (First) {
  4697. SetDeclDeleted(MD, MD->getLocation());
  4698. } else {
  4699. // C++11 [dcl.fct.def.default]p4:
  4700. // [For a] user-provided explicitly-defaulted function [...] if such a
  4701. // function is implicitly defined as deleted, the program is ill-formed.
  4702. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  4703. ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
  4704. HadError = true;
  4705. }
  4706. }
  4707. if (HadError)
  4708. MD->setInvalidDecl();
  4709. }
  4710. /// Check whether the exception specification provided for an
  4711. /// explicitly-defaulted special member matches the exception specification
  4712. /// that would have been generated for an implicit special member, per
  4713. /// C++11 [dcl.fct.def.default]p2.
  4714. void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
  4715. CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
  4716. // If the exception specification was explicitly specified but hadn't been
  4717. // parsed when the method was defaulted, grab it now.
  4718. if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
  4719. SpecifiedType =
  4720. MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
  4721. // Compute the implicit exception specification.
  4722. CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  4723. /*IsCXXMethod=*/true);
  4724. FunctionProtoType::ExtProtoInfo EPI(CC);
  4725. EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
  4726. .getExceptionSpec();
  4727. const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
  4728. Context.getFunctionType(Context.VoidTy, None, EPI, None)); // HLSL Change - special members are all-in params
  4729. // Ensure that it matches.
  4730. CheckEquivalentExceptionSpec(
  4731. PDiag(diag::err_incorrect_defaulted_exception_spec)
  4732. << getSpecialMember(MD), PDiag(),
  4733. ImplicitType, SourceLocation(),
  4734. SpecifiedType, MD->getLocation());
  4735. }
  4736. void Sema::CheckDelayedMemberExceptionSpecs() {
  4737. decltype(DelayedExceptionSpecChecks) Checks;
  4738. decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
  4739. std::swap(Checks, DelayedExceptionSpecChecks);
  4740. std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
  4741. // Perform any deferred checking of exception specifications for virtual
  4742. // destructors.
  4743. for (auto &Check : Checks)
  4744. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  4745. // Check that any explicitly-defaulted methods have exception specifications
  4746. // compatible with their implicit exception specifications.
  4747. for (auto &Spec : Specs)
  4748. CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
  4749. }
  4750. namespace {
  4751. struct SpecialMemberDeletionInfo {
  4752. Sema &S;
  4753. CXXMethodDecl *MD;
  4754. Sema::CXXSpecialMember CSM;
  4755. bool Diagnose;
  4756. // Properties of the special member, computed for convenience.
  4757. bool IsConstructor, IsAssignment, IsMove, ConstArg;
  4758. SourceLocation Loc;
  4759. bool AllFieldsAreConst;
  4760. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  4761. Sema::CXXSpecialMember CSM, bool Diagnose)
  4762. : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
  4763. IsConstructor(false), IsAssignment(false), IsMove(false),
  4764. ConstArg(false), Loc(MD->getLocation()),
  4765. AllFieldsAreConst(true) {
  4766. switch (CSM) {
  4767. case Sema::CXXDefaultConstructor:
  4768. case Sema::CXXCopyConstructor:
  4769. IsConstructor = true;
  4770. break;
  4771. case Sema::CXXMoveConstructor:
  4772. IsConstructor = true;
  4773. IsMove = true;
  4774. break;
  4775. case Sema::CXXCopyAssignment:
  4776. IsAssignment = true;
  4777. break;
  4778. case Sema::CXXMoveAssignment:
  4779. IsAssignment = true;
  4780. IsMove = true;
  4781. break;
  4782. case Sema::CXXDestructor:
  4783. break;
  4784. case Sema::CXXInvalid:
  4785. llvm_unreachable("invalid special member kind");
  4786. }
  4787. if (MD->getNumParams()) {
  4788. if (const ReferenceType *RT =
  4789. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  4790. ConstArg = RT->getPointeeType().isConstQualified();
  4791. }
  4792. }
  4793. bool inUnion() const { return MD->getParent()->isUnion(); }
  4794. /// Look up the corresponding special member in the given class.
  4795. Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
  4796. unsigned Quals, bool IsMutable) {
  4797. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  4798. ConstArg && !IsMutable);
  4799. }
  4800. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  4801. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  4802. bool shouldDeleteForField(FieldDecl *FD);
  4803. bool shouldDeleteForAllConstMembers();
  4804. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  4805. unsigned Quals);
  4806. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  4807. Sema::SpecialMemberOverloadResult *SMOR,
  4808. bool IsDtorCallInCtor);
  4809. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  4810. };
  4811. }
  4812. /// Is the given special member inaccessible when used on the given
  4813. /// sub-object.
  4814. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  4815. CXXMethodDecl *target) {
  4816. /// If we're operating on a base class, the object type is the
  4817. /// type of this special member.
  4818. QualType objectTy;
  4819. AccessSpecifier access = target->getAccess();
  4820. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  4821. objectTy = S.Context.getTypeDeclType(MD->getParent());
  4822. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  4823. // If we're operating on a field, the object type is the type of the field.
  4824. } else {
  4825. objectTy = S.Context.getTypeDeclType(target->getParent());
  4826. }
  4827. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  4828. }
  4829. /// Check whether we should delete a special member due to the implicit
  4830. /// definition containing a call to a special member of a subobject.
  4831. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  4832. Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
  4833. bool IsDtorCallInCtor) {
  4834. CXXMethodDecl *Decl = SMOR->getMethod();
  4835. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  4836. int DiagKind = -1;
  4837. if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  4838. DiagKind = !Decl ? 0 : 1;
  4839. else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  4840. DiagKind = 2;
  4841. else if (!isAccessible(Subobj, Decl))
  4842. DiagKind = 3;
  4843. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  4844. !Decl->isTrivial()) {
  4845. // A member of a union must have a trivial corresponding special member.
  4846. // As a weird special case, a destructor call from a union's constructor
  4847. // must be accessible and non-deleted, but need not be trivial. Such a
  4848. // destructor is never actually called, but is semantically checked as
  4849. // if it were.
  4850. DiagKind = 4;
  4851. }
  4852. if (DiagKind == -1)
  4853. return false;
  4854. if (Diagnose) {
  4855. if (Field) {
  4856. S.Diag(Field->getLocation(),
  4857. diag::note_deleted_special_member_class_subobject)
  4858. << CSM << MD->getParent() << /*IsField*/true
  4859. << Field << DiagKind << IsDtorCallInCtor;
  4860. } else {
  4861. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  4862. S.Diag(Base->getLocStart(),
  4863. diag::note_deleted_special_member_class_subobject)
  4864. << CSM << MD->getParent() << /*IsField*/false
  4865. << Base->getType() << DiagKind << IsDtorCallInCtor;
  4866. }
  4867. if (DiagKind == 1)
  4868. S.NoteDeletedFunction(Decl);
  4869. // FIXME: Explain inaccessibility if DiagKind == 3.
  4870. }
  4871. return true;
  4872. }
  4873. /// Check whether we should delete a special member function due to having a
  4874. /// direct or virtual base class or non-static data member of class type M.
  4875. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  4876. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  4877. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  4878. bool IsMutable = Field && Field->isMutable();
  4879. // C++11 [class.ctor]p5:
  4880. // -- any direct or virtual base class, or non-static data member with no
  4881. // brace-or-equal-initializer, has class type M (or array thereof) and
  4882. // either M has no default constructor or overload resolution as applied
  4883. // to M's default constructor results in an ambiguity or in a function
  4884. // that is deleted or inaccessible
  4885. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  4886. // -- a direct or virtual base class B that cannot be copied/moved because
  4887. // overload resolution, as applied to B's corresponding special member,
  4888. // results in an ambiguity or a function that is deleted or inaccessible
  4889. // from the defaulted special member
  4890. // C++11 [class.dtor]p5:
  4891. // -- any direct or virtual base class [...] has a type with a destructor
  4892. // that is deleted or inaccessible
  4893. if (!(CSM == Sema::CXXDefaultConstructor &&
  4894. Field && Field->hasInClassInitializer()) &&
  4895. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  4896. false))
  4897. return true;
  4898. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  4899. // -- any direct or virtual base class or non-static data member has a
  4900. // type with a destructor that is deleted or inaccessible
  4901. if (IsConstructor) {
  4902. Sema::SpecialMemberOverloadResult *SMOR =
  4903. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  4904. false, false, false, false, false);
  4905. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  4906. return true;
  4907. }
  4908. return false;
  4909. }
  4910. /// Check whether we should delete a special member function due to the class
  4911. /// having a particular direct or virtual base class.
  4912. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  4913. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  4914. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  4915. }
  4916. /// Check whether we should delete a special member function due to the class
  4917. /// having a particular non-static data member.
  4918. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  4919. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  4920. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  4921. if (CSM == Sema::CXXDefaultConstructor) {
  4922. // For a default constructor, all references must be initialized in-class
  4923. // and, if a union, it must have a non-const member.
  4924. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  4925. if (Diagnose)
  4926. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  4927. << MD->getParent() << FD << FieldType << /*Reference*/0;
  4928. return true;
  4929. }
  4930. // C++11 [class.ctor]p5: any non-variant non-static data member of
  4931. // const-qualified type (or array thereof) with no
  4932. // brace-or-equal-initializer does not have a user-provided default
  4933. // constructor.
  4934. if (!inUnion() && FieldType.isConstQualified() &&
  4935. !FD->hasInClassInitializer() &&
  4936. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  4937. if (Diagnose)
  4938. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  4939. << MD->getParent() << FD << FD->getType() << /*Const*/1;
  4940. return true;
  4941. }
  4942. if (inUnion() && !FieldType.isConstQualified())
  4943. AllFieldsAreConst = false;
  4944. } else if (CSM == Sema::CXXCopyConstructor) {
  4945. // For a copy constructor, data members must not be of rvalue reference
  4946. // type.
  4947. if (FieldType->isRValueReferenceType()) {
  4948. if (Diagnose)
  4949. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  4950. << MD->getParent() << FD << FieldType;
  4951. return true;
  4952. }
  4953. } else if (IsAssignment) {
  4954. // For an assignment operator, data members must not be of reference type.
  4955. if (FieldType->isReferenceType()) {
  4956. if (Diagnose)
  4957. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  4958. << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
  4959. return true;
  4960. }
  4961. if (!FieldRecord && FieldType.isConstQualified()) {
  4962. // C++11 [class.copy]p23:
  4963. // -- a non-static data member of const non-class type (or array thereof)
  4964. if (Diagnose)
  4965. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  4966. << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
  4967. return true;
  4968. }
  4969. }
  4970. if (FieldRecord) {
  4971. // Some additional restrictions exist on the variant members.
  4972. if (!inUnion() && FieldRecord->isUnion() &&
  4973. FieldRecord->isAnonymousStructOrUnion()) {
  4974. bool AllVariantFieldsAreConst = true;
  4975. // FIXME: Handle anonymous unions declared within anonymous unions.
  4976. for (auto *UI : FieldRecord->fields()) {
  4977. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  4978. if (!UnionFieldType.isConstQualified())
  4979. AllVariantFieldsAreConst = false;
  4980. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  4981. if (UnionFieldRecord &&
  4982. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  4983. UnionFieldType.getCVRQualifiers()))
  4984. return true;
  4985. }
  4986. // At least one member in each anonymous union must be non-const
  4987. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  4988. !FieldRecord->field_empty()) {
  4989. if (Diagnose)
  4990. S.Diag(FieldRecord->getLocation(),
  4991. diag::note_deleted_default_ctor_all_const)
  4992. << MD->getParent() << /*anonymous union*/1;
  4993. return true;
  4994. }
  4995. // Don't check the implicit member of the anonymous union type.
  4996. // This is technically non-conformant, but sanity demands it.
  4997. return false;
  4998. }
  4999. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  5000. FieldType.getCVRQualifiers()))
  5001. return true;
  5002. }
  5003. return false;
  5004. }
  5005. /// C++11 [class.ctor] p5:
  5006. /// A defaulted default constructor for a class X is defined as deleted if
  5007. /// X is a union and all of its variant members are of const-qualified type.
  5008. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  5009. // This is a silly definition, because it gives an empty union a deleted
  5010. // default constructor. Don't do that.
  5011. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
  5012. !MD->getParent()->field_empty()) {
  5013. if (Diagnose)
  5014. S.Diag(MD->getParent()->getLocation(),
  5015. diag::note_deleted_default_ctor_all_const)
  5016. << MD->getParent() << /*not anonymous union*/0;
  5017. return true;
  5018. }
  5019. return false;
  5020. }
  5021. /// Determine whether a defaulted special member function should be defined as
  5022. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  5023. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  5024. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  5025. bool Diagnose) {
  5026. if (MD->isInvalidDecl())
  5027. return false;
  5028. CXXRecordDecl *RD = MD->getParent();
  5029. assert(!RD->isDependentType() && "do deletion after instantiation");
  5030. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  5031. return false;
  5032. // C++11 [expr.lambda.prim]p19:
  5033. // The closure type associated with a lambda-expression has a
  5034. // deleted (8.4.3) default constructor and a deleted copy
  5035. // assignment operator.
  5036. if (RD->isLambda() &&
  5037. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  5038. if (Diagnose)
  5039. Diag(RD->getLocation(), diag::note_lambda_decl);
  5040. return true;
  5041. }
  5042. // For an anonymous struct or union, the copy and assignment special members
  5043. // will never be used, so skip the check. For an anonymous union declared at
  5044. // namespace scope, the constructor and destructor are used.
  5045. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  5046. RD->isAnonymousStructOrUnion())
  5047. return false;
  5048. // C++11 [class.copy]p7, p18:
  5049. // If the class definition declares a move constructor or move assignment
  5050. // operator, an implicitly declared copy constructor or copy assignment
  5051. // operator is defined as deleted.
  5052. if (MD->isImplicit() &&
  5053. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  5054. CXXMethodDecl *UserDeclaredMove = nullptr;
  5055. // In Microsoft mode, a user-declared move only causes the deletion of the
  5056. // corresponding copy operation, not both copy operations.
  5057. if (RD->hasUserDeclaredMoveConstructor() &&
  5058. (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
  5059. if (!Diagnose) return true;
  5060. // Find any user-declared move constructor.
  5061. for (auto *I : RD->ctors()) {
  5062. if (I->isMoveConstructor()) {
  5063. UserDeclaredMove = I;
  5064. break;
  5065. }
  5066. }
  5067. assert(UserDeclaredMove);
  5068. } else if (RD->hasUserDeclaredMoveAssignment() &&
  5069. (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
  5070. if (!Diagnose) return true;
  5071. // Find any user-declared move assignment operator.
  5072. for (auto *I : RD->methods()) {
  5073. if (I->isMoveAssignmentOperator()) {
  5074. UserDeclaredMove = I;
  5075. break;
  5076. }
  5077. }
  5078. assert(UserDeclaredMove);
  5079. }
  5080. if (UserDeclaredMove) {
  5081. Diag(UserDeclaredMove->getLocation(),
  5082. diag::note_deleted_copy_user_declared_move)
  5083. << (CSM == CXXCopyAssignment) << RD
  5084. << UserDeclaredMove->isMoveAssignmentOperator();
  5085. return true;
  5086. }
  5087. }
  5088. // Do access control from the special member function
  5089. ContextRAII MethodContext(*this, MD);
  5090. // C++11 [class.dtor]p5:
  5091. // -- for a virtual destructor, lookup of the non-array deallocation function
  5092. // results in an ambiguity or in a function that is deleted or inaccessible
  5093. if (CSM == CXXDestructor && MD->isVirtual()) {
  5094. FunctionDecl *OperatorDelete = nullptr;
  5095. DeclarationName Name =
  5096. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  5097. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  5098. OperatorDelete, false)) {
  5099. if (Diagnose)
  5100. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  5101. return true;
  5102. }
  5103. }
  5104. SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
  5105. for (auto &BI : RD->bases())
  5106. if (!BI.isVirtual() &&
  5107. SMI.shouldDeleteForBase(&BI))
  5108. return true;
  5109. // Per DR1611, do not consider virtual bases of constructors of abstract
  5110. // classes, since we are not going to construct them.
  5111. if (!RD->isAbstract() || !SMI.IsConstructor) {
  5112. for (auto &BI : RD->vbases())
  5113. if (SMI.shouldDeleteForBase(&BI))
  5114. return true;
  5115. }
  5116. for (auto *FI : RD->fields())
  5117. if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
  5118. SMI.shouldDeleteForField(FI))
  5119. return true;
  5120. if (SMI.shouldDeleteForAllConstMembers())
  5121. return true;
  5122. if (getLangOpts().CUDA) {
  5123. // We should delete the special member in CUDA mode if target inference
  5124. // failed.
  5125. return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
  5126. Diagnose);
  5127. }
  5128. return false;
  5129. }
  5130. /// Perform lookup for a special member of the specified kind, and determine
  5131. /// whether it is trivial. If the triviality can be determined without the
  5132. /// lookup, skip it. This is intended for use when determining whether a
  5133. /// special member of a containing object is trivial, and thus does not ever
  5134. /// perform overload resolution for default constructors.
  5135. ///
  5136. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  5137. /// member that was most likely to be intended to be trivial, if any.
  5138. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  5139. Sema::CXXSpecialMember CSM, unsigned Quals,
  5140. bool ConstRHS, CXXMethodDecl **Selected) {
  5141. if (Selected)
  5142. *Selected = nullptr;
  5143. switch (CSM) {
  5144. case Sema::CXXInvalid:
  5145. llvm_unreachable("not a special member");
  5146. case Sema::CXXDefaultConstructor:
  5147. // C++11 [class.ctor]p5:
  5148. // A default constructor is trivial if:
  5149. // - all the [direct subobjects] have trivial default constructors
  5150. //
  5151. // Note, no overload resolution is performed in this case.
  5152. if (RD->hasTrivialDefaultConstructor())
  5153. return true;
  5154. if (Selected) {
  5155. // If there's a default constructor which could have been trivial, dig it
  5156. // out. Otherwise, if there's any user-provided default constructor, point
  5157. // to that as an example of why there's not a trivial one.
  5158. CXXConstructorDecl *DefCtor = nullptr;
  5159. if (RD->needsImplicitDefaultConstructor())
  5160. S.DeclareImplicitDefaultConstructor(RD);
  5161. for (auto *CI : RD->ctors()) {
  5162. if (!CI->isDefaultConstructor())
  5163. continue;
  5164. DefCtor = CI;
  5165. if (!DefCtor->isUserProvided())
  5166. break;
  5167. }
  5168. *Selected = DefCtor;
  5169. }
  5170. return false;
  5171. case Sema::CXXDestructor:
  5172. // C++11 [class.dtor]p5:
  5173. // A destructor is trivial if:
  5174. // - all the direct [subobjects] have trivial destructors
  5175. if (RD->hasTrivialDestructor())
  5176. return true;
  5177. if (Selected) {
  5178. if (RD->needsImplicitDestructor())
  5179. S.DeclareImplicitDestructor(RD);
  5180. *Selected = RD->getDestructor();
  5181. }
  5182. return false;
  5183. case Sema::CXXCopyConstructor:
  5184. // C++11 [class.copy]p12:
  5185. // A copy constructor is trivial if:
  5186. // - the constructor selected to copy each direct [subobject] is trivial
  5187. if (RD->hasTrivialCopyConstructor()) {
  5188. if (Quals == Qualifiers::Const)
  5189. // We must either select the trivial copy constructor or reach an
  5190. // ambiguity; no need to actually perform overload resolution.
  5191. return true;
  5192. } else if (!Selected) {
  5193. return false;
  5194. }
  5195. // In C++98, we are not supposed to perform overload resolution here, but we
  5196. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  5197. // cases like B as having a non-trivial copy constructor:
  5198. // struct A { template<typename T> A(T&); };
  5199. // struct B { mutable A a; };
  5200. goto NeedOverloadResolution;
  5201. case Sema::CXXCopyAssignment:
  5202. // C++11 [class.copy]p25:
  5203. // A copy assignment operator is trivial if:
  5204. // - the assignment operator selected to copy each direct [subobject] is
  5205. // trivial
  5206. if (RD->hasTrivialCopyAssignment()) {
  5207. if (Quals == Qualifiers::Const)
  5208. return true;
  5209. } else if (!Selected) {
  5210. return false;
  5211. }
  5212. // In C++98, we are not supposed to perform overload resolution here, but we
  5213. // treat that as a language defect.
  5214. goto NeedOverloadResolution;
  5215. case Sema::CXXMoveConstructor:
  5216. case Sema::CXXMoveAssignment:
  5217. NeedOverloadResolution:
  5218. Sema::SpecialMemberOverloadResult *SMOR =
  5219. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  5220. // The standard doesn't describe how to behave if the lookup is ambiguous.
  5221. // We treat it as not making the member non-trivial, just like the standard
  5222. // mandates for the default constructor. This should rarely matter, because
  5223. // the member will also be deleted.
  5224. if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  5225. return true;
  5226. if (!SMOR->getMethod()) {
  5227. assert(SMOR->getKind() ==
  5228. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  5229. return false;
  5230. }
  5231. // We deliberately don't check if we found a deleted special member. We're
  5232. // not supposed to!
  5233. if (Selected)
  5234. *Selected = SMOR->getMethod();
  5235. return SMOR->getMethod()->isTrivial();
  5236. }
  5237. llvm_unreachable("unknown special method kind");
  5238. }
  5239. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  5240. for (auto *CI : RD->ctors())
  5241. if (!CI->isImplicit())
  5242. return CI;
  5243. // Look for constructor templates.
  5244. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  5245. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  5246. if (CXXConstructorDecl *CD =
  5247. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  5248. return CD;
  5249. }
  5250. return nullptr;
  5251. }
  5252. /// The kind of subobject we are checking for triviality. The values of this
  5253. /// enumeration are used in diagnostics.
  5254. enum TrivialSubobjectKind {
  5255. /// The subobject is a base class.
  5256. TSK_BaseClass,
  5257. /// The subobject is a non-static data member.
  5258. TSK_Field,
  5259. /// The object is actually the complete object.
  5260. TSK_CompleteObject
  5261. };
  5262. /// Check whether the special member selected for a given type would be trivial.
  5263. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  5264. QualType SubType, bool ConstRHS,
  5265. Sema::CXXSpecialMember CSM,
  5266. TrivialSubobjectKind Kind,
  5267. bool Diagnose) {
  5268. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  5269. if (!SubRD)
  5270. return true;
  5271. CXXMethodDecl *Selected;
  5272. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  5273. ConstRHS, Diagnose ? &Selected : nullptr))
  5274. return true;
  5275. if (Diagnose) {
  5276. if (ConstRHS)
  5277. SubType.addConst();
  5278. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  5279. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  5280. << Kind << SubType.getUnqualifiedType();
  5281. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  5282. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  5283. } else if (!Selected)
  5284. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  5285. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  5286. else if (Selected->isUserProvided()) {
  5287. if (Kind == TSK_CompleteObject)
  5288. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  5289. << Kind << SubType.getUnqualifiedType() << CSM;
  5290. else {
  5291. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  5292. << Kind << SubType.getUnqualifiedType() << CSM;
  5293. S.Diag(Selected->getLocation(), diag::note_declared_at);
  5294. }
  5295. } else {
  5296. if (Kind != TSK_CompleteObject)
  5297. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  5298. << Kind << SubType.getUnqualifiedType() << CSM;
  5299. // Explain why the defaulted or deleted special member isn't trivial.
  5300. S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
  5301. }
  5302. }
  5303. return false;
  5304. }
  5305. /// Check whether the members of a class type allow a special member to be
  5306. /// trivial.
  5307. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  5308. Sema::CXXSpecialMember CSM,
  5309. bool ConstArg, bool Diagnose) {
  5310. for (const auto *FI : RD->fields()) {
  5311. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  5312. continue;
  5313. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  5314. // Pretend anonymous struct or union members are members of this class.
  5315. if (FI->isAnonymousStructOrUnion()) {
  5316. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  5317. CSM, ConstArg, Diagnose))
  5318. return false;
  5319. continue;
  5320. }
  5321. // C++11 [class.ctor]p5:
  5322. // A default constructor is trivial if [...]
  5323. // -- no non-static data member of its class has a
  5324. // brace-or-equal-initializer
  5325. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  5326. if (Diagnose)
  5327. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  5328. return false;
  5329. }
  5330. // Objective C ARC 4.3.5:
  5331. // [...] nontrivally ownership-qualified types are [...] not trivially
  5332. // default constructible, copy constructible, move constructible, copy
  5333. // assignable, move assignable, or destructible [...]
  5334. if (S.getLangOpts().ObjCAutoRefCount &&
  5335. FieldType.hasNonTrivialObjCLifetime()) {
  5336. if (Diagnose)
  5337. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  5338. << RD << FieldType.getObjCLifetime();
  5339. return false;
  5340. }
  5341. bool ConstRHS = ConstArg && !FI->isMutable();
  5342. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  5343. CSM, TSK_Field, Diagnose))
  5344. return false;
  5345. }
  5346. return true;
  5347. }
  5348. /// Diagnose why the specified class does not have a trivial special member of
  5349. /// the given kind.
  5350. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  5351. QualType Ty = Context.getRecordType(RD);
  5352. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  5353. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  5354. TSK_CompleteObject, /*Diagnose*/true);
  5355. }
  5356. /// Determine whether a defaulted or deleted special member function is trivial,
  5357. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  5358. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  5359. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  5360. bool Diagnose) {
  5361. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  5362. CXXRecordDecl *RD = MD->getParent();
  5363. bool ConstArg = false;
  5364. // C++11 [class.copy]p12, p25: [DR1593]
  5365. // A [special member] is trivial if [...] its parameter-type-list is
  5366. // equivalent to the parameter-type-list of an implicit declaration [...]
  5367. switch (CSM) {
  5368. case CXXDefaultConstructor:
  5369. case CXXDestructor:
  5370. // Trivial default constructors and destructors cannot have parameters.
  5371. break;
  5372. case CXXCopyConstructor:
  5373. case CXXCopyAssignment: {
  5374. // Trivial copy operations always have const, non-volatile parameter types.
  5375. ConstArg = true;
  5376. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  5377. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  5378. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  5379. if (Diagnose)
  5380. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  5381. << Param0->getSourceRange() << Param0->getType()
  5382. << Context.getLValueReferenceType(
  5383. Context.getRecordType(RD).withConst());
  5384. return false;
  5385. }
  5386. break;
  5387. }
  5388. case CXXMoveConstructor:
  5389. case CXXMoveAssignment: {
  5390. // Trivial move operations always have non-cv-qualified parameters.
  5391. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  5392. const RValueReferenceType *RT =
  5393. Param0->getType()->getAs<RValueReferenceType>();
  5394. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  5395. if (Diagnose)
  5396. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  5397. << Param0->getSourceRange() << Param0->getType()
  5398. << Context.getRValueReferenceType(Context.getRecordType(RD));
  5399. return false;
  5400. }
  5401. break;
  5402. }
  5403. case CXXInvalid:
  5404. llvm_unreachable("not a special member");
  5405. }
  5406. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  5407. if (Diagnose)
  5408. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  5409. diag::note_nontrivial_default_arg)
  5410. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  5411. return false;
  5412. }
  5413. if (MD->isVariadic()) {
  5414. if (Diagnose)
  5415. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  5416. return false;
  5417. }
  5418. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  5419. // A copy/move [constructor or assignment operator] is trivial if
  5420. // -- the [member] selected to copy/move each direct base class subobject
  5421. // is trivial
  5422. //
  5423. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  5424. // A [default constructor or destructor] is trivial if
  5425. // -- all the direct base classes have trivial [default constructors or
  5426. // destructors]
  5427. for (const auto &BI : RD->bases())
  5428. if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
  5429. ConstArg, CSM, TSK_BaseClass, Diagnose))
  5430. return false;
  5431. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  5432. // A copy/move [constructor or assignment operator] for a class X is
  5433. // trivial if
  5434. // -- for each non-static data member of X that is of class type (or array
  5435. // thereof), the constructor selected to copy/move that member is
  5436. // trivial
  5437. //
  5438. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  5439. // A [default constructor or destructor] is trivial if
  5440. // -- for all of the non-static data members of its class that are of class
  5441. // type (or array thereof), each such class has a trivial [default
  5442. // constructor or destructor]
  5443. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
  5444. return false;
  5445. // C++11 [class.dtor]p5:
  5446. // A destructor is trivial if [...]
  5447. // -- the destructor is not virtual
  5448. if (CSM == CXXDestructor && MD->isVirtual()) {
  5449. if (Diagnose)
  5450. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  5451. return false;
  5452. }
  5453. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  5454. // A [special member] for class X is trivial if [...]
  5455. // -- class X has no virtual functions and no virtual base classes
  5456. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  5457. if (!Diagnose)
  5458. return false;
  5459. if (RD->getNumVBases()) {
  5460. // Check for virtual bases. We already know that the corresponding
  5461. // member in all bases is trivial, so vbases must all be direct.
  5462. CXXBaseSpecifier &BS = *RD->vbases_begin();
  5463. assert(BS.isVirtual());
  5464. Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
  5465. return false;
  5466. }
  5467. // Must have a virtual method.
  5468. for (const auto *MI : RD->methods()) {
  5469. if (MI->isVirtual()) {
  5470. SourceLocation MLoc = MI->getLocStart();
  5471. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  5472. return false;
  5473. }
  5474. }
  5475. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  5476. }
  5477. // Looks like it's trivial!
  5478. return true;
  5479. }
  5480. /// \brief Data used with FindHiddenVirtualMethod
  5481. namespace {
  5482. struct FindHiddenVirtualMethodData {
  5483. Sema *S;
  5484. CXXMethodDecl *Method;
  5485. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  5486. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  5487. };
  5488. }
  5489. /// \brief Check whether any most overriden method from MD in Methods
  5490. static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
  5491. const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  5492. if (MD->size_overridden_methods() == 0)
  5493. return Methods.count(MD->getCanonicalDecl());
  5494. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5495. E = MD->end_overridden_methods();
  5496. I != E; ++I)
  5497. if (CheckMostOverridenMethods(*I, Methods))
  5498. return true;
  5499. return false;
  5500. }
  5501. /// \brief Member lookup function that determines whether a given C++
  5502. /// method overloads virtual methods in a base class without overriding any,
  5503. /// to be used with CXXRecordDecl::lookupInBases().
  5504. static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
  5505. CXXBasePath &Path,
  5506. void *UserData) {
  5507. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  5508. FindHiddenVirtualMethodData &Data
  5509. = *static_cast<FindHiddenVirtualMethodData*>(UserData);
  5510. DeclarationName Name = Data.Method->getDeclName();
  5511. assert(Name.getNameKind() == DeclarationName::Identifier);
  5512. bool foundSameNameMethod = false;
  5513. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  5514. for (Path.Decls = BaseRecord->lookup(Name);
  5515. !Path.Decls.empty();
  5516. Path.Decls = Path.Decls.slice(1)) {
  5517. NamedDecl *D = Path.Decls.front();
  5518. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  5519. MD = MD->getCanonicalDecl();
  5520. foundSameNameMethod = true;
  5521. // Interested only in hidden virtual methods.
  5522. if (!MD->isVirtual())
  5523. continue;
  5524. // If the method we are checking overrides a method from its base
  5525. // don't warn about the other overloaded methods. Clang deviates from GCC
  5526. // by only diagnosing overloads of inherited virtual functions that do not
  5527. // override any other virtual functions in the base. GCC's
  5528. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  5529. // function from a base class. These cases may be better served by a
  5530. // warning (not specific to virtual functions) on call sites when the call
  5531. // would select a different function from the base class, were it visible.
  5532. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  5533. if (!Data.S->IsOverload(Data.Method, MD, false))
  5534. return true;
  5535. // Collect the overload only if its hidden.
  5536. if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
  5537. overloadedMethods.push_back(MD);
  5538. }
  5539. }
  5540. if (foundSameNameMethod)
  5541. Data.OverloadedMethods.append(overloadedMethods.begin(),
  5542. overloadedMethods.end());
  5543. return foundSameNameMethod;
  5544. }
  5545. /// \brief Add the most overriden methods from MD to Methods
  5546. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  5547. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  5548. if (MD->size_overridden_methods() == 0)
  5549. Methods.insert(MD->getCanonicalDecl());
  5550. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5551. E = MD->end_overridden_methods();
  5552. I != E; ++I)
  5553. AddMostOverridenMethods(*I, Methods);
  5554. }
  5555. /// \brief Check if a method overloads virtual methods in a base class without
  5556. /// overriding any.
  5557. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  5558. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  5559. if (!MD->getDeclName().isIdentifier())
  5560. return;
  5561. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  5562. /*bool RecordPaths=*/false,
  5563. /*bool DetectVirtual=*/false);
  5564. FindHiddenVirtualMethodData Data;
  5565. Data.Method = MD;
  5566. Data.S = this;
  5567. // Keep the base methods that were overriden or introduced in the subclass
  5568. // by 'using' in a set. A base method not in this set is hidden.
  5569. CXXRecordDecl *DC = MD->getParent();
  5570. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  5571. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  5572. NamedDecl *ND = *I;
  5573. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  5574. ND = shad->getTargetDecl();
  5575. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  5576. AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
  5577. }
  5578. if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
  5579. OverloadedMethods = Data.OverloadedMethods;
  5580. }
  5581. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  5582. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  5583. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  5584. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  5585. PartialDiagnostic PD = PDiag(
  5586. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  5587. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  5588. Diag(overloadedMD->getLocation(), PD);
  5589. }
  5590. }
  5591. /// \brief Diagnose methods which overload virtual methods in a base class
  5592. /// without overriding any.
  5593. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  5594. if (MD->isInvalidDecl())
  5595. return;
  5596. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  5597. return;
  5598. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  5599. FindHiddenVirtualMethods(MD, OverloadedMethods);
  5600. if (!OverloadedMethods.empty()) {
  5601. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  5602. << MD << (OverloadedMethods.size() > 1);
  5603. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  5604. }
  5605. }
  5606. void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
  5607. Decl *TagDecl,
  5608. SourceLocation LBrac,
  5609. SourceLocation RBrac,
  5610. AttributeList *AttrList) {
  5611. if (!TagDecl)
  5612. return;
  5613. AdjustDeclIfTemplate(TagDecl);
  5614. for (const AttributeList* l = AttrList; l; l = l->getNext()) {
  5615. if (l->getKind() != AttributeList::AT_Visibility)
  5616. continue;
  5617. l->setInvalid();
  5618. Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
  5619. l->getName();
  5620. }
  5621. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  5622. // strict aliasing violation!
  5623. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  5624. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  5625. CheckCompletedCXXClass(
  5626. dyn_cast_or_null<CXXRecordDecl>(TagDecl));
  5627. }
  5628. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  5629. /// special functions, such as the default constructor, copy
  5630. /// constructor, or destructor, to the given C++ class (C++
  5631. /// [special]p1). This routine can only be executed just before the
  5632. /// definition of the class is complete.
  5633. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  5634. if (!ClassDecl->hasUserDeclaredConstructor())
  5635. ++ASTContext::NumImplicitDefaultConstructors;
  5636. if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
  5637. ++ASTContext::NumImplicitCopyConstructors;
  5638. // If the properties or semantics of the copy constructor couldn't be
  5639. // determined while the class was being declared, force a declaration
  5640. // of it now.
  5641. if (ClassDecl->needsOverloadResolutionForCopyConstructor())
  5642. DeclareImplicitCopyConstructor(ClassDecl);
  5643. }
  5644. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  5645. ++ASTContext::NumImplicitMoveConstructors;
  5646. if (ClassDecl->needsOverloadResolutionForMoveConstructor())
  5647. DeclareImplicitMoveConstructor(ClassDecl);
  5648. }
  5649. if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
  5650. ++ASTContext::NumImplicitCopyAssignmentOperators;
  5651. // If we have a dynamic class, then the copy assignment operator may be
  5652. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  5653. // it shows up in the right place in the vtable and that we diagnose
  5654. // problems with the implicit exception specification.
  5655. if (ClassDecl->isDynamicClass() ||
  5656. ClassDecl->needsOverloadResolutionForCopyAssignment())
  5657. DeclareImplicitCopyAssignment(ClassDecl);
  5658. }
  5659. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  5660. ++ASTContext::NumImplicitMoveAssignmentOperators;
  5661. // Likewise for the move assignment operator.
  5662. if (ClassDecl->isDynamicClass() ||
  5663. ClassDecl->needsOverloadResolutionForMoveAssignment())
  5664. DeclareImplicitMoveAssignment(ClassDecl);
  5665. }
  5666. if (!ClassDecl->hasUserDeclaredDestructor()) {
  5667. ++ASTContext::NumImplicitDestructors;
  5668. // If we have a dynamic class, then the destructor may be virtual, so we
  5669. // have to declare the destructor immediately. This ensures that, e.g., it
  5670. // shows up in the right place in the vtable and that we diagnose problems
  5671. // with the implicit exception specification.
  5672. if (ClassDecl->isDynamicClass() ||
  5673. ClassDecl->needsOverloadResolutionForDestructor())
  5674. DeclareImplicitDestructor(ClassDecl);
  5675. }
  5676. }
  5677. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  5678. if (!D)
  5679. return 0;
  5680. // The order of template parameters is not important here. All names
  5681. // get added to the same scope.
  5682. SmallVector<TemplateParameterList *, 4> ParameterLists;
  5683. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  5684. D = TD->getTemplatedDecl();
  5685. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  5686. ParameterLists.push_back(PSD->getTemplateParameters());
  5687. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  5688. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  5689. ParameterLists.push_back(DD->getTemplateParameterList(i));
  5690. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  5691. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  5692. ParameterLists.push_back(FTD->getTemplateParameters());
  5693. }
  5694. }
  5695. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  5696. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  5697. ParameterLists.push_back(TD->getTemplateParameterList(i));
  5698. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  5699. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  5700. ParameterLists.push_back(CTD->getTemplateParameters());
  5701. }
  5702. }
  5703. unsigned Count = 0;
  5704. for (TemplateParameterList *Params : ParameterLists) {
  5705. if (Params->size() > 0)
  5706. // Ignore explicit specializations; they don't contribute to the template
  5707. // depth.
  5708. ++Count;
  5709. for (NamedDecl *Param : *Params) {
  5710. if (Param->getDeclName()) {
  5711. S->AddDecl(Param);
  5712. IdResolver.AddDecl(Param);
  5713. }
  5714. }
  5715. }
  5716. return Count;
  5717. }
  5718. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  5719. if (!RecordD) return;
  5720. AdjustDeclIfTemplate(RecordD);
  5721. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  5722. PushDeclContext(S, Record);
  5723. }
  5724. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  5725. if (!RecordD) return;
  5726. PopDeclContext();
  5727. }
  5728. /// This is used to implement the constant expression evaluation part of the
  5729. /// attribute enable_if extension. There is nothing in standard C++ which would
  5730. /// require reentering parameters.
  5731. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  5732. if (!Param)
  5733. return;
  5734. S->AddDecl(Param);
  5735. if (Param->getDeclName())
  5736. IdResolver.AddDecl(Param);
  5737. }
  5738. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  5739. /// parsing a top-level (non-nested) C++ class, and we are now
  5740. /// parsing those parts of the given Method declaration that could
  5741. /// not be parsed earlier (C++ [class.mem]p2), such as default
  5742. /// arguments. This action should enter the scope of the given
  5743. /// Method declaration as if we had just parsed the qualified method
  5744. /// name. However, it should not bring the parameters into scope;
  5745. /// that will be performed by ActOnDelayedCXXMethodParameter.
  5746. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  5747. }
  5748. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  5749. /// C++ method declaration. We're (re-)introducing the given
  5750. /// function parameter into scope for use in parsing later parts of
  5751. /// the method declaration. For example, we could see an
  5752. /// ActOnParamDefaultArgument event for this parameter.
  5753. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  5754. if (!ParamD)
  5755. return;
  5756. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  5757. // If this parameter has an unparsed default argument, clear it out
  5758. // to make way for the parsed default argument.
  5759. if (Param->hasUnparsedDefaultArg())
  5760. Param->setDefaultArg(nullptr);
  5761. S->AddDecl(Param);
  5762. if (Param->getDeclName())
  5763. IdResolver.AddDecl(Param);
  5764. }
  5765. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  5766. /// processing the delayed method declaration for Method. The method
  5767. /// declaration is now considered finished. There may be a separate
  5768. /// ActOnStartOfFunctionDef action later (not necessarily
  5769. /// immediately!) for this method, if it was also defined inside the
  5770. /// class body.
  5771. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  5772. if (!MethodD)
  5773. return;
  5774. AdjustDeclIfTemplate(MethodD);
  5775. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  5776. // Now that we have our default arguments, check the constructor
  5777. // again. It could produce additional diagnostics or affect whether
  5778. // the class has implicitly-declared destructors, among other
  5779. // things.
  5780. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  5781. CheckConstructor(Constructor);
  5782. // Check the default arguments, which we may have added.
  5783. if (!Method->isInvalidDecl())
  5784. CheckCXXDefaultArguments(Method);
  5785. }
  5786. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  5787. /// the well-formedness of the constructor declarator @p D with type @p
  5788. /// R. If there are any errors in the declarator, this routine will
  5789. /// emit diagnostics and set the invalid bit to true. In any case, the type
  5790. /// will be updated to reflect a well-formed type for the constructor and
  5791. /// returned.
  5792. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  5793. StorageClass &SC) {
  5794. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  5795. // C++ [class.ctor]p3:
  5796. // A constructor shall not be virtual (10.3) or static (9.4). A
  5797. // constructor can be invoked for a const, volatile or const
  5798. // volatile object. A constructor shall not be declared const,
  5799. // volatile, or const volatile (9.3.2).
  5800. if (isVirtual) {
  5801. if (!D.isInvalidType())
  5802. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  5803. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  5804. << SourceRange(D.getIdentifierLoc());
  5805. D.setInvalidType();
  5806. }
  5807. if (SC == SC_Static) {
  5808. if (!D.isInvalidType())
  5809. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  5810. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  5811. << SourceRange(D.getIdentifierLoc());
  5812. D.setInvalidType();
  5813. SC = SC_None;
  5814. }
  5815. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  5816. diagnoseIgnoredQualifiers(
  5817. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  5818. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  5819. D.getDeclSpec().getRestrictSpecLoc(),
  5820. D.getDeclSpec().getAtomicSpecLoc());
  5821. D.setInvalidType();
  5822. }
  5823. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  5824. if (FTI.TypeQuals != 0) {
  5825. if (FTI.TypeQuals & Qualifiers::Const)
  5826. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  5827. << "const" << SourceRange(D.getIdentifierLoc());
  5828. if (FTI.TypeQuals & Qualifiers::Volatile)
  5829. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  5830. << "volatile" << SourceRange(D.getIdentifierLoc());
  5831. if (FTI.TypeQuals & Qualifiers::Restrict)
  5832. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  5833. << "restrict" << SourceRange(D.getIdentifierLoc());
  5834. D.setInvalidType();
  5835. }
  5836. // C++0x [class.ctor]p4:
  5837. // A constructor shall not be declared with a ref-qualifier.
  5838. if (FTI.hasRefQualifier()) {
  5839. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  5840. << FTI.RefQualifierIsLValueRef
  5841. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  5842. D.setInvalidType();
  5843. }
  5844. // Rebuild the function type "R" without any type qualifiers (in
  5845. // case any of the errors above fired) and with "void" as the
  5846. // return type, since constructors don't have return types.
  5847. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  5848. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  5849. return R;
  5850. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  5851. EPI.TypeQuals = 0;
  5852. EPI.RefQualifier = RQ_None;
  5853. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI, None); // HLSL Change - constructors members are all-in params
  5854. }
  5855. /// CheckConstructor - Checks a fully-formed constructor for
  5856. /// well-formedness, issuing any diagnostics required. Returns true if
  5857. /// the constructor declarator is invalid.
  5858. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  5859. CXXRecordDecl *ClassDecl
  5860. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  5861. if (!ClassDecl)
  5862. return Constructor->setInvalidDecl();
  5863. // C++ [class.copy]p3:
  5864. // A declaration of a constructor for a class X is ill-formed if
  5865. // its first parameter is of type (optionally cv-qualified) X and
  5866. // either there are no other parameters or else all other
  5867. // parameters have default arguments.
  5868. if (!Constructor->isInvalidDecl() &&
  5869. ((Constructor->getNumParams() == 1) ||
  5870. (Constructor->getNumParams() > 1 &&
  5871. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  5872. Constructor->getTemplateSpecializationKind()
  5873. != TSK_ImplicitInstantiation) {
  5874. QualType ParamType = Constructor->getParamDecl(0)->getType();
  5875. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  5876. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  5877. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  5878. const char *ConstRef
  5879. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  5880. : " const &";
  5881. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  5882. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  5883. // FIXME: Rather that making the constructor invalid, we should endeavor
  5884. // to fix the type.
  5885. Constructor->setInvalidDecl();
  5886. }
  5887. }
  5888. }
  5889. /// CheckDestructor - Checks a fully-formed destructor definition for
  5890. /// well-formedness, issuing any diagnostics required. Returns true
  5891. /// on error.
  5892. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  5893. CXXRecordDecl *RD = Destructor->getParent();
  5894. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  5895. SourceLocation Loc;
  5896. if (!Destructor->isImplicit())
  5897. Loc = Destructor->getLocation();
  5898. else
  5899. Loc = RD->getLocation();
  5900. // If we have a virtual destructor, look up the deallocation function
  5901. FunctionDecl *OperatorDelete = nullptr;
  5902. DeclarationName Name =
  5903. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  5904. if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
  5905. return true;
  5906. // If there's no class-specific operator delete, look up the global
  5907. // non-array delete.
  5908. if (!OperatorDelete)
  5909. OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
  5910. MarkFunctionReferenced(Loc, OperatorDelete);
  5911. Destructor->setOperatorDelete(OperatorDelete);
  5912. }
  5913. return false;
  5914. }
  5915. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  5916. /// the well-formednes of the destructor declarator @p D with type @p
  5917. /// R. If there are any errors in the declarator, this routine will
  5918. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  5919. /// will be updated to reflect a well-formed type for the destructor and
  5920. /// returned.
  5921. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  5922. StorageClass& SC) {
  5923. // C++ [class.dtor]p1:
  5924. // [...] A typedef-name that names a class is a class-name
  5925. // (7.1.3); however, a typedef-name that names a class shall not
  5926. // be used as the identifier in the declarator for a destructor
  5927. // declaration.
  5928. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  5929. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  5930. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  5931. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  5932. else if (const TemplateSpecializationType *TST =
  5933. DeclaratorType->getAs<TemplateSpecializationType>())
  5934. if (TST->isTypeAlias())
  5935. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  5936. << DeclaratorType << 1;
  5937. // C++ [class.dtor]p2:
  5938. // A destructor is used to destroy objects of its class type. A
  5939. // destructor takes no parameters, and no return type can be
  5940. // specified for it (not even void). The address of a destructor
  5941. // shall not be taken. A destructor shall not be static. A
  5942. // destructor can be invoked for a const, volatile or const
  5943. // volatile object. A destructor shall not be declared const,
  5944. // volatile or const volatile (9.3.2).
  5945. if (SC == SC_Static) {
  5946. if (!D.isInvalidType())
  5947. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  5948. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  5949. << SourceRange(D.getIdentifierLoc())
  5950. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5951. SC = SC_None;
  5952. }
  5953. if (!D.isInvalidType()) {
  5954. // Destructors don't have return types, but the parser will
  5955. // happily parse something like:
  5956. //
  5957. // class X {
  5958. // float ~X();
  5959. // };
  5960. //
  5961. // The return type will be eliminated later.
  5962. if (D.getDeclSpec().hasTypeSpecifier())
  5963. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  5964. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  5965. << SourceRange(D.getIdentifierLoc());
  5966. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  5967. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  5968. SourceLocation(),
  5969. D.getDeclSpec().getConstSpecLoc(),
  5970. D.getDeclSpec().getVolatileSpecLoc(),
  5971. D.getDeclSpec().getRestrictSpecLoc(),
  5972. D.getDeclSpec().getAtomicSpecLoc());
  5973. D.setInvalidType();
  5974. }
  5975. }
  5976. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  5977. if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
  5978. if (FTI.TypeQuals & Qualifiers::Const)
  5979. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  5980. << "const" << SourceRange(D.getIdentifierLoc());
  5981. if (FTI.TypeQuals & Qualifiers::Volatile)
  5982. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  5983. << "volatile" << SourceRange(D.getIdentifierLoc());
  5984. if (FTI.TypeQuals & Qualifiers::Restrict)
  5985. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  5986. << "restrict" << SourceRange(D.getIdentifierLoc());
  5987. D.setInvalidType();
  5988. }
  5989. // C++0x [class.dtor]p2:
  5990. // A destructor shall not be declared with a ref-qualifier.
  5991. if (FTI.hasRefQualifier()) {
  5992. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  5993. << FTI.RefQualifierIsLValueRef
  5994. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  5995. D.setInvalidType();
  5996. }
  5997. // Make sure we don't have any parameters.
  5998. if (FTIHasNonVoidParameters(FTI)) {
  5999. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  6000. // Delete the parameters.
  6001. FTI.freeParams();
  6002. D.setInvalidType();
  6003. }
  6004. // Make sure the destructor isn't variadic.
  6005. if (FTI.isVariadic) {
  6006. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  6007. D.setInvalidType();
  6008. }
  6009. // Rebuild the function type "R" without any type qualifiers or
  6010. // parameters (in case any of the errors above fired) and with
  6011. // "void" as the return type, since destructors don't have return
  6012. // types.
  6013. if (!D.isInvalidType())
  6014. return R;
  6015. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  6016. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  6017. EPI.Variadic = false;
  6018. EPI.TypeQuals = 0;
  6019. EPI.RefQualifier = RQ_None;
  6020. return Context.getFunctionType(Context.VoidTy, None, EPI, None); // HLSL Change - no destructor args
  6021. }
  6022. static void extendLeft(SourceRange &R, const SourceRange &Before) {
  6023. if (Before.isInvalid())
  6024. return;
  6025. R.setBegin(Before.getBegin());
  6026. if (R.getEnd().isInvalid())
  6027. R.setEnd(Before.getEnd());
  6028. }
  6029. static void extendRight(SourceRange &R, const SourceRange &After) {
  6030. if (After.isInvalid())
  6031. return;
  6032. if (R.getBegin().isInvalid())
  6033. R.setBegin(After.getBegin());
  6034. R.setEnd(After.getEnd());
  6035. }
  6036. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  6037. /// well-formednes of the conversion function declarator @p D with
  6038. /// type @p R. If there are any errors in the declarator, this routine
  6039. /// will emit diagnostics and return true. Otherwise, it will return
  6040. /// false. Either way, the type @p R will be updated to reflect a
  6041. /// well-formed type for the conversion operator.
  6042. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  6043. StorageClass& SC) {
  6044. // C++ [class.conv.fct]p1:
  6045. // Neither parameter types nor return type can be specified. The
  6046. // type of a conversion function (8.3.5) is "function taking no
  6047. // parameter returning conversion-type-id."
  6048. if (SC == SC_Static) {
  6049. if (!D.isInvalidType())
  6050. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  6051. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  6052. << D.getName().getSourceRange();
  6053. D.setInvalidType();
  6054. SC = SC_None;
  6055. }
  6056. TypeSourceInfo *ConvTSI = nullptr;
  6057. QualType ConvType =
  6058. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  6059. if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
  6060. // Conversion functions don't have return types, but the parser will
  6061. // happily parse something like:
  6062. //
  6063. // class X {
  6064. // float operator bool();
  6065. // };
  6066. //
  6067. // The return type will be changed later anyway.
  6068. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  6069. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6070. << SourceRange(D.getIdentifierLoc());
  6071. D.setInvalidType();
  6072. }
  6073. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  6074. // Make sure we don't have any parameters.
  6075. if (Proto->getNumParams() > 0) {
  6076. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  6077. // Delete the parameters.
  6078. D.getFunctionTypeInfo().freeParams();
  6079. D.setInvalidType();
  6080. } else if (Proto->isVariadic()) {
  6081. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  6082. D.setInvalidType();
  6083. }
  6084. // Diagnose "&operator bool()" and other such nonsense. This
  6085. // is actually a gcc extension which we don't support.
  6086. if (Proto->getReturnType() != ConvType) {
  6087. bool NeedsTypedef = false;
  6088. SourceRange Before, After;
  6089. // Walk the chunks and extract information on them for our diagnostic.
  6090. bool PastFunctionChunk = false;
  6091. for (auto &Chunk : D.type_objects()) {
  6092. switch (Chunk.Kind) {
  6093. case DeclaratorChunk::Function:
  6094. if (!PastFunctionChunk) {
  6095. if (Chunk.Fun.HasTrailingReturnType) {
  6096. TypeSourceInfo *TRT = nullptr;
  6097. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  6098. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  6099. }
  6100. PastFunctionChunk = true;
  6101. break;
  6102. }
  6103. // Fall through.
  6104. case DeclaratorChunk::Array:
  6105. NeedsTypedef = true;
  6106. extendRight(After, Chunk.getSourceRange());
  6107. break;
  6108. case DeclaratorChunk::Pointer:
  6109. case DeclaratorChunk::BlockPointer:
  6110. case DeclaratorChunk::Reference:
  6111. case DeclaratorChunk::MemberPointer:
  6112. extendLeft(Before, Chunk.getSourceRange());
  6113. break;
  6114. case DeclaratorChunk::Paren:
  6115. extendLeft(Before, Chunk.Loc);
  6116. extendRight(After, Chunk.EndLoc);
  6117. break;
  6118. }
  6119. }
  6120. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  6121. After.isValid() ? After.getBegin() :
  6122. D.getIdentifierLoc();
  6123. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  6124. DB << Before << After;
  6125. if (!NeedsTypedef) {
  6126. DB << /*don't need a typedef*/0;
  6127. // If we can provide a correct fix-it hint, do so.
  6128. if (After.isInvalid() && ConvTSI) {
  6129. SourceLocation InsertLoc =
  6130. PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
  6131. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  6132. << FixItHint::CreateInsertionFromRange(
  6133. InsertLoc, CharSourceRange::getTokenRange(Before))
  6134. << FixItHint::CreateRemoval(Before);
  6135. }
  6136. } else if (!Proto->getReturnType()->isDependentType()) {
  6137. DB << /*typedef*/1 << Proto->getReturnType();
  6138. } else if (getLangOpts().CPlusPlus11) {
  6139. DB << /*alias template*/2 << Proto->getReturnType();
  6140. } else {
  6141. DB << /*might not be fixable*/3;
  6142. }
  6143. // Recover by incorporating the other type chunks into the result type.
  6144. // Note, this does *not* change the name of the function. This is compatible
  6145. // with the GCC extension:
  6146. // struct S { &operator int(); } s;
  6147. // int &r = s.operator int(); // ok in GCC
  6148. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  6149. ConvType = Proto->getReturnType();
  6150. }
  6151. // C++ [class.conv.fct]p4:
  6152. // The conversion-type-id shall not represent a function type nor
  6153. // an array type.
  6154. if (ConvType->isArrayType()) {
  6155. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  6156. ConvType = Context.getPointerType(ConvType);
  6157. D.setInvalidType();
  6158. } else if (ConvType->isFunctionType()) {
  6159. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  6160. ConvType = Context.getPointerType(ConvType);
  6161. D.setInvalidType();
  6162. }
  6163. // Rebuild the function type "R" without any parameters (in case any
  6164. // of the errors above fired) and with the conversion type as the
  6165. // return type.
  6166. if (D.isInvalidType())
  6167. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo(), None); // HLSL Change
  6168. // C++0x explicit conversion operators.
  6169. if (D.getDeclSpec().isExplicitSpecified())
  6170. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6171. getLangOpts().CPlusPlus11 ?
  6172. diag::warn_cxx98_compat_explicit_conversion_functions :
  6173. diag::ext_explicit_conversion_functions)
  6174. << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
  6175. }
  6176. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  6177. /// the declaration of the given C++ conversion function. This routine
  6178. /// is responsible for recording the conversion function in the C++
  6179. /// class, if possible.
  6180. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  6181. assert(Conversion && "Expected to receive a conversion function declaration");
  6182. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  6183. // Make sure we aren't redeclaring the conversion function.
  6184. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  6185. // C++ [class.conv.fct]p1:
  6186. // [...] A conversion function is never used to convert a
  6187. // (possibly cv-qualified) object to the (possibly cv-qualified)
  6188. // same object type (or a reference to it), to a (possibly
  6189. // cv-qualified) base class of that type (or a reference to it),
  6190. // or to (possibly cv-qualified) void.
  6191. // FIXME: Suppress this warning if the conversion function ends up being a
  6192. // virtual function that overrides a virtual function in a base class.
  6193. QualType ClassType
  6194. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  6195. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  6196. ConvType = ConvTypeRef->getPointeeType();
  6197. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  6198. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  6199. /* Suppress diagnostics for instantiations. */;
  6200. else if (ConvType->isRecordType()) {
  6201. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  6202. if (ConvType == ClassType)
  6203. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  6204. << ClassType;
  6205. else if (IsDerivedFrom(ClassType, ConvType))
  6206. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  6207. << ClassType << ConvType;
  6208. } else if (ConvType->isVoidType()) {
  6209. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  6210. << ClassType << ConvType;
  6211. }
  6212. if (FunctionTemplateDecl *ConversionTemplate
  6213. = Conversion->getDescribedFunctionTemplate())
  6214. return ConversionTemplate;
  6215. return Conversion;
  6216. }
  6217. //===----------------------------------------------------------------------===//
  6218. // Namespace Handling
  6219. //===----------------------------------------------------------------------===//
  6220. /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
  6221. /// reopened.
  6222. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  6223. SourceLocation Loc,
  6224. IdentifierInfo *II, bool *IsInline,
  6225. NamespaceDecl *PrevNS) {
  6226. assert(*IsInline != PrevNS->isInline());
  6227. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  6228. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  6229. // inline namespaces, with the intention of bringing names into namespace std.
  6230. //
  6231. // We support this just well enough to get that case working; this is not
  6232. // sufficient to support reopening namespaces as inline in general.
  6233. if (*IsInline && II && II->getName().startswith("__atomic") &&
  6234. S.getSourceManager().isInSystemHeader(Loc)) {
  6235. // Mark all prior declarations of the namespace as inline.
  6236. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  6237. NS = NS->getPreviousDecl())
  6238. NS->setInline(*IsInline);
  6239. // Patch up the lookup table for the containing namespace. This isn't really
  6240. // correct, but it's good enough for this particular case.
  6241. for (auto *I : PrevNS->decls())
  6242. if (auto *ND = dyn_cast<NamedDecl>(I))
  6243. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  6244. return;
  6245. }
  6246. if (PrevNS->isInline())
  6247. // The user probably just forgot the 'inline', so suggest that it
  6248. // be added back.
  6249. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  6250. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  6251. else
  6252. S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
  6253. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  6254. *IsInline = PrevNS->isInline();
  6255. }
  6256. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  6257. /// definition.
  6258. Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
  6259. SourceLocation InlineLoc,
  6260. SourceLocation NamespaceLoc,
  6261. SourceLocation IdentLoc,
  6262. IdentifierInfo *II,
  6263. SourceLocation LBrace,
  6264. AttributeList *AttrList) {
  6265. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  6266. // For anonymous namespace, take the location of the left brace.
  6267. SourceLocation Loc = II ? IdentLoc : LBrace;
  6268. bool IsInline = InlineLoc.isValid();
  6269. bool IsInvalid = false;
  6270. bool IsStd = false;
  6271. bool AddToKnown = false;
  6272. Scope *DeclRegionScope = NamespcScope->getParent();
  6273. NamespaceDecl *PrevNS = nullptr;
  6274. if (II) {
  6275. // C++ [namespace.def]p2:
  6276. // The identifier in an original-namespace-definition shall not
  6277. // have been previously defined in the declarative region in
  6278. // which the original-namespace-definition appears. The
  6279. // identifier in an original-namespace-definition is the name of
  6280. // the namespace. Subsequently in that declarative region, it is
  6281. // treated as an original-namespace-name.
  6282. //
  6283. // Since namespace names are unique in their scope, and we don't
  6284. // look through using directives, just look for any ordinary names.
  6285. const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
  6286. Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
  6287. Decl::IDNS_Namespace;
  6288. NamedDecl *PrevDecl = nullptr;
  6289. DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
  6290. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  6291. ++I) {
  6292. if ((*I)->getIdentifierNamespace() & IDNS) {
  6293. PrevDecl = *I;
  6294. break;
  6295. }
  6296. }
  6297. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  6298. if (PrevNS) {
  6299. // This is an extended namespace definition.
  6300. if (IsInline != PrevNS->isInline())
  6301. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  6302. &IsInline, PrevNS);
  6303. } else if (PrevDecl) {
  6304. // This is an invalid name redefinition.
  6305. Diag(Loc, diag::err_redefinition_different_kind)
  6306. << II;
  6307. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  6308. IsInvalid = true;
  6309. // Continue on to push Namespc as current DeclContext and return it.
  6310. } else if (II->isStr("std") &&
  6311. CurContext->getRedeclContext()->isTranslationUnit()) {
  6312. // This is the first "real" definition of the namespace "std", so update
  6313. // our cache of the "std" namespace to point at this definition.
  6314. PrevNS = getStdNamespace();
  6315. IsStd = true;
  6316. AddToKnown = !IsInline;
  6317. } else {
  6318. // We've seen this namespace for the first time.
  6319. AddToKnown = !IsInline;
  6320. }
  6321. } else {
  6322. // Anonymous namespaces.
  6323. // Determine whether the parent already has an anonymous namespace.
  6324. DeclContext *Parent = CurContext->getRedeclContext();
  6325. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  6326. PrevNS = TU->getAnonymousNamespace();
  6327. } else {
  6328. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  6329. PrevNS = ND->getAnonymousNamespace();
  6330. }
  6331. if (PrevNS && IsInline != PrevNS->isInline())
  6332. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  6333. &IsInline, PrevNS);
  6334. }
  6335. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  6336. StartLoc, Loc, II, PrevNS);
  6337. if (IsInvalid)
  6338. Namespc->setInvalidDecl();
  6339. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  6340. // FIXME: Should we be merging attributes?
  6341. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  6342. PushNamespaceVisibilityAttr(Attr, Loc);
  6343. if (IsStd)
  6344. StdNamespace = Namespc;
  6345. if (AddToKnown)
  6346. KnownNamespaces[Namespc] = false;
  6347. if (II) {
  6348. PushOnScopeChains(Namespc, DeclRegionScope);
  6349. } else {
  6350. // Link the anonymous namespace into its parent.
  6351. DeclContext *Parent = CurContext->getRedeclContext();
  6352. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  6353. TU->setAnonymousNamespace(Namespc);
  6354. } else {
  6355. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  6356. }
  6357. CurContext->addDecl(Namespc);
  6358. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  6359. // behaves as if it were replaced by
  6360. // namespace unique { /* empty body */ }
  6361. // using namespace unique;
  6362. // namespace unique { namespace-body }
  6363. // where all occurrences of 'unique' in a translation unit are
  6364. // replaced by the same identifier and this identifier differs
  6365. // from all other identifiers in the entire program.
  6366. // We just create the namespace with an empty name and then add an
  6367. // implicit using declaration, just like the standard suggests.
  6368. //
  6369. // CodeGen enforces the "universally unique" aspect by giving all
  6370. // declarations semantically contained within an anonymous
  6371. // namespace internal linkage.
  6372. if (!PrevNS) {
  6373. UsingDirectiveDecl* UD
  6374. = UsingDirectiveDecl::Create(Context, Parent,
  6375. /* 'using' */ LBrace,
  6376. /* 'namespace' */ SourceLocation(),
  6377. /* qualifier */ NestedNameSpecifierLoc(),
  6378. /* identifier */ SourceLocation(),
  6379. Namespc,
  6380. /* Ancestor */ Parent);
  6381. UD->setImplicit();
  6382. Parent->addDecl(UD);
  6383. }
  6384. }
  6385. ActOnDocumentableDecl(Namespc);
  6386. // Although we could have an invalid decl (i.e. the namespace name is a
  6387. // redefinition), push it as current DeclContext and try to continue parsing.
  6388. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  6389. // for the namespace has the declarations that showed up in that particular
  6390. // namespace definition.
  6391. PushDeclContext(NamespcScope, Namespc);
  6392. return Namespc;
  6393. }
  6394. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  6395. /// is a namespace alias, returns the namespace it points to.
  6396. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  6397. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  6398. return AD->getNamespace();
  6399. return dyn_cast_or_null<NamespaceDecl>(D);
  6400. }
  6401. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  6402. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  6403. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  6404. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  6405. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  6406. Namespc->setRBraceLoc(RBrace);
  6407. PopDeclContext();
  6408. if (Namespc->hasAttr<VisibilityAttr>())
  6409. PopPragmaVisibility(true, RBrace);
  6410. }
  6411. CXXRecordDecl *Sema::getStdBadAlloc() const {
  6412. return cast_or_null<CXXRecordDecl>(
  6413. StdBadAlloc.get(Context.getExternalSource()));
  6414. }
  6415. NamespaceDecl *Sema::getStdNamespace() const {
  6416. return cast_or_null<NamespaceDecl>(
  6417. StdNamespace.get(Context.getExternalSource()));
  6418. }
  6419. /// \brief Retrieve the special "std" namespace, which may require us to
  6420. /// implicitly define the namespace.
  6421. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  6422. if (!StdNamespace) {
  6423. // The "std" namespace has not yet been defined, so build one implicitly.
  6424. StdNamespace = NamespaceDecl::Create(Context,
  6425. Context.getTranslationUnitDecl(),
  6426. /*Inline=*/false,
  6427. SourceLocation(), SourceLocation(),
  6428. &PP.getIdentifierTable().get("std"),
  6429. /*PrevDecl=*/nullptr);
  6430. getStdNamespace()->setImplicit(true);
  6431. }
  6432. return getStdNamespace();
  6433. }
  6434. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  6435. assert(getLangOpts().CPlusPlus &&
  6436. "Looking for std::initializer_list outside of C++.");
  6437. // We're looking for implicit instantiations of
  6438. // template <typename E> class std::initializer_list.
  6439. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  6440. return false;
  6441. ClassTemplateDecl *Template = nullptr;
  6442. const TemplateArgument *Arguments = nullptr;
  6443. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  6444. ClassTemplateSpecializationDecl *Specialization =
  6445. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  6446. if (!Specialization)
  6447. return false;
  6448. Template = Specialization->getSpecializedTemplate();
  6449. Arguments = Specialization->getTemplateArgs().data();
  6450. } else if (const TemplateSpecializationType *TST =
  6451. Ty->getAs<TemplateSpecializationType>()) {
  6452. Template = dyn_cast_or_null<ClassTemplateDecl>(
  6453. TST->getTemplateName().getAsTemplateDecl());
  6454. Arguments = TST->getArgs();
  6455. }
  6456. if (!Template)
  6457. return false;
  6458. if (!StdInitializerList) {
  6459. // Haven't recognized std::initializer_list yet, maybe this is it.
  6460. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  6461. if (TemplateClass->getIdentifier() !=
  6462. &PP.getIdentifierTable().get("initializer_list") ||
  6463. !getStdNamespace()->InEnclosingNamespaceSetOf(
  6464. TemplateClass->getDeclContext()))
  6465. return false;
  6466. // This is a template called std::initializer_list, but is it the right
  6467. // template?
  6468. TemplateParameterList *Params = Template->getTemplateParameters();
  6469. if (Params->getMinRequiredArguments() != 1)
  6470. return false;
  6471. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  6472. return false;
  6473. // It's the right template.
  6474. StdInitializerList = Template;
  6475. }
  6476. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  6477. return false;
  6478. // This is an instance of std::initializer_list. Find the argument type.
  6479. if (Element)
  6480. *Element = Arguments[0].getAsType();
  6481. return true;
  6482. }
  6483. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  6484. NamespaceDecl *Std = S.getStdNamespace();
  6485. if (!Std) {
  6486. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  6487. return nullptr;
  6488. }
  6489. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  6490. Loc, Sema::LookupOrdinaryName);
  6491. if (!S.LookupQualifiedName(Result, Std)) {
  6492. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  6493. return nullptr;
  6494. }
  6495. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  6496. if (!Template) {
  6497. Result.suppressDiagnostics();
  6498. // We found something weird. Complain about the first thing we found.
  6499. NamedDecl *Found = *Result.begin();
  6500. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  6501. return nullptr;
  6502. }
  6503. // We found some template called std::initializer_list. Now verify that it's
  6504. // correct.
  6505. TemplateParameterList *Params = Template->getTemplateParameters();
  6506. if (Params->getMinRequiredArguments() != 1 ||
  6507. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  6508. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  6509. return nullptr;
  6510. }
  6511. return Template;
  6512. }
  6513. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  6514. if (!StdInitializerList) {
  6515. StdInitializerList = LookupStdInitializerList(*this, Loc);
  6516. if (!StdInitializerList)
  6517. return QualType();
  6518. }
  6519. TemplateArgumentListInfo Args(Loc, Loc);
  6520. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  6521. Context.getTrivialTypeSourceInfo(Element,
  6522. Loc)));
  6523. return Context.getCanonicalType(
  6524. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  6525. }
  6526. bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
  6527. // C++ [dcl.init.list]p2:
  6528. // A constructor is an initializer-list constructor if its first parameter
  6529. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  6530. // std::initializer_list<E> for some type E, and either there are no other
  6531. // parameters or else all other parameters have default arguments.
  6532. if (Ctor->getNumParams() < 1 ||
  6533. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  6534. return false;
  6535. QualType ArgType = Ctor->getParamDecl(0)->getType();
  6536. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  6537. ArgType = RT->getPointeeType().getUnqualifiedType();
  6538. return isStdInitializerList(ArgType, nullptr);
  6539. }
  6540. /// \brief Determine whether a using statement is in a context where it will be
  6541. /// apply in all contexts.
  6542. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  6543. switch (CurContext->getDeclKind()) {
  6544. case Decl::TranslationUnit:
  6545. return true;
  6546. case Decl::LinkageSpec:
  6547. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  6548. default:
  6549. return false;
  6550. }
  6551. }
  6552. namespace {
  6553. // Callback to only accept typo corrections that are namespaces.
  6554. class NamespaceValidatorCCC : public CorrectionCandidateCallback {
  6555. public:
  6556. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6557. if (NamedDecl *ND = candidate.getCorrectionDecl())
  6558. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  6559. return false;
  6560. }
  6561. };
  6562. }
  6563. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  6564. CXXScopeSpec &SS,
  6565. SourceLocation IdentLoc,
  6566. IdentifierInfo *Ident) {
  6567. R.clear();
  6568. if (TypoCorrection Corrected =
  6569. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
  6570. llvm::make_unique<NamespaceValidatorCCC>(),
  6571. Sema::CTK_ErrorRecovery)) {
  6572. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  6573. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  6574. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  6575. Ident->getName().equals(CorrectedStr);
  6576. S.diagnoseTypo(Corrected,
  6577. S.PDiag(diag::err_using_directive_member_suggest)
  6578. << Ident << DC << DroppedSpecifier << SS.getRange(),
  6579. S.PDiag(diag::note_namespace_defined_here));
  6580. } else {
  6581. S.diagnoseTypo(Corrected,
  6582. S.PDiag(diag::err_using_directive_suggest) << Ident,
  6583. S.PDiag(diag::note_namespace_defined_here));
  6584. }
  6585. R.addDecl(Corrected.getCorrectionDecl());
  6586. return true;
  6587. }
  6588. return false;
  6589. }
  6590. Decl *Sema::ActOnUsingDirective(Scope *S,
  6591. SourceLocation UsingLoc,
  6592. SourceLocation NamespcLoc,
  6593. CXXScopeSpec &SS,
  6594. SourceLocation IdentLoc,
  6595. IdentifierInfo *NamespcName,
  6596. AttributeList *AttrList) {
  6597. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  6598. assert(NamespcName && "Invalid NamespcName.");
  6599. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  6600. // This can only happen along a recovery path.
  6601. while (S->getFlags() & Scope::TemplateParamScope)
  6602. S = S->getParent();
  6603. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  6604. UsingDirectiveDecl *UDir = nullptr;
  6605. NestedNameSpecifier *Qualifier = nullptr;
  6606. if (SS.isSet())
  6607. Qualifier = SS.getScopeRep();
  6608. // Lookup namespace name.
  6609. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  6610. LookupParsedName(R, S, &SS);
  6611. if (R.isAmbiguous())
  6612. return nullptr;
  6613. if (R.empty()) {
  6614. R.clear();
  6615. // Allow "using namespace std;" or "using namespace ::std;" even if
  6616. // "std" hasn't been defined yet, for GCC compatibility.
  6617. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  6618. NamespcName->isStr("std")) {
  6619. Diag(IdentLoc, diag::ext_using_undefined_std);
  6620. R.addDecl(getOrCreateStdNamespace());
  6621. R.resolveKind();
  6622. }
  6623. // Otherwise, attempt typo correction.
  6624. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  6625. }
  6626. if (!R.empty()) {
  6627. NamedDecl *Named = R.getFoundDecl();
  6628. assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
  6629. && "expected namespace decl");
  6630. // The use of a nested name specifier may trigger deprecation warnings.
  6631. DiagnoseUseOfDecl(Named, IdentLoc);
  6632. // C++ [namespace.udir]p1:
  6633. // A using-directive specifies that the names in the nominated
  6634. // namespace can be used in the scope in which the
  6635. // using-directive appears after the using-directive. During
  6636. // unqualified name lookup (3.4.1), the names appear as if they
  6637. // were declared in the nearest enclosing namespace which
  6638. // contains both the using-directive and the nominated
  6639. // namespace. [Note: in this context, "contains" means "contains
  6640. // directly or indirectly". ]
  6641. // Find enclosing context containing both using-directive and
  6642. // nominated namespace.
  6643. NamespaceDecl *NS = getNamespaceDecl(Named);
  6644. DeclContext *CommonAncestor = cast<DeclContext>(NS);
  6645. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  6646. CommonAncestor = CommonAncestor->getParent();
  6647. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  6648. SS.getWithLocInContext(Context),
  6649. IdentLoc, Named, CommonAncestor);
  6650. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  6651. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  6652. Diag(IdentLoc, diag::warn_using_directive_in_header);
  6653. }
  6654. PushUsingDirective(S, UDir);
  6655. } else {
  6656. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  6657. }
  6658. if (UDir)
  6659. ProcessDeclAttributeList(S, UDir, AttrList);
  6660. return UDir;
  6661. }
  6662. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  6663. // If the scope has an associated entity and the using directive is at
  6664. // namespace or translation unit scope, add the UsingDirectiveDecl into
  6665. // its lookup structure so qualified name lookup can find it.
  6666. DeclContext *Ctx = S->getEntity();
  6667. if (Ctx && !Ctx->isFunctionOrMethod())
  6668. Ctx->addDecl(UDir);
  6669. else
  6670. // Otherwise, it is at block scope. The using-directives will affect lookup
  6671. // only to the end of the scope.
  6672. S->PushUsingDirective(UDir);
  6673. }
  6674. Decl *Sema::ActOnUsingDeclaration(Scope *S,
  6675. AccessSpecifier AS,
  6676. bool HasUsingKeyword,
  6677. SourceLocation UsingLoc,
  6678. CXXScopeSpec &SS,
  6679. UnqualifiedId &Name,
  6680. AttributeList *AttrList,
  6681. bool HasTypenameKeyword,
  6682. SourceLocation TypenameLoc) {
  6683. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  6684. switch (Name.getKind()) {
  6685. case UnqualifiedId::IK_ImplicitSelfParam:
  6686. case UnqualifiedId::IK_Identifier:
  6687. case UnqualifiedId::IK_OperatorFunctionId:
  6688. case UnqualifiedId::IK_LiteralOperatorId:
  6689. case UnqualifiedId::IK_ConversionFunctionId:
  6690. break;
  6691. case UnqualifiedId::IK_ConstructorName:
  6692. case UnqualifiedId::IK_ConstructorTemplateId:
  6693. // C++11 inheriting constructors.
  6694. Diag(Name.getLocStart(),
  6695. getLangOpts().CPlusPlus11 ?
  6696. diag::warn_cxx98_compat_using_decl_constructor :
  6697. diag::err_using_decl_constructor)
  6698. << SS.getRange();
  6699. if (getLangOpts().CPlusPlus11) break;
  6700. return nullptr;
  6701. case UnqualifiedId::IK_DestructorName:
  6702. Diag(Name.getLocStart(), diag::err_using_decl_destructor)
  6703. << SS.getRange();
  6704. return nullptr;
  6705. case UnqualifiedId::IK_TemplateId:
  6706. Diag(Name.getLocStart(), diag::err_using_decl_template_id)
  6707. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  6708. return nullptr;
  6709. }
  6710. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  6711. DeclarationName TargetName = TargetNameInfo.getName();
  6712. if (!TargetName)
  6713. return nullptr;
  6714. // Warn about access declarations.
  6715. if (!HasUsingKeyword) {
  6716. Diag(Name.getLocStart(),
  6717. getLangOpts().CPlusPlus11 ? diag::err_access_decl
  6718. : diag::warn_access_decl_deprecated)
  6719. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  6720. }
  6721. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  6722. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  6723. return nullptr;
  6724. NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
  6725. TargetNameInfo, AttrList,
  6726. /* IsInstantiation */ false,
  6727. HasTypenameKeyword, TypenameLoc);
  6728. if (UD)
  6729. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  6730. return UD;
  6731. }
  6732. /// \brief Determine whether a using declaration considers the given
  6733. /// declarations as "equivalent", e.g., if they are redeclarations of
  6734. /// the same entity or are both typedefs of the same type.
  6735. static bool
  6736. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  6737. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  6738. return true;
  6739. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  6740. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  6741. return Context.hasSameType(TD1->getUnderlyingType(),
  6742. TD2->getUnderlyingType());
  6743. return false;
  6744. }
  6745. /// Determines whether to create a using shadow decl for a particular
  6746. /// decl, given the set of decls existing prior to this using lookup.
  6747. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  6748. const LookupResult &Previous,
  6749. UsingShadowDecl *&PrevShadow) {
  6750. // Diagnose finding a decl which is not from a base class of the
  6751. // current class. We do this now because there are cases where this
  6752. // function will silently decide not to build a shadow decl, which
  6753. // will pre-empt further diagnostics.
  6754. //
  6755. // We don't need to do this in C++0x because we do the check once on
  6756. // the qualifier.
  6757. //
  6758. // FIXME: diagnose the following if we care enough:
  6759. // struct A { int foo; };
  6760. // struct B : A { using A::foo; };
  6761. // template <class T> struct C : A {};
  6762. // template <class T> struct D : C<T> { using B::foo; } // <---
  6763. // This is invalid (during instantiation) in C++03 because B::foo
  6764. // resolves to the using decl in B, which is not a base class of D<T>.
  6765. // We can't diagnose it immediately because C<T> is an unknown
  6766. // specialization. The UsingShadowDecl in D<T> then points directly
  6767. // to A::foo, which will look well-formed when we instantiate.
  6768. // The right solution is to not collapse the shadow-decl chain.
  6769. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  6770. DeclContext *OrigDC = Orig->getDeclContext();
  6771. // Handle enums and anonymous structs.
  6772. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  6773. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  6774. while (OrigRec->isAnonymousStructOrUnion())
  6775. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  6776. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  6777. if (OrigDC == CurContext) {
  6778. Diag(Using->getLocation(),
  6779. diag::err_using_decl_nested_name_specifier_is_current_class)
  6780. << Using->getQualifierLoc().getSourceRange();
  6781. Diag(Orig->getLocation(), diag::note_using_decl_target);
  6782. return true;
  6783. }
  6784. Diag(Using->getQualifierLoc().getBeginLoc(),
  6785. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  6786. << Using->getQualifier()
  6787. << cast<CXXRecordDecl>(CurContext)
  6788. << Using->getQualifierLoc().getSourceRange();
  6789. Diag(Orig->getLocation(), diag::note_using_decl_target);
  6790. return true;
  6791. }
  6792. }
  6793. if (Previous.empty()) return false;
  6794. NamedDecl *Target = Orig;
  6795. if (isa<UsingShadowDecl>(Target))
  6796. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  6797. // If the target happens to be one of the previous declarations, we
  6798. // don't have a conflict.
  6799. //
  6800. // FIXME: but we might be increasing its access, in which case we
  6801. // should redeclare it.
  6802. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  6803. bool FoundEquivalentDecl = false;
  6804. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6805. I != E; ++I) {
  6806. NamedDecl *D = (*I)->getUnderlyingDecl();
  6807. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  6808. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  6809. PrevShadow = Shadow;
  6810. FoundEquivalentDecl = true;
  6811. }
  6812. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  6813. }
  6814. if (FoundEquivalentDecl)
  6815. return false;
  6816. if (FunctionDecl *FD = Target->getAsFunction()) {
  6817. NamedDecl *OldDecl = nullptr;
  6818. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  6819. /*IsForUsingDecl*/ true)) {
  6820. case Ovl_Overload:
  6821. return false;
  6822. case Ovl_NonFunction:
  6823. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  6824. break;
  6825. // We found a decl with the exact signature.
  6826. case Ovl_Match:
  6827. // If we're in a record, we want to hide the target, so we
  6828. // return true (without a diagnostic) to tell the caller not to
  6829. // build a shadow decl.
  6830. if (CurContext->isRecord())
  6831. return true;
  6832. // If we're not in a record, this is an error.
  6833. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  6834. break;
  6835. }
  6836. Diag(Target->getLocation(), diag::note_using_decl_target);
  6837. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  6838. return true;
  6839. }
  6840. // Target is not a function.
  6841. if (isa<TagDecl>(Target)) {
  6842. // No conflict between a tag and a non-tag.
  6843. if (!Tag) return false;
  6844. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  6845. Diag(Target->getLocation(), diag::note_using_decl_target);
  6846. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  6847. return true;
  6848. }
  6849. // No conflict between a tag and a non-tag.
  6850. if (!NonTag) return false;
  6851. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  6852. Diag(Target->getLocation(), diag::note_using_decl_target);
  6853. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  6854. return true;
  6855. }
  6856. /// Builds a shadow declaration corresponding to a 'using' declaration.
  6857. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  6858. UsingDecl *UD,
  6859. NamedDecl *Orig,
  6860. UsingShadowDecl *PrevDecl) {
  6861. // If we resolved to another shadow declaration, just coalesce them.
  6862. NamedDecl *Target = Orig;
  6863. if (isa<UsingShadowDecl>(Target)) {
  6864. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  6865. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  6866. }
  6867. UsingShadowDecl *Shadow
  6868. = UsingShadowDecl::Create(Context, CurContext,
  6869. UD->getLocation(), UD, Target);
  6870. UD->addShadowDecl(Shadow);
  6871. Shadow->setAccess(UD->getAccess());
  6872. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  6873. Shadow->setInvalidDecl();
  6874. Shadow->setPreviousDecl(PrevDecl);
  6875. if (S)
  6876. PushOnScopeChains(Shadow, S);
  6877. else
  6878. CurContext->addDecl(Shadow);
  6879. return Shadow;
  6880. }
  6881. /// Hides a using shadow declaration. This is required by the current
  6882. /// using-decl implementation when a resolvable using declaration in a
  6883. /// class is followed by a declaration which would hide or override
  6884. /// one or more of the using decl's targets; for example:
  6885. ///
  6886. /// struct Base { void foo(int); };
  6887. /// struct Derived : Base {
  6888. /// using Base::foo;
  6889. /// void foo(int);
  6890. /// };
  6891. ///
  6892. /// The governing language is C++03 [namespace.udecl]p12:
  6893. ///
  6894. /// When a using-declaration brings names from a base class into a
  6895. /// derived class scope, member functions in the derived class
  6896. /// override and/or hide member functions with the same name and
  6897. /// parameter types in a base class (rather than conflicting).
  6898. ///
  6899. /// There are two ways to implement this:
  6900. /// (1) optimistically create shadow decls when they're not hidden
  6901. /// by existing declarations, or
  6902. /// (2) don't create any shadow decls (or at least don't make them
  6903. /// visible) until we've fully parsed/instantiated the class.
  6904. /// The problem with (1) is that we might have to retroactively remove
  6905. /// a shadow decl, which requires several O(n) operations because the
  6906. /// decl structures are (very reasonably) not designed for removal.
  6907. /// (2) avoids this but is very fiddly and phase-dependent.
  6908. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  6909. if (Shadow->getDeclName().getNameKind() ==
  6910. DeclarationName::CXXConversionFunctionName)
  6911. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  6912. // Remove it from the DeclContext...
  6913. Shadow->getDeclContext()->removeDecl(Shadow);
  6914. // ...and the scope, if applicable...
  6915. if (S) {
  6916. S->RemoveDecl(Shadow);
  6917. IdResolver.RemoveDecl(Shadow);
  6918. }
  6919. // ...and the using decl.
  6920. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  6921. // TODO: complain somehow if Shadow was used. It shouldn't
  6922. // be possible for this to happen, because...?
  6923. }
  6924. /// Find the base specifier for a base class with the given type.
  6925. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  6926. QualType DesiredBase,
  6927. bool &AnyDependentBases) {
  6928. // Check whether the named type is a direct base class.
  6929. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
  6930. for (auto &Base : Derived->bases()) {
  6931. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  6932. if (CanonicalDesiredBase == BaseType)
  6933. return &Base;
  6934. if (BaseType->isDependentType())
  6935. AnyDependentBases = true;
  6936. }
  6937. return nullptr;
  6938. }
  6939. namespace {
  6940. class UsingValidatorCCC : public CorrectionCandidateCallback {
  6941. public:
  6942. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  6943. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  6944. : HasTypenameKeyword(HasTypenameKeyword),
  6945. IsInstantiation(IsInstantiation), OldNNS(NNS),
  6946. RequireMemberOf(RequireMemberOf) {}
  6947. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  6948. NamedDecl *ND = Candidate.getCorrectionDecl();
  6949. // Keywords are not valid here.
  6950. if (!ND || isa<NamespaceDecl>(ND))
  6951. return false;
  6952. // Completely unqualified names are invalid for a 'using' declaration.
  6953. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  6954. return false;
  6955. if (RequireMemberOf) {
  6956. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  6957. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  6958. // No-one ever wants a using-declaration to name an injected-class-name
  6959. // of a base class, unless they're declaring an inheriting constructor.
  6960. ASTContext &Ctx = ND->getASTContext();
  6961. if (!Ctx.getLangOpts().CPlusPlus11)
  6962. return false;
  6963. QualType FoundType = Ctx.getRecordType(FoundRecord);
  6964. // Check that the injected-class-name is named as a member of its own
  6965. // type; we don't want to suggest 'using Derived::Base;', since that
  6966. // means something else.
  6967. NestedNameSpecifier *Specifier =
  6968. Candidate.WillReplaceSpecifier()
  6969. ? Candidate.getCorrectionSpecifier()
  6970. : OldNNS;
  6971. if (!Specifier->getAsType() ||
  6972. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  6973. return false;
  6974. // Check that this inheriting constructor declaration actually names a
  6975. // direct base class of the current class.
  6976. bool AnyDependentBases = false;
  6977. if (!findDirectBaseWithType(RequireMemberOf,
  6978. Ctx.getRecordType(FoundRecord),
  6979. AnyDependentBases) &&
  6980. !AnyDependentBases)
  6981. return false;
  6982. } else {
  6983. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  6984. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  6985. return false;
  6986. // FIXME: Check that the base class member is accessible?
  6987. }
  6988. }
  6989. if (isa<TypeDecl>(ND))
  6990. return HasTypenameKeyword || !IsInstantiation;
  6991. return !HasTypenameKeyword;
  6992. }
  6993. private:
  6994. bool HasTypenameKeyword;
  6995. bool IsInstantiation;
  6996. NestedNameSpecifier *OldNNS;
  6997. CXXRecordDecl *RequireMemberOf;
  6998. };
  6999. } // end anonymous namespace
  7000. /// Builds a using declaration.
  7001. ///
  7002. /// \param IsInstantiation - Whether this call arises from an
  7003. /// instantiation of an unresolved using declaration. We treat
  7004. /// the lookup differently for these declarations.
  7005. NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
  7006. SourceLocation UsingLoc,
  7007. CXXScopeSpec &SS,
  7008. DeclarationNameInfo NameInfo,
  7009. AttributeList *AttrList,
  7010. bool IsInstantiation,
  7011. bool HasTypenameKeyword,
  7012. SourceLocation TypenameLoc) {
  7013. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  7014. SourceLocation IdentLoc = NameInfo.getLoc();
  7015. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  7016. // FIXME: We ignore attributes for now.
  7017. if (SS.isEmpty()) {
  7018. Diag(IdentLoc, diag::err_using_requires_qualname);
  7019. return nullptr;
  7020. }
  7021. // Do the redeclaration lookup in the current scope.
  7022. LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
  7023. ForRedeclaration);
  7024. Previous.setHideTags(false);
  7025. if (S) {
  7026. LookupName(Previous, S);
  7027. // It is really dumb that we have to do this.
  7028. LookupResult::Filter F = Previous.makeFilter();
  7029. while (F.hasNext()) {
  7030. NamedDecl *D = F.next();
  7031. if (!isDeclInScope(D, CurContext, S))
  7032. F.erase();
  7033. // If we found a local extern declaration that's not ordinarily visible,
  7034. // and this declaration is being added to a non-block scope, ignore it.
  7035. // We're only checking for scope conflicts here, not also for violations
  7036. // of the linkage rules.
  7037. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  7038. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  7039. F.erase();
  7040. }
  7041. F.done();
  7042. } else {
  7043. assert(IsInstantiation && "no scope in non-instantiation");
  7044. assert(CurContext->isRecord() && "scope not record in instantiation");
  7045. LookupQualifiedName(Previous, CurContext);
  7046. }
  7047. // Check for invalid redeclarations.
  7048. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  7049. SS, IdentLoc, Previous))
  7050. return nullptr;
  7051. // Check for bad qualifiers.
  7052. if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
  7053. return nullptr;
  7054. DeclContext *LookupContext = computeDeclContext(SS);
  7055. NamedDecl *D;
  7056. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  7057. if (!LookupContext) {
  7058. if (HasTypenameKeyword) {
  7059. // FIXME: not all declaration name kinds are legal here
  7060. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  7061. UsingLoc, TypenameLoc,
  7062. QualifierLoc,
  7063. IdentLoc, NameInfo.getName());
  7064. } else {
  7065. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  7066. QualifierLoc, NameInfo);
  7067. }
  7068. D->setAccess(AS);
  7069. CurContext->addDecl(D);
  7070. return D;
  7071. }
  7072. auto Build = [&](bool Invalid) {
  7073. UsingDecl *UD =
  7074. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
  7075. HasTypenameKeyword);
  7076. UD->setAccess(AS);
  7077. CurContext->addDecl(UD);
  7078. UD->setInvalidDecl(Invalid);
  7079. return UD;
  7080. };
  7081. auto BuildInvalid = [&]{ return Build(true); };
  7082. auto BuildValid = [&]{ return Build(false); };
  7083. if (RequireCompleteDeclContext(SS, LookupContext))
  7084. return BuildInvalid();
  7085. // Look up the target name.
  7086. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  7087. // Unlike most lookups, we don't always want to hide tag
  7088. // declarations: tag names are visible through the using declaration
  7089. // even if hidden by ordinary names, *except* in a dependent context
  7090. // where it's important for the sanity of two-phase lookup.
  7091. if (!IsInstantiation)
  7092. R.setHideTags(false);
  7093. // For the purposes of this lookup, we have a base object type
  7094. // equal to that of the current context.
  7095. if (CurContext->isRecord()) {
  7096. R.setBaseObjectType(
  7097. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  7098. }
  7099. LookupQualifiedName(R, LookupContext);
  7100. // Try to correct typos if possible. If constructor name lookup finds no
  7101. // results, that means the named class has no explicit constructors, and we
  7102. // suppressed declaring implicit ones (probably because it's dependent or
  7103. // invalid).
  7104. if (R.empty() &&
  7105. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  7106. if (TypoCorrection Corrected = CorrectTypo(
  7107. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  7108. llvm::make_unique<UsingValidatorCCC>(
  7109. HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  7110. dyn_cast<CXXRecordDecl>(CurContext)),
  7111. CTK_ErrorRecovery)) {
  7112. // We reject any correction for which ND would be NULL.
  7113. NamedDecl *ND = Corrected.getCorrectionDecl();
  7114. // We reject candidates where DroppedSpecifier == true, hence the
  7115. // literal '0' below.
  7116. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  7117. << NameInfo.getName() << LookupContext << 0
  7118. << SS.getRange());
  7119. // If we corrected to an inheriting constructor, handle it as one.
  7120. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  7121. if (RD && RD->isInjectedClassName()) {
  7122. // Fix up the information we'll use to build the using declaration.
  7123. if (Corrected.WillReplaceSpecifier()) {
  7124. NestedNameSpecifierLocBuilder Builder;
  7125. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  7126. QualifierLoc.getSourceRange());
  7127. QualifierLoc = Builder.getWithLocInContext(Context);
  7128. }
  7129. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  7130. Context.getCanonicalType(Context.getRecordType(RD))));
  7131. NameInfo.setNamedTypeInfo(nullptr);
  7132. for (auto *Ctor : LookupConstructors(RD))
  7133. R.addDecl(Ctor);
  7134. } else {
  7135. // FIXME: Pick up all the declarations if we found an overloaded function.
  7136. R.addDecl(ND);
  7137. }
  7138. } else {
  7139. Diag(IdentLoc, diag::err_no_member)
  7140. << NameInfo.getName() << LookupContext << SS.getRange();
  7141. return BuildInvalid();
  7142. }
  7143. }
  7144. if (R.isAmbiguous())
  7145. return BuildInvalid();
  7146. if (HasTypenameKeyword) {
  7147. // If we asked for a typename and got a non-type decl, error out.
  7148. if (!R.getAsSingle<TypeDecl>()) {
  7149. Diag(IdentLoc, diag::err_using_typename_non_type);
  7150. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  7151. Diag((*I)->getUnderlyingDecl()->getLocation(),
  7152. diag::note_using_decl_target);
  7153. return BuildInvalid();
  7154. }
  7155. } else {
  7156. // If we asked for a non-typename and we got a type, error out,
  7157. // but only if this is an instantiation of an unresolved using
  7158. // decl. Otherwise just silently find the type name.
  7159. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  7160. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  7161. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  7162. return BuildInvalid();
  7163. }
  7164. }
  7165. // C++0x N2914 [namespace.udecl]p6:
  7166. // A using-declaration shall not name a namespace.
  7167. if (R.getAsSingle<NamespaceDecl>()) {
  7168. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  7169. << SS.getRange();
  7170. return BuildInvalid();
  7171. }
  7172. UsingDecl *UD = BuildValid();
  7173. // The normal rules do not apply to inheriting constructor declarations.
  7174. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
  7175. // Suppress access diagnostics; the access check is instead performed at the
  7176. // point of use for an inheriting constructor.
  7177. R.suppressDiagnostics();
  7178. CheckInheritingConstructorUsingDecl(UD);
  7179. return UD;
  7180. }
  7181. // Otherwise, look up the target name.
  7182. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  7183. UsingShadowDecl *PrevDecl = nullptr;
  7184. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  7185. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  7186. }
  7187. return UD;
  7188. }
  7189. /// Additional checks for a using declaration referring to a constructor name.
  7190. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  7191. assert(!UD->hasTypename() && "expecting a constructor name");
  7192. const Type *SourceType = UD->getQualifier()->getAsType();
  7193. assert(SourceType &&
  7194. "Using decl naming constructor doesn't have type in scope spec.");
  7195. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  7196. // Check whether the named type is a direct base class.
  7197. bool AnyDependentBases = false;
  7198. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  7199. AnyDependentBases);
  7200. if (!Base && !AnyDependentBases) {
  7201. Diag(UD->getUsingLoc(),
  7202. diag::err_using_decl_constructor_not_in_direct_base)
  7203. << UD->getNameInfo().getSourceRange()
  7204. << QualType(SourceType, 0) << TargetClass;
  7205. UD->setInvalidDecl();
  7206. return true;
  7207. }
  7208. if (Base)
  7209. Base->setInheritConstructors();
  7210. return false;
  7211. }
  7212. /// Checks that the given using declaration is not an invalid
  7213. /// redeclaration. Note that this is checking only for the using decl
  7214. /// itself, not for any ill-formedness among the UsingShadowDecls.
  7215. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  7216. bool HasTypenameKeyword,
  7217. const CXXScopeSpec &SS,
  7218. SourceLocation NameLoc,
  7219. const LookupResult &Prev) {
  7220. // C++03 [namespace.udecl]p8:
  7221. // C++0x [namespace.udecl]p10:
  7222. // A using-declaration is a declaration and can therefore be used
  7223. // repeatedly where (and only where) multiple declarations are
  7224. // allowed.
  7225. //
  7226. // That's in non-member contexts.
  7227. if (!CurContext->getRedeclContext()->isRecord())
  7228. return false;
  7229. NestedNameSpecifier *Qual = SS.getScopeRep();
  7230. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  7231. NamedDecl *D = *I;
  7232. bool DTypename;
  7233. NestedNameSpecifier *DQual;
  7234. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  7235. DTypename = UD->hasTypename();
  7236. DQual = UD->getQualifier();
  7237. } else if (UnresolvedUsingValueDecl *UD
  7238. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  7239. DTypename = false;
  7240. DQual = UD->getQualifier();
  7241. } else if (UnresolvedUsingTypenameDecl *UD
  7242. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  7243. DTypename = true;
  7244. DQual = UD->getQualifier();
  7245. } else continue;
  7246. // using decls differ if one says 'typename' and the other doesn't.
  7247. // FIXME: non-dependent using decls?
  7248. if (HasTypenameKeyword != DTypename) continue;
  7249. // using decls differ if they name different scopes (but note that
  7250. // template instantiation can cause this check to trigger when it
  7251. // didn't before instantiation).
  7252. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  7253. Context.getCanonicalNestedNameSpecifier(DQual))
  7254. continue;
  7255. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  7256. Diag(D->getLocation(), diag::note_using_decl) << 1;
  7257. return true;
  7258. }
  7259. return false;
  7260. }
  7261. /// Checks that the given nested-name qualifier used in a using decl
  7262. /// in the current context is appropriately related to the current
  7263. /// scope. If an error is found, diagnoses it and returns true.
  7264. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  7265. const CXXScopeSpec &SS,
  7266. const DeclarationNameInfo &NameInfo,
  7267. SourceLocation NameLoc) {
  7268. DeclContext *NamedContext = computeDeclContext(SS);
  7269. if (!CurContext->isRecord()) {
  7270. // C++03 [namespace.udecl]p3:
  7271. // C++0x [namespace.udecl]p8:
  7272. // A using-declaration for a class member shall be a member-declaration.
  7273. // If we weren't able to compute a valid scope, it must be a
  7274. // dependent class scope.
  7275. if (!NamedContext || NamedContext->isRecord()) {
  7276. auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
  7277. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  7278. RD = nullptr;
  7279. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  7280. << SS.getRange();
  7281. // If we have a complete, non-dependent source type, try to suggest a
  7282. // way to get the same effect.
  7283. if (!RD)
  7284. return true;
  7285. // Find what this using-declaration was referring to.
  7286. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  7287. R.setHideTags(false);
  7288. R.suppressDiagnostics();
  7289. LookupQualifiedName(R, RD);
  7290. if (R.getAsSingle<TypeDecl>()) {
  7291. if (getLangOpts().CPlusPlus11) {
  7292. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  7293. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  7294. << 0 // alias declaration
  7295. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  7296. NameInfo.getName().getAsString() +
  7297. " = ");
  7298. } else {
  7299. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  7300. SourceLocation InsertLoc =
  7301. PP.getLocForEndOfToken(NameInfo.getLocEnd());
  7302. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  7303. << 1 // typedef declaration
  7304. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  7305. << FixItHint::CreateInsertion(
  7306. InsertLoc, " " + NameInfo.getName().getAsString());
  7307. }
  7308. } else if (R.getAsSingle<VarDecl>()) {
  7309. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  7310. // repeating the type of the static data member here.
  7311. FixItHint FixIt;
  7312. if (getLangOpts().CPlusPlus11) {
  7313. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  7314. FixIt = FixItHint::CreateReplacement(
  7315. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  7316. }
  7317. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  7318. << 2 // reference declaration
  7319. << FixIt;
  7320. }
  7321. return true;
  7322. }
  7323. // Otherwise, everything is known to be fine.
  7324. return false;
  7325. }
  7326. // The current scope is a record.
  7327. // If the named context is dependent, we can't decide much.
  7328. if (!NamedContext) {
  7329. // FIXME: in C++0x, we can diagnose if we can prove that the
  7330. // nested-name-specifier does not refer to a base class, which is
  7331. // still possible in some cases.
  7332. // Otherwise we have to conservatively report that things might be
  7333. // okay.
  7334. return false;
  7335. }
  7336. if (!NamedContext->isRecord()) {
  7337. // Ideally this would point at the last name in the specifier,
  7338. // but we don't have that level of source info.
  7339. Diag(SS.getRange().getBegin(),
  7340. diag::err_using_decl_nested_name_specifier_is_not_class)
  7341. << SS.getScopeRep() << SS.getRange();
  7342. return true;
  7343. }
  7344. if (!NamedContext->isDependentContext() &&
  7345. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  7346. return true;
  7347. if (getLangOpts().CPlusPlus11) {
  7348. // C++0x [namespace.udecl]p3:
  7349. // In a using-declaration used as a member-declaration, the
  7350. // nested-name-specifier shall name a base class of the class
  7351. // being defined.
  7352. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  7353. cast<CXXRecordDecl>(NamedContext))) {
  7354. if (CurContext == NamedContext) {
  7355. Diag(NameLoc,
  7356. diag::err_using_decl_nested_name_specifier_is_current_class)
  7357. << SS.getRange();
  7358. return true;
  7359. }
  7360. Diag(SS.getRange().getBegin(),
  7361. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  7362. << SS.getScopeRep()
  7363. << cast<CXXRecordDecl>(CurContext)
  7364. << SS.getRange();
  7365. return true;
  7366. }
  7367. return false;
  7368. }
  7369. // C++03 [namespace.udecl]p4:
  7370. // A using-declaration used as a member-declaration shall refer
  7371. // to a member of a base class of the class being defined [etc.].
  7372. // Salient point: SS doesn't have to name a base class as long as
  7373. // lookup only finds members from base classes. Therefore we can
  7374. // diagnose here only if we can prove that that can't happen,
  7375. // i.e. if the class hierarchies provably don't intersect.
  7376. // TODO: it would be nice if "definitely valid" results were cached
  7377. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  7378. // need to be repeated.
  7379. struct UserData {
  7380. llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
  7381. static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
  7382. UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
  7383. Data->Bases.insert(Base);
  7384. return true;
  7385. }
  7386. bool hasDependentBases(const CXXRecordDecl *Class) {
  7387. return !Class->forallBases(collect, this);
  7388. }
  7389. /// Returns true if the base is dependent or is one of the
  7390. /// accumulated base classes.
  7391. static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
  7392. UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
  7393. return !Data->Bases.count(Base);
  7394. }
  7395. bool mightShareBases(const CXXRecordDecl *Class) {
  7396. return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
  7397. }
  7398. };
  7399. UserData Data;
  7400. // Returns false if we find a dependent base.
  7401. if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
  7402. return false;
  7403. // Returns false if the class has a dependent base or if it or one
  7404. // of its bases is present in the base set of the current context.
  7405. if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
  7406. return false;
  7407. Diag(SS.getRange().getBegin(),
  7408. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  7409. << SS.getScopeRep()
  7410. << cast<CXXRecordDecl>(CurContext)
  7411. << SS.getRange();
  7412. return true;
  7413. }
  7414. Decl *Sema::ActOnAliasDeclaration(Scope *S,
  7415. AccessSpecifier AS,
  7416. MultiTemplateParamsArg TemplateParamLists,
  7417. SourceLocation UsingLoc,
  7418. UnqualifiedId &Name,
  7419. AttributeList *AttrList,
  7420. TypeResult Type,
  7421. Decl *DeclFromDeclSpec) {
  7422. // Skip up to the relevant declaration scope.
  7423. while (S->getFlags() & Scope::TemplateParamScope)
  7424. S = S->getParent();
  7425. assert((S->getFlags() & Scope::DeclScope) &&
  7426. "got alias-declaration outside of declaration scope");
  7427. if (Type.isInvalid())
  7428. return nullptr;
  7429. bool Invalid = false;
  7430. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  7431. TypeSourceInfo *TInfo = nullptr;
  7432. GetTypeFromParser(Type.get(), &TInfo);
  7433. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  7434. return nullptr;
  7435. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  7436. UPPC_DeclarationType)) {
  7437. Invalid = true;
  7438. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  7439. TInfo->getTypeLoc().getBeginLoc());
  7440. }
  7441. LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
  7442. LookupName(Previous, S);
  7443. // Warn about shadowing the name of a template parameter.
  7444. if (Previous.isSingleResult() &&
  7445. Previous.getFoundDecl()->isTemplateParameter()) {
  7446. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  7447. Previous.clear();
  7448. }
  7449. assert(Name.Kind == UnqualifiedId::IK_Identifier &&
  7450. "name in alias declaration must be an identifier");
  7451. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  7452. Name.StartLocation,
  7453. Name.Identifier, TInfo);
  7454. NewTD->setAccess(AS);
  7455. if (Invalid)
  7456. NewTD->setInvalidDecl();
  7457. ProcessDeclAttributeList(S, NewTD, AttrList);
  7458. CheckTypedefForVariablyModifiedType(S, NewTD);
  7459. Invalid |= NewTD->isInvalidDecl();
  7460. bool Redeclaration = false;
  7461. NamedDecl *NewND;
  7462. if (TemplateParamLists.size()) {
  7463. TypeAliasTemplateDecl *OldDecl = nullptr;
  7464. TemplateParameterList *OldTemplateParams = nullptr;
  7465. if (TemplateParamLists.size() != 1) {
  7466. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  7467. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  7468. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  7469. }
  7470. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  7471. // Only consider previous declarations in the same scope.
  7472. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  7473. /*ExplicitInstantiationOrSpecialization*/false);
  7474. if (!Previous.empty()) {
  7475. Redeclaration = true;
  7476. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  7477. if (!OldDecl && !Invalid) {
  7478. Diag(UsingLoc, diag::err_redefinition_different_kind)
  7479. << Name.Identifier;
  7480. NamedDecl *OldD = Previous.getRepresentativeDecl();
  7481. if (OldD->getLocation().isValid())
  7482. Diag(OldD->getLocation(), diag::note_previous_definition);
  7483. Invalid = true;
  7484. }
  7485. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  7486. if (TemplateParameterListsAreEqual(TemplateParams,
  7487. OldDecl->getTemplateParameters(),
  7488. /*Complain=*/true,
  7489. TPL_TemplateMatch))
  7490. OldTemplateParams = OldDecl->getTemplateParameters();
  7491. else
  7492. Invalid = true;
  7493. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  7494. if (!Invalid &&
  7495. !Context.hasSameType(OldTD->getUnderlyingType(),
  7496. NewTD->getUnderlyingType())) {
  7497. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  7498. // but we can't reasonably accept it.
  7499. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  7500. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  7501. if (OldTD->getLocation().isValid())
  7502. Diag(OldTD->getLocation(), diag::note_previous_definition);
  7503. Invalid = true;
  7504. }
  7505. }
  7506. }
  7507. // Merge any previous default template arguments into our parameters,
  7508. // and check the parameter list.
  7509. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  7510. TPC_TypeAliasTemplate))
  7511. return nullptr;
  7512. TypeAliasTemplateDecl *NewDecl =
  7513. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  7514. Name.Identifier, TemplateParams,
  7515. NewTD);
  7516. NewTD->setDescribedAliasTemplate(NewDecl);
  7517. NewDecl->setAccess(AS);
  7518. if (Invalid)
  7519. NewDecl->setInvalidDecl();
  7520. else if (OldDecl)
  7521. NewDecl->setPreviousDecl(OldDecl);
  7522. NewND = NewDecl;
  7523. } else {
  7524. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  7525. setTagNameForLinkagePurposes(TD, NewTD);
  7526. handleTagNumbering(TD, S);
  7527. }
  7528. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  7529. NewND = NewTD;
  7530. }
  7531. if (!Redeclaration)
  7532. PushOnScopeChains(NewND, S);
  7533. ActOnDocumentableDecl(NewND);
  7534. return NewND;
  7535. }
  7536. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  7537. SourceLocation AliasLoc,
  7538. IdentifierInfo *Alias, CXXScopeSpec &SS,
  7539. SourceLocation IdentLoc,
  7540. IdentifierInfo *Ident) {
  7541. // Lookup the namespace name.
  7542. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  7543. LookupParsedName(R, S, &SS);
  7544. if (R.isAmbiguous())
  7545. return nullptr;
  7546. if (R.empty()) {
  7547. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  7548. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  7549. return nullptr;
  7550. }
  7551. }
  7552. assert(!R.isAmbiguous() && !R.empty());
  7553. // Check if we have a previous declaration with the same name.
  7554. NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
  7555. ForRedeclaration);
  7556. if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
  7557. PrevDecl = nullptr;
  7558. NamedDecl *ND = R.getFoundDecl();
  7559. if (PrevDecl) {
  7560. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  7561. // We already have an alias with the same name that points to the same
  7562. // namespace; check that it matches.
  7563. if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  7564. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  7565. << Alias;
  7566. Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
  7567. << AD->getNamespace();
  7568. return nullptr;
  7569. }
  7570. } else {
  7571. unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
  7572. ? diag::err_redefinition
  7573. : diag::err_redefinition_different_kind;
  7574. Diag(AliasLoc, DiagID) << Alias;
  7575. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7576. return nullptr;
  7577. }
  7578. }
  7579. // The use of a nested name specifier may trigger deprecation warnings.
  7580. DiagnoseUseOfDecl(ND, IdentLoc);
  7581. NamespaceAliasDecl *AliasDecl =
  7582. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  7583. Alias, SS.getWithLocInContext(Context),
  7584. IdentLoc, ND);
  7585. if (PrevDecl)
  7586. AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
  7587. PushOnScopeChains(AliasDecl, S);
  7588. return AliasDecl;
  7589. }
  7590. Sema::ImplicitExceptionSpecification
  7591. Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
  7592. CXXMethodDecl *MD) {
  7593. CXXRecordDecl *ClassDecl = MD->getParent();
  7594. // C++ [except.spec]p14:
  7595. // An implicitly declared special member function (Clause 12) shall have an
  7596. // exception-specification. [...]
  7597. ImplicitExceptionSpecification ExceptSpec(*this);
  7598. if (ClassDecl->isInvalidDecl())
  7599. return ExceptSpec;
  7600. // Direct base-class constructors.
  7601. for (const auto &B : ClassDecl->bases()) {
  7602. if (B.isVirtual()) // Handled below.
  7603. continue;
  7604. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  7605. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7606. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  7607. // If this is a deleted function, add it anyway. This might be conformant
  7608. // with the standard. This might not. I'm not sure. It might not matter.
  7609. if (Constructor)
  7610. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  7611. }
  7612. }
  7613. // Virtual base-class constructors.
  7614. for (const auto &B : ClassDecl->vbases()) {
  7615. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  7616. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7617. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  7618. // If this is a deleted function, add it anyway. This might be conformant
  7619. // with the standard. This might not. I'm not sure. It might not matter.
  7620. if (Constructor)
  7621. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  7622. }
  7623. }
  7624. // Field constructors.
  7625. for (const auto *F : ClassDecl->fields()) {
  7626. if (F->hasInClassInitializer()) {
  7627. if (Expr *E = F->getInClassInitializer())
  7628. ExceptSpec.CalledExpr(E);
  7629. } else if (const RecordType *RecordTy
  7630. = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
  7631. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  7632. CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
  7633. // If this is a deleted function, add it anyway. This might be conformant
  7634. // with the standard. This might not. I'm not sure. It might not matter.
  7635. // In particular, the problem is that this function never gets called. It
  7636. // might just be ill-formed because this function attempts to refer to
  7637. // a deleted function here.
  7638. if (Constructor)
  7639. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  7640. }
  7641. }
  7642. return ExceptSpec;
  7643. }
  7644. Sema::ImplicitExceptionSpecification
  7645. Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
  7646. CXXRecordDecl *ClassDecl = CD->getParent();
  7647. // C++ [except.spec]p14:
  7648. // An inheriting constructor [...] shall have an exception-specification. [...]
  7649. ImplicitExceptionSpecification ExceptSpec(*this);
  7650. if (ClassDecl->isInvalidDecl())
  7651. return ExceptSpec;
  7652. // Inherited constructor.
  7653. const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
  7654. const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
  7655. // FIXME: Copying or moving the parameters could add extra exceptions to the
  7656. // set, as could the default arguments for the inherited constructor. This
  7657. // will be addressed when we implement the resolution of core issue 1351.
  7658. ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
  7659. // Direct base-class constructors.
  7660. for (const auto &B : ClassDecl->bases()) {
  7661. if (B.isVirtual()) // Handled below.
  7662. continue;
  7663. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  7664. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7665. if (BaseClassDecl == InheritedDecl)
  7666. continue;
  7667. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  7668. if (Constructor)
  7669. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  7670. }
  7671. }
  7672. // Virtual base-class constructors.
  7673. for (const auto &B : ClassDecl->vbases()) {
  7674. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  7675. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7676. if (BaseClassDecl == InheritedDecl)
  7677. continue;
  7678. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  7679. if (Constructor)
  7680. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  7681. }
  7682. }
  7683. // Field constructors.
  7684. for (const auto *F : ClassDecl->fields()) {
  7685. if (F->hasInClassInitializer()) {
  7686. if (Expr *E = F->getInClassInitializer())
  7687. ExceptSpec.CalledExpr(E);
  7688. } else if (const RecordType *RecordTy
  7689. = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
  7690. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  7691. CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
  7692. if (Constructor)
  7693. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  7694. }
  7695. }
  7696. return ExceptSpec;
  7697. }
  7698. namespace {
  7699. /// RAII object to register a special member as being currently declared.
  7700. struct DeclaringSpecialMember {
  7701. Sema &S;
  7702. Sema::SpecialMemberDecl D;
  7703. bool WasAlreadyBeingDeclared;
  7704. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  7705. : S(S), D(RD, CSM) {
  7706. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  7707. if (WasAlreadyBeingDeclared)
  7708. // This almost never happens, but if it does, ensure that our cache
  7709. // doesn't contain a stale result.
  7710. S.SpecialMemberCache.clear();
  7711. // FIXME: Register a note to be produced if we encounter an error while
  7712. // declaring the special member.
  7713. }
  7714. ~DeclaringSpecialMember() {
  7715. if (!WasAlreadyBeingDeclared)
  7716. S.SpecialMembersBeingDeclared.erase(D);
  7717. }
  7718. /// \brief Are we already trying to declare this special member?
  7719. bool isAlreadyBeingDeclared() const {
  7720. return WasAlreadyBeingDeclared;
  7721. }
  7722. };
  7723. }
  7724. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  7725. CXXRecordDecl *ClassDecl) {
  7726. // C++ [class.ctor]p5:
  7727. // A default constructor for a class X is a constructor of class X
  7728. // that can be called without an argument. If there is no
  7729. // user-declared constructor for class X, a default constructor is
  7730. // implicitly declared. An implicitly-declared default constructor
  7731. // is an inline public member of its class.
  7732. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  7733. "Should not build implicit default constructor!");
  7734. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  7735. if (DSM.isAlreadyBeingDeclared())
  7736. return nullptr;
  7737. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  7738. CXXDefaultConstructor,
  7739. false);
  7740. // Create the actual constructor declaration.
  7741. CanQualType ClassType
  7742. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7743. SourceLocation ClassLoc = ClassDecl->getLocation();
  7744. DeclarationName Name
  7745. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  7746. DeclarationNameInfo NameInfo(Name, ClassLoc);
  7747. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  7748. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
  7749. /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
  7750. /*isImplicitlyDeclared=*/true, Constexpr);
  7751. DefaultCon->setAccess(AS_public);
  7752. DefaultCon->setDefaulted();
  7753. if (getLangOpts().CUDA) {
  7754. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  7755. DefaultCon,
  7756. /* ConstRHS */ false,
  7757. /* Diagnose */ false);
  7758. }
  7759. // Build an exception specification pointing back at this constructor.
  7760. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
  7761. DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI, None)); // HLSL Change - add param mods
  7762. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  7763. // constructors is easy to compute.
  7764. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  7765. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  7766. SetDeclDeleted(DefaultCon, ClassLoc);
  7767. // Note that we have declared this constructor.
  7768. ++ASTContext::NumImplicitDefaultConstructorsDeclared;
  7769. if (Scope *S = getScopeForContext(ClassDecl))
  7770. PushOnScopeChains(DefaultCon, S, false);
  7771. ClassDecl->addDecl(DefaultCon);
  7772. return DefaultCon;
  7773. }
  7774. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  7775. CXXConstructorDecl *Constructor) {
  7776. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  7777. !Constructor->doesThisDeclarationHaveABody() &&
  7778. !Constructor->isDeleted()) &&
  7779. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  7780. CXXRecordDecl *ClassDecl = Constructor->getParent();
  7781. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  7782. SynthesizedFunctionScope Scope(*this, Constructor);
  7783. DiagnosticErrorTrap Trap(Diags);
  7784. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
  7785. Trap.hasErrorOccurred()) {
  7786. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7787. << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
  7788. Constructor->setInvalidDecl();
  7789. return;
  7790. }
  7791. // The exception specification is needed because we are defining the
  7792. // function.
  7793. ResolveExceptionSpec(CurrentLocation,
  7794. Constructor->getType()->castAs<FunctionProtoType>());
  7795. SourceLocation Loc = Constructor->getLocEnd().isValid()
  7796. ? Constructor->getLocEnd()
  7797. : Constructor->getLocation();
  7798. Constructor->setBody(new (Context) CompoundStmt(Loc));
  7799. Constructor->markUsed(Context);
  7800. MarkVTableUsed(CurrentLocation, ClassDecl);
  7801. if (ASTMutationListener *L = getASTMutationListener()) {
  7802. L->CompletedImplicitDefinition(Constructor);
  7803. }
  7804. DiagnoseUninitializedFields(*this, Constructor);
  7805. }
  7806. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  7807. // Perform any delayed checks on exception specifications.
  7808. CheckDelayedMemberExceptionSpecs();
  7809. }
  7810. namespace {
  7811. /// Information on inheriting constructors to declare.
  7812. class InheritingConstructorInfo {
  7813. public:
  7814. InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
  7815. : SemaRef(SemaRef), Derived(Derived) {
  7816. // Mark the constructors that we already have in the derived class.
  7817. //
  7818. // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
  7819. // unless there is a user-declared constructor with the same signature in
  7820. // the class where the using-declaration appears.
  7821. visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
  7822. }
  7823. void inheritAll(CXXRecordDecl *RD) {
  7824. visitAll(RD, &InheritingConstructorInfo::inherit);
  7825. }
  7826. private:
  7827. /// Information about an inheriting constructor.
  7828. struct InheritingConstructor {
  7829. InheritingConstructor()
  7830. : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
  7831. /// If \c true, a constructor with this signature is already declared
  7832. /// in the derived class.
  7833. bool DeclaredInDerived;
  7834. /// The constructor which is inherited.
  7835. const CXXConstructorDecl *BaseCtor;
  7836. /// The derived constructor we declared.
  7837. CXXConstructorDecl *DerivedCtor;
  7838. };
  7839. /// Inheriting constructors with a given canonical type. There can be at
  7840. /// most one such non-template constructor, and any number of templated
  7841. /// constructors.
  7842. struct InheritingConstructorsForType {
  7843. InheritingConstructor NonTemplate;
  7844. SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
  7845. Templates;
  7846. InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
  7847. if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
  7848. TemplateParameterList *ParamList = FTD->getTemplateParameters();
  7849. for (unsigned I = 0, N = Templates.size(); I != N; ++I)
  7850. if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
  7851. false, S.TPL_TemplateMatch))
  7852. return Templates[I].second;
  7853. Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
  7854. return Templates.back().second;
  7855. }
  7856. return NonTemplate;
  7857. }
  7858. };
  7859. /// Get or create the inheriting constructor record for a constructor.
  7860. InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
  7861. QualType CtorType) {
  7862. return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
  7863. .getEntry(SemaRef, Ctor);
  7864. }
  7865. typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
  7866. /// Process all constructors for a class.
  7867. void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
  7868. for (const auto *Ctor : RD->ctors())
  7869. (this->*Callback)(Ctor);
  7870. for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
  7871. I(RD->decls_begin()), E(RD->decls_end());
  7872. I != E; ++I) {
  7873. const FunctionDecl *FD = (*I)->getTemplatedDecl();
  7874. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  7875. (this->*Callback)(CD);
  7876. }
  7877. }
  7878. /// Note that a constructor (or constructor template) was declared in Derived.
  7879. void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
  7880. getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
  7881. }
  7882. /// Inherit a single constructor.
  7883. void inherit(const CXXConstructorDecl *Ctor) {
  7884. const FunctionProtoType *CtorType =
  7885. Ctor->getType()->castAs<FunctionProtoType>();
  7886. ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
  7887. FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
  7888. SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
  7889. // Core issue (no number yet): the ellipsis is always discarded.
  7890. if (EPI.Variadic) {
  7891. SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
  7892. SemaRef.Diag(Ctor->getLocation(),
  7893. diag::note_using_decl_constructor_ellipsis);
  7894. EPI.Variadic = false;
  7895. }
  7896. // Declare a constructor for each number of parameters.
  7897. //
  7898. // C++11 [class.inhctor]p1:
  7899. // The candidate set of inherited constructors from the class X named in
  7900. // the using-declaration consists of [... modulo defects ...] for each
  7901. // constructor or constructor template of X, the set of constructors or
  7902. // constructor templates that results from omitting any ellipsis parameter
  7903. // specification and successively omitting parameters with a default
  7904. // argument from the end of the parameter-type-list
  7905. unsigned MinParams = minParamsToInherit(Ctor);
  7906. unsigned Params = Ctor->getNumParams();
  7907. if (Params >= MinParams) {
  7908. do
  7909. declareCtor(UsingLoc, Ctor,
  7910. SemaRef.Context.getFunctionType(
  7911. Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI, None)); // HLSL Change - add param mods
  7912. while (Params > MinParams &&
  7913. Ctor->getParamDecl(--Params)->hasDefaultArg());
  7914. }
  7915. }
  7916. /// Find the using-declaration which specified that we should inherit the
  7917. /// constructors of \p Base.
  7918. SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
  7919. // No fancy lookup required; just look for the base constructor name
  7920. // directly within the derived class.
  7921. ASTContext &Context = SemaRef.Context;
  7922. DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
  7923. Context.getCanonicalType(Context.getRecordType(Base)));
  7924. DeclContext::lookup_result Decls = Derived->lookup(Name);
  7925. return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
  7926. }
  7927. unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
  7928. // C++11 [class.inhctor]p3:
  7929. // [F]or each constructor template in the candidate set of inherited
  7930. // constructors, a constructor template is implicitly declared
  7931. if (Ctor->getDescribedFunctionTemplate())
  7932. return 0;
  7933. // For each non-template constructor in the candidate set of inherited
  7934. // constructors other than a constructor having no parameters or a
  7935. // copy/move constructor having a single parameter, a constructor is
  7936. // implicitly declared [...]
  7937. if (Ctor->getNumParams() == 0)
  7938. return 1;
  7939. if (Ctor->isCopyOrMoveConstructor())
  7940. return 2;
  7941. // Per discussion on core reflector, never inherit a constructor which
  7942. // would become a default, copy, or move constructor of Derived either.
  7943. const ParmVarDecl *PD = Ctor->getParamDecl(0);
  7944. const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
  7945. return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
  7946. }
  7947. /// Declare a single inheriting constructor, inheriting the specified
  7948. /// constructor, with the given type.
  7949. void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
  7950. QualType DerivedType) {
  7951. InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
  7952. // C++11 [class.inhctor]p3:
  7953. // ... a constructor is implicitly declared with the same constructor
  7954. // characteristics unless there is a user-declared constructor with
  7955. // the same signature in the class where the using-declaration appears
  7956. if (Entry.DeclaredInDerived)
  7957. return;
  7958. // C++11 [class.inhctor]p7:
  7959. // If two using-declarations declare inheriting constructors with the
  7960. // same signature, the program is ill-formed
  7961. if (Entry.DerivedCtor) {
  7962. if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
  7963. // Only diagnose this once per constructor.
  7964. if (Entry.DerivedCtor->isInvalidDecl())
  7965. return;
  7966. Entry.DerivedCtor->setInvalidDecl();
  7967. SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
  7968. SemaRef.Diag(BaseCtor->getLocation(),
  7969. diag::note_using_decl_constructor_conflict_current_ctor);
  7970. SemaRef.Diag(Entry.BaseCtor->getLocation(),
  7971. diag::note_using_decl_constructor_conflict_previous_ctor);
  7972. SemaRef.Diag(Entry.DerivedCtor->getLocation(),
  7973. diag::note_using_decl_constructor_conflict_previous_using);
  7974. } else {
  7975. // Core issue (no number): if the same inheriting constructor is
  7976. // produced by multiple base class constructors from the same base
  7977. // class, the inheriting constructor is defined as deleted.
  7978. SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
  7979. }
  7980. return;
  7981. }
  7982. ASTContext &Context = SemaRef.Context;
  7983. DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
  7984. Context.getCanonicalType(Context.getRecordType(Derived)));
  7985. DeclarationNameInfo NameInfo(Name, UsingLoc);
  7986. TemplateParameterList *TemplateParams = nullptr;
  7987. if (const FunctionTemplateDecl *FTD =
  7988. BaseCtor->getDescribedFunctionTemplate()) {
  7989. TemplateParams = FTD->getTemplateParameters();
  7990. // We're reusing template parameters from a different DeclContext. This
  7991. // is questionable at best, but works out because the template depth in
  7992. // both places is guaranteed to be 0.
  7993. // FIXME: Rebuild the template parameters in the new context, and
  7994. // transform the function type to refer to them.
  7995. }
  7996. // Build type source info pointing at the using-declaration. This is
  7997. // required by template instantiation.
  7998. TypeSourceInfo *TInfo =
  7999. Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
  8000. FunctionProtoTypeLoc ProtoLoc =
  8001. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  8002. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  8003. Context, Derived, UsingLoc, NameInfo, DerivedType,
  8004. TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
  8005. /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
  8006. // Build an unevaluated exception specification for this constructor.
  8007. const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
  8008. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8009. EPI.ExceptionSpec.Type = EST_Unevaluated;
  8010. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  8011. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  8012. FPT->getParamTypes(), EPI, None)); // HLSL Change - add param mods
  8013. // Build the parameter declarations.
  8014. SmallVector<ParmVarDecl *, 16> ParamDecls;
  8015. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  8016. TypeSourceInfo *TInfo =
  8017. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  8018. ParmVarDecl *PD = ParmVarDecl::Create(
  8019. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  8020. FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
  8021. PD->setScopeInfo(0, I);
  8022. PD->setImplicit();
  8023. ParamDecls.push_back(PD);
  8024. ProtoLoc.setParam(I, PD);
  8025. }
  8026. // Set up the new constructor.
  8027. DerivedCtor->setAccess(BaseCtor->getAccess());
  8028. DerivedCtor->setParams(ParamDecls);
  8029. DerivedCtor->setInheritedConstructor(BaseCtor);
  8030. if (BaseCtor->isDeleted())
  8031. SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
  8032. // If this is a constructor template, build the template declaration.
  8033. if (TemplateParams) {
  8034. FunctionTemplateDecl *DerivedTemplate =
  8035. FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
  8036. TemplateParams, DerivedCtor);
  8037. DerivedTemplate->setAccess(BaseCtor->getAccess());
  8038. DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
  8039. Derived->addDecl(DerivedTemplate);
  8040. } else {
  8041. Derived->addDecl(DerivedCtor);
  8042. }
  8043. Entry.BaseCtor = BaseCtor;
  8044. Entry.DerivedCtor = DerivedCtor;
  8045. }
  8046. Sema &SemaRef;
  8047. CXXRecordDecl *Derived;
  8048. typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
  8049. MapType Map;
  8050. };
  8051. }
  8052. void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
  8053. // Defer declaring the inheriting constructors until the class is
  8054. // instantiated.
  8055. if (ClassDecl->isDependentContext())
  8056. return;
  8057. // Find base classes from which we might inherit constructors.
  8058. SmallVector<CXXRecordDecl*, 4> InheritedBases;
  8059. for (const auto &BaseIt : ClassDecl->bases())
  8060. if (BaseIt.getInheritConstructors())
  8061. InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
  8062. // Go no further if we're not inheriting any constructors.
  8063. if (InheritedBases.empty())
  8064. return;
  8065. // Declare the inherited constructors.
  8066. InheritingConstructorInfo ICI(*this, ClassDecl);
  8067. for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
  8068. ICI.inheritAll(InheritedBases[I]);
  8069. }
  8070. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  8071. CXXConstructorDecl *Constructor) {
  8072. CXXRecordDecl *ClassDecl = Constructor->getParent();
  8073. assert(Constructor->getInheritedConstructor() &&
  8074. !Constructor->doesThisDeclarationHaveABody() &&
  8075. !Constructor->isDeleted());
  8076. SynthesizedFunctionScope Scope(*this, Constructor);
  8077. DiagnosticErrorTrap Trap(Diags);
  8078. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
  8079. Trap.hasErrorOccurred()) {
  8080. Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
  8081. << Context.getTagDeclType(ClassDecl);
  8082. Constructor->setInvalidDecl();
  8083. return;
  8084. }
  8085. SourceLocation Loc = Constructor->getLocation();
  8086. Constructor->setBody(new (Context) CompoundStmt(Loc));
  8087. Constructor->markUsed(Context);
  8088. MarkVTableUsed(CurrentLocation, ClassDecl);
  8089. if (ASTMutationListener *L = getASTMutationListener()) {
  8090. L->CompletedImplicitDefinition(Constructor);
  8091. }
  8092. }
  8093. Sema::ImplicitExceptionSpecification
  8094. Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
  8095. CXXRecordDecl *ClassDecl = MD->getParent();
  8096. // C++ [except.spec]p14:
  8097. // An implicitly declared special member function (Clause 12) shall have
  8098. // an exception-specification.
  8099. ImplicitExceptionSpecification ExceptSpec(*this);
  8100. if (ClassDecl->isInvalidDecl())
  8101. return ExceptSpec;
  8102. // Direct base-class destructors.
  8103. for (const auto &B : ClassDecl->bases()) {
  8104. if (B.isVirtual()) // Handled below.
  8105. continue;
  8106. if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
  8107. ExceptSpec.CalledDecl(B.getLocStart(),
  8108. LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
  8109. }
  8110. // Virtual base-class destructors.
  8111. for (const auto &B : ClassDecl->vbases()) {
  8112. if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
  8113. ExceptSpec.CalledDecl(B.getLocStart(),
  8114. LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
  8115. }
  8116. // Field destructors.
  8117. for (const auto *F : ClassDecl->fields()) {
  8118. if (const RecordType *RecordTy
  8119. = Context.getBaseElementType(F->getType())->getAs<RecordType>())
  8120. ExceptSpec.CalledDecl(F->getLocation(),
  8121. LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
  8122. }
  8123. return ExceptSpec;
  8124. }
  8125. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  8126. // C++ [class.dtor]p2:
  8127. // If a class has no user-declared destructor, a destructor is
  8128. // declared implicitly. An implicitly-declared destructor is an
  8129. // inline public member of its class.
  8130. assert(ClassDecl->needsImplicitDestructor());
  8131. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  8132. if (DSM.isAlreadyBeingDeclared())
  8133. return nullptr;
  8134. // Create the actual destructor declaration.
  8135. CanQualType ClassType
  8136. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  8137. SourceLocation ClassLoc = ClassDecl->getLocation();
  8138. DeclarationName Name
  8139. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  8140. DeclarationNameInfo NameInfo(Name, ClassLoc);
  8141. CXXDestructorDecl *Destructor
  8142. = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  8143. QualType(), nullptr, /*isInline=*/true,
  8144. /*isImplicitlyDeclared=*/true);
  8145. Destructor->setAccess(AS_public);
  8146. Destructor->setDefaulted();
  8147. if (getLangOpts().CUDA) {
  8148. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  8149. Destructor,
  8150. /* ConstRHS */ false,
  8151. /* Diagnose */ false);
  8152. }
  8153. // Build an exception specification pointing back at this destructor.
  8154. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
  8155. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI, None)); // HLSL Change
  8156. AddOverriddenMethods(ClassDecl, Destructor);
  8157. // We don't need to use SpecialMemberIsTrivial here; triviality for
  8158. // destructors is easy to compute.
  8159. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  8160. if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  8161. SetDeclDeleted(Destructor, ClassLoc);
  8162. // Note that we have declared this destructor.
  8163. ++ASTContext::NumImplicitDestructorsDeclared;
  8164. // Introduce this destructor into its scope.
  8165. if (Scope *S = getScopeForContext(ClassDecl))
  8166. PushOnScopeChains(Destructor, S, false);
  8167. ClassDecl->addDecl(Destructor);
  8168. return Destructor;
  8169. }
  8170. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  8171. CXXDestructorDecl *Destructor) {
  8172. assert((Destructor->isDefaulted() &&
  8173. !Destructor->doesThisDeclarationHaveABody() &&
  8174. !Destructor->isDeleted()) &&
  8175. "DefineImplicitDestructor - call it for implicit default dtor");
  8176. CXXRecordDecl *ClassDecl = Destructor->getParent();
  8177. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  8178. if (Destructor->isInvalidDecl())
  8179. return;
  8180. SynthesizedFunctionScope Scope(*this, Destructor);
  8181. DiagnosticErrorTrap Trap(Diags);
  8182. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  8183. Destructor->getParent());
  8184. if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
  8185. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8186. << CXXDestructor << Context.getTagDeclType(ClassDecl);
  8187. Destructor->setInvalidDecl();
  8188. return;
  8189. }
  8190. // The exception specification is needed because we are defining the
  8191. // function.
  8192. ResolveExceptionSpec(CurrentLocation,
  8193. Destructor->getType()->castAs<FunctionProtoType>());
  8194. SourceLocation Loc = Destructor->getLocEnd().isValid()
  8195. ? Destructor->getLocEnd()
  8196. : Destructor->getLocation();
  8197. Destructor->setBody(new (Context) CompoundStmt(Loc));
  8198. Destructor->markUsed(Context);
  8199. MarkVTableUsed(CurrentLocation, ClassDecl);
  8200. if (ASTMutationListener *L = getASTMutationListener()) {
  8201. L->CompletedImplicitDefinition(Destructor);
  8202. }
  8203. }
  8204. /// \brief Perform any semantic analysis which needs to be delayed until all
  8205. /// pending class member declarations have been parsed.
  8206. void Sema::ActOnFinishCXXMemberDecls() {
  8207. // If the context is an invalid C++ class, just suppress these checks.
  8208. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  8209. if (Record->isInvalidDecl()) {
  8210. DelayedDefaultedMemberExceptionSpecs.clear();
  8211. DelayedExceptionSpecChecks.clear();
  8212. return;
  8213. }
  8214. }
  8215. }
  8216. static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
  8217. // Don't do anything for template patterns.
  8218. if (Class->getDescribedClassTemplate())
  8219. return;
  8220. for (Decl *Member : Class->decls()) {
  8221. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  8222. if (!CD) {
  8223. // Recurse on nested classes.
  8224. if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
  8225. getDefaultArgExprsForConstructors(S, NestedRD);
  8226. continue;
  8227. } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
  8228. continue;
  8229. }
  8230. for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
  8231. // Skip any default arguments that we've already instantiated.
  8232. if (S.Context.getDefaultArgExprForConstructor(CD, I))
  8233. continue;
  8234. Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
  8235. CD->getParamDecl(I)).get();
  8236. S.DiscardCleanupsInEvaluationContext();
  8237. S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
  8238. }
  8239. }
  8240. }
  8241. void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
  8242. auto *RD = dyn_cast<CXXRecordDecl>(D);
  8243. // Default constructors that are annotated with __declspec(dllexport) which
  8244. // have default arguments or don't use the standard calling convention are
  8245. // wrapped with a thunk called the default constructor closure.
  8246. if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
  8247. getDefaultArgExprsForConstructors(*this, RD);
  8248. }
  8249. void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
  8250. CXXDestructorDecl *Destructor) {
  8251. assert(getLangOpts().CPlusPlus11 &&
  8252. "adjusting dtor exception specs was introduced in c++11");
  8253. // C++11 [class.dtor]p3:
  8254. // A declaration of a destructor that does not have an exception-
  8255. // specification is implicitly considered to have the same exception-
  8256. // specification as an implicit declaration.
  8257. const FunctionProtoType *DtorType = Destructor->getType()->
  8258. getAs<FunctionProtoType>();
  8259. if (DtorType->hasExceptionSpec())
  8260. return;
  8261. // Replace the destructor's type, building off the existing one. Fortunately,
  8262. // the only thing of interest in the destructor type is its extended info.
  8263. // The return and arguments are fixed.
  8264. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  8265. EPI.ExceptionSpec.Type = EST_Unevaluated;
  8266. EPI.ExceptionSpec.SourceDecl = Destructor;
  8267. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI, None)); // HLSL Change - add param mods
  8268. // FIXME: If the destructor has a body that could throw, and the newly created
  8269. // spec doesn't allow exceptions, we should emit a warning, because this
  8270. // change in behavior can break conforming C++03 programs at runtime.
  8271. // However, we don't have a body or an exception specification yet, so it
  8272. // needs to be done somewhere else.
  8273. }
  8274. namespace {
  8275. /// \brief An abstract base class for all helper classes used in building the
  8276. // copy/move operators. These classes serve as factory functions and help us
  8277. // avoid using the same Expr* in the AST twice.
  8278. class ExprBuilder {
  8279. ExprBuilder(const ExprBuilder&) = delete;
  8280. ExprBuilder &operator=(const ExprBuilder&) = delete;
  8281. protected:
  8282. static Expr *assertNotNull(Expr *E) {
  8283. assert(E && "Expression construction must not fail.");
  8284. return E;
  8285. }
  8286. public:
  8287. ExprBuilder() {}
  8288. virtual ~ExprBuilder() {}
  8289. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  8290. };
  8291. class RefBuilder: public ExprBuilder {
  8292. VarDecl *Var;
  8293. QualType VarType;
  8294. public:
  8295. Expr *build(Sema &S, SourceLocation Loc) const override {
  8296. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
  8297. }
  8298. RefBuilder(VarDecl *Var, QualType VarType)
  8299. : Var(Var), VarType(VarType) {}
  8300. };
  8301. class ThisBuilder: public ExprBuilder {
  8302. public:
  8303. Expr *build(Sema &S, SourceLocation Loc) const override {
  8304. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  8305. }
  8306. };
  8307. class CastBuilder: public ExprBuilder {
  8308. const ExprBuilder &Builder;
  8309. QualType Type;
  8310. ExprValueKind Kind;
  8311. const CXXCastPath &Path;
  8312. public:
  8313. Expr *build(Sema &S, SourceLocation Loc) const override {
  8314. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  8315. CK_UncheckedDerivedToBase, Kind,
  8316. &Path).get());
  8317. }
  8318. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  8319. const CXXCastPath &Path)
  8320. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  8321. };
  8322. class DerefBuilder: public ExprBuilder {
  8323. const ExprBuilder &Builder;
  8324. public:
  8325. Expr *build(Sema &S, SourceLocation Loc) const override {
  8326. return assertNotNull(
  8327. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  8328. }
  8329. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  8330. };
  8331. class MemberBuilder: public ExprBuilder {
  8332. const ExprBuilder &Builder;
  8333. QualType Type;
  8334. CXXScopeSpec SS;
  8335. bool IsArrow;
  8336. LookupResult &MemberLookup;
  8337. public:
  8338. Expr *build(Sema &S, SourceLocation Loc) const override {
  8339. return assertNotNull(S.BuildMemberReferenceExpr(
  8340. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  8341. nullptr, MemberLookup, nullptr).get());
  8342. }
  8343. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  8344. LookupResult &MemberLookup)
  8345. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  8346. MemberLookup(MemberLookup) {}
  8347. };
  8348. class MoveCastBuilder: public ExprBuilder {
  8349. const ExprBuilder &Builder;
  8350. public:
  8351. Expr *build(Sema &S, SourceLocation Loc) const override {
  8352. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  8353. }
  8354. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  8355. };
  8356. class LvalueConvBuilder: public ExprBuilder {
  8357. const ExprBuilder &Builder;
  8358. public:
  8359. Expr *build(Sema &S, SourceLocation Loc) const override {
  8360. return assertNotNull(
  8361. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  8362. }
  8363. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  8364. };
  8365. class SubscriptBuilder: public ExprBuilder {
  8366. const ExprBuilder &Base;
  8367. const ExprBuilder &Index;
  8368. public:
  8369. Expr *build(Sema &S, SourceLocation Loc) const override {
  8370. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  8371. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  8372. }
  8373. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  8374. : Base(Base), Index(Index) {}
  8375. };
  8376. } // end anonymous namespace
  8377. /// When generating a defaulted copy or move assignment operator, if a field
  8378. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  8379. /// do so. This optimization only applies for arrays of scalars, and for arrays
  8380. /// of class type where the selected copy/move-assignment operator is trivial.
  8381. static StmtResult
  8382. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  8383. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  8384. // Compute the size of the memory buffer to be copied.
  8385. QualType SizeType = S.Context.getSizeType();
  8386. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  8387. S.Context.getTypeSizeInChars(T).getQuantity());
  8388. // Take the address of the field references for "from" and "to". We
  8389. // directly construct UnaryOperators here because semantic analysis
  8390. // does not permit us to take the address of an xvalue.
  8391. Expr *From = FromB.build(S, Loc);
  8392. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  8393. S.Context.getPointerType(From->getType()),
  8394. VK_RValue, OK_Ordinary, Loc);
  8395. Expr *To = ToB.build(S, Loc);
  8396. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  8397. S.Context.getPointerType(To->getType()),
  8398. VK_RValue, OK_Ordinary, Loc);
  8399. const Type *E = T->getBaseElementTypeUnsafe();
  8400. bool NeedsCollectableMemCpy =
  8401. E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
  8402. // Create a reference to the __builtin_objc_memmove_collectable function
  8403. StringRef MemCpyName = NeedsCollectableMemCpy ?
  8404. "__builtin_objc_memmove_collectable" :
  8405. "__builtin_memcpy";
  8406. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  8407. Sema::LookupOrdinaryName);
  8408. S.LookupName(R, S.TUScope, true);
  8409. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  8410. if (!MemCpy)
  8411. // Something went horribly wrong earlier, and we will have complained
  8412. // about it.
  8413. return StmtError();
  8414. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  8415. VK_RValue, Loc, nullptr);
  8416. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  8417. Expr *CallArgs[] = {
  8418. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  8419. };
  8420. ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  8421. Loc, CallArgs, Loc);
  8422. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  8423. return Call.getAs<Stmt>();
  8424. }
  8425. /// \brief Builds a statement that copies/moves the given entity from \p From to
  8426. /// \c To.
  8427. ///
  8428. /// This routine is used to copy/move the members of a class with an
  8429. /// implicitly-declared copy/move assignment operator. When the entities being
  8430. /// copied are arrays, this routine builds for loops to copy them.
  8431. ///
  8432. /// \param S The Sema object used for type-checking.
  8433. ///
  8434. /// \param Loc The location where the implicit copy/move is being generated.
  8435. ///
  8436. /// \param T The type of the expressions being copied/moved. Both expressions
  8437. /// must have this type.
  8438. ///
  8439. /// \param To The expression we are copying/moving to.
  8440. ///
  8441. /// \param From The expression we are copying/moving from.
  8442. ///
  8443. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  8444. /// Otherwise, it's a non-static member subobject.
  8445. ///
  8446. /// \param Copying Whether we're copying or moving.
  8447. ///
  8448. /// \param Depth Internal parameter recording the depth of the recursion.
  8449. ///
  8450. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  8451. /// if a memcpy should be used instead.
  8452. static StmtResult
  8453. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  8454. const ExprBuilder &To, const ExprBuilder &From,
  8455. bool CopyingBaseSubobject, bool Copying,
  8456. unsigned Depth = 0) {
  8457. // C++11 [class.copy]p28:
  8458. // Each subobject is assigned in the manner appropriate to its type:
  8459. //
  8460. // - if the subobject is of class type, as if by a call to operator= with
  8461. // the subobject as the object expression and the corresponding
  8462. // subobject of x as a single function argument (as if by explicit
  8463. // qualification; that is, ignoring any possible virtual overriding
  8464. // functions in more derived classes);
  8465. //
  8466. // C++03 [class.copy]p13:
  8467. // - if the subobject is of class type, the copy assignment operator for
  8468. // the class is used (as if by explicit qualification; that is,
  8469. // ignoring any possible virtual overriding functions in more derived
  8470. // classes);
  8471. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  8472. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  8473. // Look for operator=.
  8474. DeclarationName Name
  8475. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  8476. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  8477. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  8478. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  8479. // operator.
  8480. if (!S.getLangOpts().CPlusPlus11) {
  8481. LookupResult::Filter F = OpLookup.makeFilter();
  8482. while (F.hasNext()) {
  8483. NamedDecl *D = F.next();
  8484. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  8485. if (Method->isCopyAssignmentOperator() ||
  8486. (!Copying && Method->isMoveAssignmentOperator()))
  8487. continue;
  8488. F.erase();
  8489. }
  8490. F.done();
  8491. }
  8492. // Suppress the protected check (C++ [class.protected]) for each of the
  8493. // assignment operators we found. This strange dance is required when
  8494. // we're assigning via a base classes's copy-assignment operator. To
  8495. // ensure that we're getting the right base class subobject (without
  8496. // ambiguities), we need to cast "this" to that subobject type; to
  8497. // ensure that we don't go through the virtual call mechanism, we need
  8498. // to qualify the operator= name with the base class (see below). However,
  8499. // this means that if the base class has a protected copy assignment
  8500. // operator, the protected member access check will fail. So, we
  8501. // rewrite "protected" access to "public" access in this case, since we
  8502. // know by construction that we're calling from a derived class.
  8503. if (CopyingBaseSubobject) {
  8504. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  8505. L != LEnd; ++L) {
  8506. if (L.getAccess() == AS_protected)
  8507. L.setAccess(AS_public);
  8508. }
  8509. }
  8510. // Create the nested-name-specifier that will be used to qualify the
  8511. // reference to operator=; this is required to suppress the virtual
  8512. // call mechanism.
  8513. CXXScopeSpec SS;
  8514. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  8515. SS.MakeTrivial(S.Context,
  8516. NestedNameSpecifier::Create(S.Context, nullptr, false,
  8517. CanonicalT),
  8518. Loc);
  8519. // Create the reference to operator=.
  8520. ExprResult OpEqualRef
  8521. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
  8522. SS, /*TemplateKWLoc=*/SourceLocation(),
  8523. /*FirstQualifierInScope=*/nullptr,
  8524. OpLookup,
  8525. /*TemplateArgs=*/nullptr,
  8526. /*SuppressQualifierCheck=*/true);
  8527. if (OpEqualRef.isInvalid())
  8528. return StmtError();
  8529. // Build the call to the assignment operator.
  8530. Expr *FromInst = From.build(S, Loc);
  8531. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  8532. OpEqualRef.getAs<Expr>(),
  8533. Loc, FromInst, Loc);
  8534. if (Call.isInvalid())
  8535. return StmtError();
  8536. // If we built a call to a trivial 'operator=' while copying an array,
  8537. // bail out. We'll replace the whole shebang with a memcpy.
  8538. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  8539. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  8540. return StmtResult((Stmt*)nullptr);
  8541. // Convert to an expression-statement, and clean up any produced
  8542. // temporaries.
  8543. return S.ActOnExprStmt(Call);
  8544. }
  8545. // - if the subobject is of scalar type, the built-in assignment
  8546. // operator is used.
  8547. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  8548. if (!ArrayTy) {
  8549. ExprResult Assignment = S.CreateBuiltinBinOp(
  8550. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  8551. if (Assignment.isInvalid())
  8552. return StmtError();
  8553. return S.ActOnExprStmt(Assignment);
  8554. }
  8555. // - if the subobject is an array, each element is assigned, in the
  8556. // manner appropriate to the element type;
  8557. // Construct a loop over the array bounds, e.g.,
  8558. //
  8559. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  8560. //
  8561. // that will copy each of the array elements.
  8562. QualType SizeType = S.Context.getSizeType();
  8563. // Create the iteration variable.
  8564. IdentifierInfo *IterationVarName = nullptr;
  8565. {
  8566. SmallString<8> Str;
  8567. llvm::raw_svector_ostream OS(Str);
  8568. OS << "__i" << Depth;
  8569. IterationVarName = &S.Context.Idents.get(OS.str());
  8570. }
  8571. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  8572. IterationVarName, SizeType,
  8573. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  8574. SC_None);
  8575. // Initialize the iteration variable to zero.
  8576. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  8577. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  8578. // Creates a reference to the iteration variable.
  8579. RefBuilder IterationVarRef(IterationVar, SizeType);
  8580. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  8581. // Create the DeclStmt that holds the iteration variable.
  8582. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  8583. // Subscript the "from" and "to" expressions with the iteration variable.
  8584. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  8585. MoveCastBuilder FromIndexMove(FromIndexCopy);
  8586. const ExprBuilder *FromIndex;
  8587. if (Copying)
  8588. FromIndex = &FromIndexCopy;
  8589. else
  8590. FromIndex = &FromIndexMove;
  8591. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  8592. // Build the copy/move for an individual element of the array.
  8593. StmtResult Copy =
  8594. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  8595. ToIndex, *FromIndex, CopyingBaseSubobject,
  8596. Copying, Depth + 1);
  8597. // Bail out if copying fails or if we determined that we should use memcpy.
  8598. if (Copy.isInvalid() || !Copy.get())
  8599. return Copy;
  8600. // Create the comparison against the array bound.
  8601. llvm::APInt Upper
  8602. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  8603. Expr *Comparison
  8604. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  8605. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  8606. BO_NE, S.Context.BoolTy,
  8607. VK_RValue, OK_Ordinary, Loc, false);
  8608. // Create the pre-increment of the iteration variable.
  8609. Expr *Increment
  8610. = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
  8611. SizeType, VK_LValue, OK_Ordinary, Loc);
  8612. // Construct the loop that copies all elements of this array.
  8613. return S.ActOnForStmt(Loc, Loc, InitStmt,
  8614. S.MakeFullExpr(Comparison),
  8615. nullptr, S.MakeFullDiscardedValueExpr(Increment),
  8616. Loc, Copy.get());
  8617. }
  8618. static StmtResult
  8619. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  8620. const ExprBuilder &To, const ExprBuilder &From,
  8621. bool CopyingBaseSubobject, bool Copying) {
  8622. // Maybe we should use a memcpy?
  8623. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  8624. T.isTriviallyCopyableType(S.Context))
  8625. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  8626. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  8627. CopyingBaseSubobject,
  8628. Copying, 0));
  8629. // If we ended up picking a trivial assignment operator for an array of a
  8630. // non-trivially-copyable class type, just emit a memcpy.
  8631. if (!Result.isInvalid() && !Result.get())
  8632. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  8633. return Result;
  8634. }
  8635. Sema::ImplicitExceptionSpecification
  8636. Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
  8637. CXXRecordDecl *ClassDecl = MD->getParent();
  8638. ImplicitExceptionSpecification ExceptSpec(*this);
  8639. if (ClassDecl->isInvalidDecl())
  8640. return ExceptSpec;
  8641. const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
  8642. assert(T->getNumParams() == 1 && "not a copy assignment op");
  8643. unsigned ArgQuals =
  8644. T->getParamType(0).getNonReferenceType().getCVRQualifiers();
  8645. // C++ [except.spec]p14:
  8646. // An implicitly declared special member function (Clause 12) shall have an
  8647. // exception-specification. [...]
  8648. // It is unspecified whether or not an implicit copy assignment operator
  8649. // attempts to deduplicate calls to assignment operators of virtual bases are
  8650. // made. As such, this exception specification is effectively unspecified.
  8651. // Based on a similar decision made for constness in C++0x, we're erring on
  8652. // the side of assuming such calls to be made regardless of whether they
  8653. // actually happen.
  8654. for (const auto &Base : ClassDecl->bases()) {
  8655. if (Base.isVirtual())
  8656. continue;
  8657. CXXRecordDecl *BaseClassDecl
  8658. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  8659. if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
  8660. ArgQuals, false, 0))
  8661. ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
  8662. }
  8663. for (const auto &Base : ClassDecl->vbases()) {
  8664. CXXRecordDecl *BaseClassDecl
  8665. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  8666. if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
  8667. ArgQuals, false, 0))
  8668. ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
  8669. }
  8670. for (const auto *Field : ClassDecl->fields()) {
  8671. QualType FieldType = Context.getBaseElementType(Field->getType());
  8672. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  8673. if (CXXMethodDecl *CopyAssign =
  8674. LookupCopyingAssignment(FieldClassDecl,
  8675. ArgQuals | FieldType.getCVRQualifiers(),
  8676. false, 0))
  8677. ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
  8678. }
  8679. }
  8680. return ExceptSpec;
  8681. }
  8682. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  8683. // Note: The following rules are largely analoguous to the copy
  8684. // constructor rules. Note that virtual bases are not taken into account
  8685. // for determining the argument type of the operator. Note also that
  8686. // operators taking an object instead of a reference are allowed.
  8687. assert(ClassDecl->needsImplicitCopyAssignment());
  8688. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  8689. if (DSM.isAlreadyBeingDeclared())
  8690. return nullptr;
  8691. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  8692. QualType RetType = Context.getLValueReferenceType(ArgType);
  8693. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  8694. if (Const)
  8695. ArgType = ArgType.withConst();
  8696. ArgType = Context.getLValueReferenceType(ArgType);
  8697. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  8698. CXXCopyAssignment,
  8699. Const);
  8700. // An implicitly-declared copy assignment operator is an inline public
  8701. // member of its class.
  8702. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  8703. SourceLocation ClassLoc = ClassDecl->getLocation();
  8704. DeclarationNameInfo NameInfo(Name, ClassLoc);
  8705. CXXMethodDecl *CopyAssignment =
  8706. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  8707. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  8708. /*isInline=*/true, Constexpr, SourceLocation());
  8709. CopyAssignment->setAccess(AS_public);
  8710. CopyAssignment->setDefaulted();
  8711. CopyAssignment->setImplicit();
  8712. if (getLangOpts().CUDA) {
  8713. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  8714. CopyAssignment,
  8715. /* ConstRHS */ Const,
  8716. /* Diagnose */ false);
  8717. }
  8718. // Build an exception specification pointing back at this member.
  8719. FunctionProtoType::ExtProtoInfo EPI =
  8720. getImplicitMethodEPI(*this, CopyAssignment);
  8721. CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI, None)); // HLSL Change - add param mods
  8722. // Add the parameter to the operator.
  8723. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  8724. ClassLoc, ClassLoc,
  8725. /*Id=*/nullptr, ArgType,
  8726. /*TInfo=*/nullptr, SC_None,
  8727. nullptr);
  8728. CopyAssignment->setParams(FromParam);
  8729. AddOverriddenMethods(ClassDecl, CopyAssignment);
  8730. CopyAssignment->setTrivial(
  8731. ClassDecl->needsOverloadResolutionForCopyAssignment()
  8732. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  8733. : ClassDecl->hasTrivialCopyAssignment());
  8734. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  8735. SetDeclDeleted(CopyAssignment, ClassLoc);
  8736. // Note that we have added this copy-assignment operator.
  8737. ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
  8738. if (Scope *S = getScopeForContext(ClassDecl))
  8739. PushOnScopeChains(CopyAssignment, S, false);
  8740. ClassDecl->addDecl(CopyAssignment);
  8741. return CopyAssignment;
  8742. }
  8743. /// Diagnose an implicit copy operation for a class which is odr-used, but
  8744. /// which is deprecated because the class has a user-declared copy constructor,
  8745. /// copy assignment operator, or destructor.
  8746. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
  8747. SourceLocation UseLoc) {
  8748. assert(CopyOp->isImplicit());
  8749. CXXRecordDecl *RD = CopyOp->getParent();
  8750. CXXMethodDecl *UserDeclaredOperation = nullptr;
  8751. // In Microsoft mode, assignment operations don't affect constructors and
  8752. // vice versa.
  8753. if (RD->hasUserDeclaredDestructor()) {
  8754. UserDeclaredOperation = RD->getDestructor();
  8755. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  8756. RD->hasUserDeclaredCopyConstructor() &&
  8757. !S.getLangOpts().MSVCCompat) {
  8758. // Find any user-declared copy constructor.
  8759. for (auto *I : RD->ctors()) {
  8760. if (I->isCopyConstructor()) {
  8761. UserDeclaredOperation = I;
  8762. break;
  8763. }
  8764. }
  8765. assert(UserDeclaredOperation);
  8766. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  8767. RD->hasUserDeclaredCopyAssignment() &&
  8768. !S.getLangOpts().MSVCCompat) {
  8769. // Find any user-declared move assignment operator.
  8770. for (auto *I : RD->methods()) {
  8771. if (I->isCopyAssignmentOperator()) {
  8772. UserDeclaredOperation = I;
  8773. break;
  8774. }
  8775. }
  8776. assert(UserDeclaredOperation);
  8777. }
  8778. if (UserDeclaredOperation) {
  8779. S.Diag(UserDeclaredOperation->getLocation(),
  8780. diag::warn_deprecated_copy_operation)
  8781. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  8782. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  8783. S.Diag(UseLoc, diag::note_member_synthesized_at)
  8784. << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
  8785. : Sema::CXXCopyAssignment)
  8786. << RD;
  8787. }
  8788. }
  8789. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  8790. CXXMethodDecl *CopyAssignOperator) {
  8791. assert((CopyAssignOperator->isDefaulted() &&
  8792. CopyAssignOperator->isOverloadedOperator() &&
  8793. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  8794. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  8795. !CopyAssignOperator->isDeleted()) &&
  8796. "DefineImplicitCopyAssignment called for wrong function");
  8797. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  8798. if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
  8799. CopyAssignOperator->setInvalidDecl();
  8800. return;
  8801. }
  8802. // C++11 [class.copy]p18:
  8803. // The [definition of an implicitly declared copy assignment operator] is
  8804. // deprecated if the class has a user-declared copy constructor or a
  8805. // user-declared destructor.
  8806. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  8807. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
  8808. CopyAssignOperator->markUsed(Context);
  8809. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  8810. DiagnosticErrorTrap Trap(Diags);
  8811. // C++0x [class.copy]p30:
  8812. // The implicitly-defined or explicitly-defaulted copy assignment operator
  8813. // for a non-union class X performs memberwise copy assignment of its
  8814. // subobjects. The direct base classes of X are assigned first, in the
  8815. // order of their declaration in the base-specifier-list, and then the
  8816. // immediate non-static data members of X are assigned, in the order in
  8817. // which they were declared in the class definition.
  8818. // The statements that form the synthesized function body.
  8819. SmallVector<Stmt*, 8> Statements;
  8820. // The parameter for the "other" object, which we are copying from.
  8821. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  8822. Qualifiers OtherQuals = Other->getType().getQualifiers();
  8823. QualType OtherRefType = Other->getType();
  8824. if (const LValueReferenceType *OtherRef
  8825. = OtherRefType->getAs<LValueReferenceType>()) {
  8826. OtherRefType = OtherRef->getPointeeType();
  8827. OtherQuals = OtherRefType.getQualifiers();
  8828. }
  8829. // Our location for everything implicitly-generated.
  8830. SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
  8831. ? CopyAssignOperator->getLocEnd()
  8832. : CopyAssignOperator->getLocation();
  8833. // Builds a DeclRefExpr for the "other" object.
  8834. RefBuilder OtherRef(Other, OtherRefType);
  8835. // Builds the "this" pointer.
  8836. ThisBuilder This;
  8837. // Assign base classes.
  8838. bool Invalid = false;
  8839. for (auto &Base : ClassDecl->bases()) {
  8840. // Form the assignment:
  8841. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  8842. QualType BaseType = Base.getType().getUnqualifiedType();
  8843. if (!BaseType->isRecordType()) {
  8844. Invalid = true;
  8845. continue;
  8846. }
  8847. CXXCastPath BasePath;
  8848. BasePath.push_back(&Base);
  8849. // Construct the "from" expression, which is an implicit cast to the
  8850. // appropriately-qualified base type.
  8851. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  8852. VK_LValue, BasePath);
  8853. // Dereference "this".
  8854. DerefBuilder DerefThis(This);
  8855. CastBuilder To(DerefThis,
  8856. Context.getCVRQualifiedType(
  8857. BaseType, CopyAssignOperator->getTypeQualifiers()),
  8858. VK_LValue, BasePath);
  8859. // Build the copy.
  8860. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  8861. To, From,
  8862. /*CopyingBaseSubobject=*/true,
  8863. /*Copying=*/true);
  8864. if (Copy.isInvalid()) {
  8865. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8866. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8867. CopyAssignOperator->setInvalidDecl();
  8868. return;
  8869. }
  8870. // Success! Record the copy.
  8871. Statements.push_back(Copy.getAs<Expr>());
  8872. }
  8873. // Assign non-static members.
  8874. for (auto *Field : ClassDecl->fields()) {
  8875. // FIXME: We should form some kind of AST representation for the implied
  8876. // memcpy in a union copy operation.
  8877. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  8878. continue;
  8879. if (Field->isInvalidDecl()) {
  8880. Invalid = true;
  8881. continue;
  8882. }
  8883. // Check for members of reference type; we can't copy those.
  8884. if (Field->getType()->isReferenceType()) {
  8885. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  8886. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  8887. Diag(Field->getLocation(), diag::note_declared_at);
  8888. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8889. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8890. Invalid = true;
  8891. continue;
  8892. }
  8893. // Check for members of const-qualified, non-class type.
  8894. QualType BaseType = Context.getBaseElementType(Field->getType());
  8895. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  8896. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  8897. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  8898. Diag(Field->getLocation(), diag::note_declared_at);
  8899. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8900. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8901. Invalid = true;
  8902. continue;
  8903. }
  8904. // Suppress assigning zero-width bitfields.
  8905. if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
  8906. continue;
  8907. QualType FieldType = Field->getType().getNonReferenceType();
  8908. if (FieldType->isIncompleteArrayType()) {
  8909. assert(ClassDecl->hasFlexibleArrayMember() &&
  8910. "Incomplete array type is not valid");
  8911. continue;
  8912. }
  8913. // Build references to the field in the object we're copying from and to.
  8914. CXXScopeSpec SS; // Intentionally empty
  8915. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  8916. LookupMemberName);
  8917. MemberLookup.addDecl(Field);
  8918. MemberLookup.resolveKind();
  8919. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  8920. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  8921. // Build the copy of this field.
  8922. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  8923. To, From,
  8924. /*CopyingBaseSubobject=*/false,
  8925. /*Copying=*/true);
  8926. if (Copy.isInvalid()) {
  8927. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8928. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8929. CopyAssignOperator->setInvalidDecl();
  8930. return;
  8931. }
  8932. // Success! Record the copy.
  8933. Statements.push_back(Copy.getAs<Stmt>());
  8934. }
  8935. if (!Invalid) {
  8936. // Add a "return *this;"
  8937. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  8938. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  8939. if (Return.isInvalid())
  8940. Invalid = true;
  8941. else {
  8942. Statements.push_back(Return.getAs<Stmt>());
  8943. if (Trap.hasErrorOccurred()) {
  8944. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8945. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8946. Invalid = true;
  8947. }
  8948. }
  8949. }
  8950. // The exception specification is needed because we are defining the
  8951. // function.
  8952. ResolveExceptionSpec(CurrentLocation,
  8953. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  8954. if (Invalid) {
  8955. CopyAssignOperator->setInvalidDecl();
  8956. return;
  8957. }
  8958. StmtResult Body;
  8959. {
  8960. CompoundScopeRAII CompoundScope(*this);
  8961. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  8962. /*isStmtExpr=*/false);
  8963. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  8964. }
  8965. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  8966. if (ASTMutationListener *L = getASTMutationListener()) {
  8967. L->CompletedImplicitDefinition(CopyAssignOperator);
  8968. }
  8969. }
  8970. Sema::ImplicitExceptionSpecification
  8971. Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
  8972. CXXRecordDecl *ClassDecl = MD->getParent();
  8973. ImplicitExceptionSpecification ExceptSpec(*this);
  8974. if (ClassDecl->isInvalidDecl())
  8975. return ExceptSpec;
  8976. // C++0x [except.spec]p14:
  8977. // An implicitly declared special member function (Clause 12) shall have an
  8978. // exception-specification. [...]
  8979. // It is unspecified whether or not an implicit move assignment operator
  8980. // attempts to deduplicate calls to assignment operators of virtual bases are
  8981. // made. As such, this exception specification is effectively unspecified.
  8982. // Based on a similar decision made for constness in C++0x, we're erring on
  8983. // the side of assuming such calls to be made regardless of whether they
  8984. // actually happen.
  8985. // Note that a move constructor is not implicitly declared when there are
  8986. // virtual bases, but it can still be user-declared and explicitly defaulted.
  8987. for (const auto &Base : ClassDecl->bases()) {
  8988. if (Base.isVirtual())
  8989. continue;
  8990. CXXRecordDecl *BaseClassDecl
  8991. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  8992. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
  8993. 0, false, 0))
  8994. ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
  8995. }
  8996. for (const auto &Base : ClassDecl->vbases()) {
  8997. CXXRecordDecl *BaseClassDecl
  8998. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  8999. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
  9000. 0, false, 0))
  9001. ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
  9002. }
  9003. for (const auto *Field : ClassDecl->fields()) {
  9004. QualType FieldType = Context.getBaseElementType(Field->getType());
  9005. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  9006. if (CXXMethodDecl *MoveAssign =
  9007. LookupMovingAssignment(FieldClassDecl,
  9008. FieldType.getCVRQualifiers(),
  9009. false, 0))
  9010. ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
  9011. }
  9012. }
  9013. return ExceptSpec;
  9014. }
  9015. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  9016. assert(ClassDecl->needsImplicitMoveAssignment());
  9017. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  9018. if (DSM.isAlreadyBeingDeclared())
  9019. return nullptr;
  9020. // Note: The following rules are largely analoguous to the move
  9021. // constructor rules.
  9022. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  9023. QualType RetType = Context.getLValueReferenceType(ArgType);
  9024. ArgType = Context.getRValueReferenceType(ArgType);
  9025. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9026. CXXMoveAssignment,
  9027. false);
  9028. // An implicitly-declared move assignment operator is an inline public
  9029. // member of its class.
  9030. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  9031. SourceLocation ClassLoc = ClassDecl->getLocation();
  9032. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9033. CXXMethodDecl *MoveAssignment =
  9034. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  9035. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  9036. /*isInline=*/true, Constexpr, SourceLocation());
  9037. MoveAssignment->setAccess(AS_public);
  9038. MoveAssignment->setDefaulted();
  9039. MoveAssignment->setImplicit();
  9040. if (getLangOpts().CUDA) {
  9041. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  9042. MoveAssignment,
  9043. /* ConstRHS */ false,
  9044. /* Diagnose */ false);
  9045. }
  9046. // Build an exception specification pointing back at this member.
  9047. FunctionProtoType::ExtProtoInfo EPI =
  9048. getImplicitMethodEPI(*this, MoveAssignment);
  9049. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI, None)); // HLSL Change - add param mods
  9050. // Add the parameter to the operator.
  9051. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  9052. ClassLoc, ClassLoc,
  9053. /*Id=*/nullptr, ArgType,
  9054. /*TInfo=*/nullptr, SC_None,
  9055. nullptr);
  9056. MoveAssignment->setParams(FromParam);
  9057. AddOverriddenMethods(ClassDecl, MoveAssignment);
  9058. MoveAssignment->setTrivial(
  9059. ClassDecl->needsOverloadResolutionForMoveAssignment()
  9060. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  9061. : ClassDecl->hasTrivialMoveAssignment());
  9062. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  9063. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  9064. SetDeclDeleted(MoveAssignment, ClassLoc);
  9065. }
  9066. // Note that we have added this copy-assignment operator.
  9067. ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
  9068. if (Scope *S = getScopeForContext(ClassDecl))
  9069. PushOnScopeChains(MoveAssignment, S, false);
  9070. ClassDecl->addDecl(MoveAssignment);
  9071. return MoveAssignment;
  9072. }
  9073. /// Check if we're implicitly defining a move assignment operator for a class
  9074. /// with virtual bases. Such a move assignment might move-assign the virtual
  9075. /// base multiple times.
  9076. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  9077. SourceLocation CurrentLocation) {
  9078. assert(!Class->isDependentContext() && "should not define dependent move");
  9079. // Only a virtual base could get implicitly move-assigned multiple times.
  9080. // Only a non-trivial move assignment can observe this. We only want to
  9081. // diagnose if we implicitly define an assignment operator that assigns
  9082. // two base classes, both of which move-assign the same virtual base.
  9083. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  9084. Class->getNumBases() < 2)
  9085. return;
  9086. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  9087. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  9088. VBaseMap VBases;
  9089. for (auto &BI : Class->bases()) {
  9090. Worklist.push_back(&BI);
  9091. while (!Worklist.empty()) {
  9092. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  9093. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  9094. // If the base has no non-trivial move assignment operators,
  9095. // we don't care about moves from it.
  9096. if (!Base->hasNonTrivialMoveAssignment())
  9097. continue;
  9098. // If there's nothing virtual here, skip it.
  9099. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  9100. continue;
  9101. // If we're not actually going to call a move assignment for this base,
  9102. // or the selected move assignment is trivial, skip it.
  9103. Sema::SpecialMemberOverloadResult *SMOR =
  9104. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  9105. /*ConstArg*/false, /*VolatileArg*/false,
  9106. /*RValueThis*/true, /*ConstThis*/false,
  9107. /*VolatileThis*/false);
  9108. if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
  9109. !SMOR->getMethod()->isMoveAssignmentOperator())
  9110. continue;
  9111. if (BaseSpec->isVirtual()) {
  9112. // We're going to move-assign this virtual base, and its move
  9113. // assignment operator is not trivial. If this can happen for
  9114. // multiple distinct direct bases of Class, diagnose it. (If it
  9115. // only happens in one base, we'll diagnose it when synthesizing
  9116. // that base class's move assignment operator.)
  9117. CXXBaseSpecifier *&Existing =
  9118. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  9119. .first->second;
  9120. if (Existing && Existing != &BI) {
  9121. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  9122. << Class << Base;
  9123. S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
  9124. << (Base->getCanonicalDecl() ==
  9125. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  9126. << Base << Existing->getType() << Existing->getSourceRange();
  9127. S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
  9128. << (Base->getCanonicalDecl() ==
  9129. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  9130. << Base << BI.getType() << BaseSpec->getSourceRange();
  9131. // Only diagnose each vbase once.
  9132. Existing = nullptr;
  9133. }
  9134. } else {
  9135. // Only walk over bases that have defaulted move assignment operators.
  9136. // We assume that any user-provided move assignment operator handles
  9137. // the multiple-moves-of-vbase case itself somehow.
  9138. if (!SMOR->getMethod()->isDefaulted())
  9139. continue;
  9140. // We're going to move the base classes of Base. Add them to the list.
  9141. for (auto &BI : Base->bases())
  9142. Worklist.push_back(&BI);
  9143. }
  9144. }
  9145. }
  9146. }
  9147. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  9148. CXXMethodDecl *MoveAssignOperator) {
  9149. assert((MoveAssignOperator->isDefaulted() &&
  9150. MoveAssignOperator->isOverloadedOperator() &&
  9151. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  9152. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  9153. !MoveAssignOperator->isDeleted()) &&
  9154. "DefineImplicitMoveAssignment called for wrong function");
  9155. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  9156. if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
  9157. MoveAssignOperator->setInvalidDecl();
  9158. return;
  9159. }
  9160. MoveAssignOperator->markUsed(Context);
  9161. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  9162. DiagnosticErrorTrap Trap(Diags);
  9163. // C++0x [class.copy]p28:
  9164. // The implicitly-defined or move assignment operator for a non-union class
  9165. // X performs memberwise move assignment of its subobjects. The direct base
  9166. // classes of X are assigned first, in the order of their declaration in the
  9167. // base-specifier-list, and then the immediate non-static data members of X
  9168. // are assigned, in the order in which they were declared in the class
  9169. // definition.
  9170. // Issue a warning if our implicit move assignment operator will move
  9171. // from a virtual base more than once.
  9172. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  9173. // The statements that form the synthesized function body.
  9174. SmallVector<Stmt*, 8> Statements;
  9175. // The parameter for the "other" object, which we are move from.
  9176. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  9177. QualType OtherRefType = Other->getType()->
  9178. getAs<RValueReferenceType>()->getPointeeType();
  9179. assert(!OtherRefType.getQualifiers() &&
  9180. "Bad argument type of defaulted move assignment");
  9181. // Our location for everything implicitly-generated.
  9182. SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
  9183. ? MoveAssignOperator->getLocEnd()
  9184. : MoveAssignOperator->getLocation();
  9185. // Builds a reference to the "other" object.
  9186. RefBuilder OtherRef(Other, OtherRefType);
  9187. // Cast to rvalue.
  9188. MoveCastBuilder MoveOther(OtherRef);
  9189. // Builds the "this" pointer.
  9190. ThisBuilder This;
  9191. // Assign base classes.
  9192. bool Invalid = false;
  9193. for (auto &Base : ClassDecl->bases()) {
  9194. // C++11 [class.copy]p28:
  9195. // It is unspecified whether subobjects representing virtual base classes
  9196. // are assigned more than once by the implicitly-defined copy assignment
  9197. // operator.
  9198. // FIXME: Do not assign to a vbase that will be assigned by some other base
  9199. // class. For a move-assignment, this can result in the vbase being moved
  9200. // multiple times.
  9201. // Form the assignment:
  9202. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  9203. QualType BaseType = Base.getType().getUnqualifiedType();
  9204. if (!BaseType->isRecordType()) {
  9205. Invalid = true;
  9206. continue;
  9207. }
  9208. CXXCastPath BasePath;
  9209. BasePath.push_back(&Base);
  9210. // Construct the "from" expression, which is an implicit cast to the
  9211. // appropriately-qualified base type.
  9212. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  9213. // Dereference "this".
  9214. DerefBuilder DerefThis(This);
  9215. // Implicitly cast "this" to the appropriately-qualified base type.
  9216. CastBuilder To(DerefThis,
  9217. Context.getCVRQualifiedType(
  9218. BaseType, MoveAssignOperator->getTypeQualifiers()),
  9219. VK_LValue, BasePath);
  9220. // Build the move.
  9221. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  9222. To, From,
  9223. /*CopyingBaseSubobject=*/true,
  9224. /*Copying=*/false);
  9225. if (Move.isInvalid()) {
  9226. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9227. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9228. MoveAssignOperator->setInvalidDecl();
  9229. return;
  9230. }
  9231. // Success! Record the move.
  9232. Statements.push_back(Move.getAs<Expr>());
  9233. }
  9234. // Assign non-static members.
  9235. for (auto *Field : ClassDecl->fields()) {
  9236. // FIXME: We should form some kind of AST representation for the implied
  9237. // memcpy in a union copy operation.
  9238. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  9239. continue;
  9240. if (Field->isInvalidDecl()) {
  9241. Invalid = true;
  9242. continue;
  9243. }
  9244. // Check for members of reference type; we can't move those.
  9245. if (Field->getType()->isReferenceType()) {
  9246. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  9247. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  9248. Diag(Field->getLocation(), diag::note_declared_at);
  9249. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9250. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9251. Invalid = true;
  9252. continue;
  9253. }
  9254. // Check for members of const-qualified, non-class type.
  9255. QualType BaseType = Context.getBaseElementType(Field->getType());
  9256. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  9257. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  9258. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  9259. Diag(Field->getLocation(), diag::note_declared_at);
  9260. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9261. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9262. Invalid = true;
  9263. continue;
  9264. }
  9265. // Suppress assigning zero-width bitfields.
  9266. if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
  9267. continue;
  9268. QualType FieldType = Field->getType().getNonReferenceType();
  9269. if (FieldType->isIncompleteArrayType()) {
  9270. assert(ClassDecl->hasFlexibleArrayMember() &&
  9271. "Incomplete array type is not valid");
  9272. continue;
  9273. }
  9274. // Build references to the field in the object we're copying from and to.
  9275. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  9276. LookupMemberName);
  9277. MemberLookup.addDecl(Field);
  9278. MemberLookup.resolveKind();
  9279. MemberBuilder From(MoveOther, OtherRefType,
  9280. /*IsArrow=*/false, MemberLookup);
  9281. MemberBuilder To(This, getCurrentThisType(),
  9282. /*IsArrow=*/true, MemberLookup);
  9283. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  9284. "Member reference with rvalue base must be rvalue except for reference "
  9285. "members, which aren't allowed for move assignment.");
  9286. // Build the move of this field.
  9287. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  9288. To, From,
  9289. /*CopyingBaseSubobject=*/false,
  9290. /*Copying=*/false);
  9291. if (Move.isInvalid()) {
  9292. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9293. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9294. MoveAssignOperator->setInvalidDecl();
  9295. return;
  9296. }
  9297. // Success! Record the copy.
  9298. Statements.push_back(Move.getAs<Stmt>());
  9299. }
  9300. if (!Invalid) {
  9301. // Add a "return *this;"
  9302. ExprResult ThisObj =
  9303. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  9304. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  9305. if (Return.isInvalid())
  9306. Invalid = true;
  9307. else {
  9308. Statements.push_back(Return.getAs<Stmt>());
  9309. if (Trap.hasErrorOccurred()) {
  9310. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9311. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9312. Invalid = true;
  9313. }
  9314. }
  9315. }
  9316. // The exception specification is needed because we are defining the
  9317. // function.
  9318. ResolveExceptionSpec(CurrentLocation,
  9319. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  9320. if (Invalid) {
  9321. MoveAssignOperator->setInvalidDecl();
  9322. return;
  9323. }
  9324. StmtResult Body;
  9325. {
  9326. CompoundScopeRAII CompoundScope(*this);
  9327. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  9328. /*isStmtExpr=*/false);
  9329. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  9330. }
  9331. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  9332. if (ASTMutationListener *L = getASTMutationListener()) {
  9333. L->CompletedImplicitDefinition(MoveAssignOperator);
  9334. }
  9335. }
  9336. Sema::ImplicitExceptionSpecification
  9337. Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
  9338. CXXRecordDecl *ClassDecl = MD->getParent();
  9339. ImplicitExceptionSpecification ExceptSpec(*this);
  9340. if (ClassDecl->isInvalidDecl())
  9341. return ExceptSpec;
  9342. const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
  9343. assert(T->getNumParams() >= 1 && "not a copy ctor");
  9344. unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
  9345. // C++ [except.spec]p14:
  9346. // An implicitly declared special member function (Clause 12) shall have an
  9347. // exception-specification. [...]
  9348. for (const auto &Base : ClassDecl->bases()) {
  9349. // Virtual bases are handled below.
  9350. if (Base.isVirtual())
  9351. continue;
  9352. CXXRecordDecl *BaseClassDecl
  9353. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  9354. if (CXXConstructorDecl *CopyConstructor =
  9355. LookupCopyingConstructor(BaseClassDecl, Quals))
  9356. ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
  9357. }
  9358. for (const auto &Base : ClassDecl->vbases()) {
  9359. CXXRecordDecl *BaseClassDecl
  9360. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  9361. if (CXXConstructorDecl *CopyConstructor =
  9362. LookupCopyingConstructor(BaseClassDecl, Quals))
  9363. ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
  9364. }
  9365. for (const auto *Field : ClassDecl->fields()) {
  9366. QualType FieldType = Context.getBaseElementType(Field->getType());
  9367. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  9368. if (CXXConstructorDecl *CopyConstructor =
  9369. LookupCopyingConstructor(FieldClassDecl,
  9370. Quals | FieldType.getCVRQualifiers()))
  9371. ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
  9372. }
  9373. }
  9374. return ExceptSpec;
  9375. }
  9376. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  9377. CXXRecordDecl *ClassDecl) {
  9378. // C++ [class.copy]p4:
  9379. // If the class definition does not explicitly declare a copy
  9380. // constructor, one is declared implicitly.
  9381. assert(ClassDecl->needsImplicitCopyConstructor());
  9382. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  9383. if (DSM.isAlreadyBeingDeclared())
  9384. return nullptr;
  9385. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  9386. QualType ArgType = ClassType;
  9387. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  9388. if (Const)
  9389. ArgType = ArgType.withConst();
  9390. ArgType = Context.getLValueReferenceType(ArgType);
  9391. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9392. CXXCopyConstructor,
  9393. Const);
  9394. DeclarationName Name
  9395. = Context.DeclarationNames.getCXXConstructorName(
  9396. Context.getCanonicalType(ClassType));
  9397. SourceLocation ClassLoc = ClassDecl->getLocation();
  9398. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9399. // An implicitly-declared copy constructor is an inline public
  9400. // member of its class.
  9401. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  9402. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  9403. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  9404. Constexpr);
  9405. CopyConstructor->setAccess(AS_public);
  9406. CopyConstructor->setDefaulted();
  9407. if (getLangOpts().CUDA) {
  9408. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  9409. CopyConstructor,
  9410. /* ConstRHS */ Const,
  9411. /* Diagnose */ false);
  9412. }
  9413. // Build an exception specification pointing back at this member.
  9414. FunctionProtoType::ExtProtoInfo EPI =
  9415. getImplicitMethodEPI(*this, CopyConstructor);
  9416. CopyConstructor->setType(
  9417. Context.getFunctionType(Context.VoidTy, ArgType, EPI, None)); // HLSL Change - add param mods
  9418. // Add the parameter to the constructor.
  9419. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  9420. ClassLoc, ClassLoc,
  9421. /*IdentifierInfo=*/nullptr,
  9422. ArgType, /*TInfo=*/nullptr,
  9423. SC_None, nullptr);
  9424. CopyConstructor->setParams(FromParam);
  9425. CopyConstructor->setTrivial(
  9426. ClassDecl->needsOverloadResolutionForCopyConstructor()
  9427. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  9428. : ClassDecl->hasTrivialCopyConstructor());
  9429. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
  9430. SetDeclDeleted(CopyConstructor, ClassLoc);
  9431. // Note that we have declared this constructor.
  9432. ++ASTContext::NumImplicitCopyConstructorsDeclared;
  9433. if (Scope *S = getScopeForContext(ClassDecl))
  9434. PushOnScopeChains(CopyConstructor, S, false);
  9435. ClassDecl->addDecl(CopyConstructor);
  9436. return CopyConstructor;
  9437. }
  9438. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  9439. CXXConstructorDecl *CopyConstructor) {
  9440. assert((CopyConstructor->isDefaulted() &&
  9441. CopyConstructor->isCopyConstructor() &&
  9442. !CopyConstructor->doesThisDeclarationHaveABody() &&
  9443. !CopyConstructor->isDeleted()) &&
  9444. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  9445. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  9446. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  9447. // C++11 [class.copy]p7:
  9448. // The [definition of an implicitly declared copy constructor] is
  9449. // deprecated if the class has a user-declared copy assignment operator
  9450. // or a user-declared destructor.
  9451. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  9452. diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
  9453. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  9454. DiagnosticErrorTrap Trap(Diags);
  9455. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
  9456. Trap.hasErrorOccurred()) {
  9457. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9458. << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
  9459. CopyConstructor->setInvalidDecl();
  9460. } else {
  9461. SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
  9462. ? CopyConstructor->getLocEnd()
  9463. : CopyConstructor->getLocation();
  9464. Sema::CompoundScopeRAII CompoundScope(*this);
  9465. CopyConstructor->setBody(
  9466. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  9467. }
  9468. // The exception specification is needed because we are defining the
  9469. // function.
  9470. ResolveExceptionSpec(CurrentLocation,
  9471. CopyConstructor->getType()->castAs<FunctionProtoType>());
  9472. CopyConstructor->markUsed(Context);
  9473. MarkVTableUsed(CurrentLocation, ClassDecl);
  9474. if (ASTMutationListener *L = getASTMutationListener()) {
  9475. L->CompletedImplicitDefinition(CopyConstructor);
  9476. }
  9477. }
  9478. Sema::ImplicitExceptionSpecification
  9479. Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
  9480. CXXRecordDecl *ClassDecl = MD->getParent();
  9481. // C++ [except.spec]p14:
  9482. // An implicitly declared special member function (Clause 12) shall have an
  9483. // exception-specification. [...]
  9484. ImplicitExceptionSpecification ExceptSpec(*this);
  9485. if (ClassDecl->isInvalidDecl())
  9486. return ExceptSpec;
  9487. // Direct base-class constructors.
  9488. for (const auto &B : ClassDecl->bases()) {
  9489. if (B.isVirtual()) // Handled below.
  9490. continue;
  9491. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  9492. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  9493. CXXConstructorDecl *Constructor =
  9494. LookupMovingConstructor(BaseClassDecl, 0);
  9495. // If this is a deleted function, add it anyway. This might be conformant
  9496. // with the standard. This might not. I'm not sure. It might not matter.
  9497. if (Constructor)
  9498. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  9499. }
  9500. }
  9501. // Virtual base-class constructors.
  9502. for (const auto &B : ClassDecl->vbases()) {
  9503. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  9504. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  9505. CXXConstructorDecl *Constructor =
  9506. LookupMovingConstructor(BaseClassDecl, 0);
  9507. // If this is a deleted function, add it anyway. This might be conformant
  9508. // with the standard. This might not. I'm not sure. It might not matter.
  9509. if (Constructor)
  9510. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  9511. }
  9512. }
  9513. // Field constructors.
  9514. for (const auto *F : ClassDecl->fields()) {
  9515. QualType FieldType = Context.getBaseElementType(F->getType());
  9516. if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
  9517. CXXConstructorDecl *Constructor =
  9518. LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
  9519. // If this is a deleted function, add it anyway. This might be conformant
  9520. // with the standard. This might not. I'm not sure. It might not matter.
  9521. // In particular, the problem is that this function never gets called. It
  9522. // might just be ill-formed because this function attempts to refer to
  9523. // a deleted function here.
  9524. if (Constructor)
  9525. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  9526. }
  9527. }
  9528. return ExceptSpec;
  9529. }
  9530. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  9531. CXXRecordDecl *ClassDecl) {
  9532. assert(ClassDecl->needsImplicitMoveConstructor());
  9533. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  9534. if (DSM.isAlreadyBeingDeclared())
  9535. return nullptr;
  9536. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  9537. QualType ArgType = Context.getRValueReferenceType(ClassType);
  9538. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9539. CXXMoveConstructor,
  9540. false);
  9541. DeclarationName Name
  9542. = Context.DeclarationNames.getCXXConstructorName(
  9543. Context.getCanonicalType(ClassType));
  9544. SourceLocation ClassLoc = ClassDecl->getLocation();
  9545. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9546. // C++11 [class.copy]p11:
  9547. // An implicitly-declared copy/move constructor is an inline public
  9548. // member of its class.
  9549. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  9550. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  9551. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  9552. Constexpr);
  9553. MoveConstructor->setAccess(AS_public);
  9554. MoveConstructor->setDefaulted();
  9555. if (getLangOpts().CUDA) {
  9556. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  9557. MoveConstructor,
  9558. /* ConstRHS */ false,
  9559. /* Diagnose */ false);
  9560. }
  9561. // Build an exception specification pointing back at this member.
  9562. FunctionProtoType::ExtProtoInfo EPI =
  9563. getImplicitMethodEPI(*this, MoveConstructor);
  9564. MoveConstructor->setType(
  9565. Context.getFunctionType(Context.VoidTy, ArgType, EPI, None)); // HLSL Change - all in-args
  9566. // Add the parameter to the constructor.
  9567. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  9568. ClassLoc, ClassLoc,
  9569. /*IdentifierInfo=*/nullptr,
  9570. ArgType, /*TInfo=*/nullptr,
  9571. SC_None, nullptr);
  9572. MoveConstructor->setParams(FromParam);
  9573. MoveConstructor->setTrivial(
  9574. ClassDecl->needsOverloadResolutionForMoveConstructor()
  9575. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  9576. : ClassDecl->hasTrivialMoveConstructor());
  9577. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  9578. ClassDecl->setImplicitMoveConstructorIsDeleted();
  9579. SetDeclDeleted(MoveConstructor, ClassLoc);
  9580. }
  9581. // Note that we have declared this constructor.
  9582. ++ASTContext::NumImplicitMoveConstructorsDeclared;
  9583. if (Scope *S = getScopeForContext(ClassDecl))
  9584. PushOnScopeChains(MoveConstructor, S, false);
  9585. ClassDecl->addDecl(MoveConstructor);
  9586. return MoveConstructor;
  9587. }
  9588. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  9589. CXXConstructorDecl *MoveConstructor) {
  9590. assert((MoveConstructor->isDefaulted() &&
  9591. MoveConstructor->isMoveConstructor() &&
  9592. !MoveConstructor->doesThisDeclarationHaveABody() &&
  9593. !MoveConstructor->isDeleted()) &&
  9594. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  9595. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  9596. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  9597. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  9598. DiagnosticErrorTrap Trap(Diags);
  9599. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
  9600. Trap.hasErrorOccurred()) {
  9601. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9602. << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
  9603. MoveConstructor->setInvalidDecl();
  9604. } else {
  9605. SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
  9606. ? MoveConstructor->getLocEnd()
  9607. : MoveConstructor->getLocation();
  9608. Sema::CompoundScopeRAII CompoundScope(*this);
  9609. MoveConstructor->setBody(ActOnCompoundStmt(
  9610. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  9611. }
  9612. // The exception specification is needed because we are defining the
  9613. // function.
  9614. ResolveExceptionSpec(CurrentLocation,
  9615. MoveConstructor->getType()->castAs<FunctionProtoType>());
  9616. MoveConstructor->markUsed(Context);
  9617. MarkVTableUsed(CurrentLocation, ClassDecl);
  9618. if (ASTMutationListener *L = getASTMutationListener()) {
  9619. L->CompletedImplicitDefinition(MoveConstructor);
  9620. }
  9621. }
  9622. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  9623. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  9624. }
  9625. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  9626. SourceLocation CurrentLocation,
  9627. CXXConversionDecl *Conv) {
  9628. CXXRecordDecl *Lambda = Conv->getParent();
  9629. CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  9630. // If we are defining a specialization of a conversion to function-ptr
  9631. // cache the deduced template arguments for this specialization
  9632. // so that we can use them to retrieve the corresponding call-operator
  9633. // and static-invoker.
  9634. const TemplateArgumentList *DeducedTemplateArgs = nullptr;
  9635. // Retrieve the corresponding call-operator specialization.
  9636. if (Lambda->isGenericLambda()) {
  9637. assert(Conv->isFunctionTemplateSpecialization());
  9638. FunctionTemplateDecl *CallOpTemplate =
  9639. CallOp->getDescribedFunctionTemplate();
  9640. DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
  9641. void *InsertPos = nullptr;
  9642. FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
  9643. DeducedTemplateArgs->asArray(),
  9644. InsertPos);
  9645. assert(CallOpSpec &&
  9646. "Conversion operator must have a corresponding call operator");
  9647. CallOp = cast<CXXMethodDecl>(CallOpSpec);
  9648. }
  9649. // Mark the call operator referenced (and add to pending instantiations
  9650. // if necessary).
  9651. // For both the conversion and static-invoker template specializations
  9652. // we construct their body's in this function, so no need to add them
  9653. // to the PendingInstantiations.
  9654. MarkFunctionReferenced(CurrentLocation, CallOp);
  9655. SynthesizedFunctionScope Scope(*this, Conv);
  9656. DiagnosticErrorTrap Trap(Diags);
  9657. // Retrieve the static invoker...
  9658. CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
  9659. // ... and get the corresponding specialization for a generic lambda.
  9660. if (Lambda->isGenericLambda()) {
  9661. assert(DeducedTemplateArgs &&
  9662. "Must have deduced template arguments from Conversion Operator");
  9663. FunctionTemplateDecl *InvokeTemplate =
  9664. Invoker->getDescribedFunctionTemplate();
  9665. void *InsertPos = nullptr;
  9666. FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
  9667. DeducedTemplateArgs->asArray(),
  9668. InsertPos);
  9669. assert(InvokeSpec &&
  9670. "Must have a corresponding static invoker specialization");
  9671. Invoker = cast<CXXMethodDecl>(InvokeSpec);
  9672. }
  9673. // Construct the body of the conversion function { return __invoke; }.
  9674. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  9675. VK_LValue, Conv->getLocation()).get();
  9676. assert(FunctionRef && "Can't refer to __invoke function?");
  9677. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  9678. Conv->setBody(new (Context) CompoundStmt(Context, Return,
  9679. Conv->getLocation(),
  9680. Conv->getLocation()));
  9681. Conv->markUsed(Context);
  9682. Conv->setReferenced();
  9683. // Fill in the __invoke function with a dummy implementation. IR generation
  9684. // will fill in the actual details.
  9685. Invoker->markUsed(Context);
  9686. Invoker->setReferenced();
  9687. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  9688. if (ASTMutationListener *L = getASTMutationListener()) {
  9689. L->CompletedImplicitDefinition(Conv);
  9690. L->CompletedImplicitDefinition(Invoker);
  9691. }
  9692. }
  9693. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  9694. SourceLocation CurrentLocation,
  9695. CXXConversionDecl *Conv)
  9696. {
  9697. assert(!Conv->getParent()->isGenericLambda());
  9698. Conv->markUsed(Context);
  9699. SynthesizedFunctionScope Scope(*this, Conv);
  9700. DiagnosticErrorTrap Trap(Diags);
  9701. // Copy-initialize the lambda object as needed to capture it.
  9702. Expr *This = ActOnCXXThis(CurrentLocation).get();
  9703. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  9704. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  9705. Conv->getLocation(),
  9706. Conv, DerefThis);
  9707. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  9708. // behavior. Note that only the general conversion function does this
  9709. // (since it's unusable otherwise); in the case where we inline the
  9710. // block literal, it has block literal lifetime semantics.
  9711. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  9712. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  9713. CK_CopyAndAutoreleaseBlockObject,
  9714. BuildBlock.get(), nullptr, VK_RValue);
  9715. if (BuildBlock.isInvalid()) {
  9716. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  9717. Conv->setInvalidDecl();
  9718. return;
  9719. }
  9720. // Create the return statement that returns the block from the conversion
  9721. // function.
  9722. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  9723. if (Return.isInvalid()) {
  9724. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  9725. Conv->setInvalidDecl();
  9726. return;
  9727. }
  9728. // Set the body of the conversion function.
  9729. Stmt *ReturnS = Return.get();
  9730. Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
  9731. Conv->getLocation(),
  9732. Conv->getLocation()));
  9733. // We're done; notify the mutation listener, if any.
  9734. if (ASTMutationListener *L = getASTMutationListener()) {
  9735. L->CompletedImplicitDefinition(Conv);
  9736. }
  9737. }
  9738. /// \brief Determine whether the given list arguments contains exactly one
  9739. /// "real" (non-default) argument.
  9740. static bool hasOneRealArgument(MultiExprArg Args) {
  9741. switch (Args.size()) {
  9742. case 0:
  9743. return false;
  9744. default:
  9745. if (!Args[1]->isDefaultArgument())
  9746. return false;
  9747. // fall through
  9748. case 1:
  9749. return !Args[0]->isDefaultArgument();
  9750. }
  9751. return false;
  9752. }
  9753. ExprResult
  9754. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  9755. CXXConstructorDecl *Constructor,
  9756. MultiExprArg ExprArgs,
  9757. bool HadMultipleCandidates,
  9758. bool IsListInitialization,
  9759. bool IsStdInitListInitialization,
  9760. bool RequiresZeroInit,
  9761. unsigned ConstructKind,
  9762. SourceRange ParenRange) {
  9763. bool Elidable = false;
  9764. // C++0x [class.copy]p34:
  9765. // When certain criteria are met, an implementation is allowed to
  9766. // omit the copy/move construction of a class object, even if the
  9767. // copy/move constructor and/or destructor for the object have
  9768. // side effects. [...]
  9769. // - when a temporary class object that has not been bound to a
  9770. // reference (12.2) would be copied/moved to a class object
  9771. // with the same cv-unqualified type, the copy/move operation
  9772. // can be omitted by constructing the temporary object
  9773. // directly into the target of the omitted copy/move
  9774. if (ConstructKind == CXXConstructExpr::CK_Complete &&
  9775. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  9776. Expr *SubExpr = ExprArgs[0];
  9777. Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
  9778. }
  9779. return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
  9780. Elidable, ExprArgs, HadMultipleCandidates,
  9781. IsListInitialization,
  9782. IsStdInitListInitialization, RequiresZeroInit,
  9783. ConstructKind, ParenRange);
  9784. }
  9785. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  9786. /// including handling of its default argument expressions.
  9787. ExprResult
  9788. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  9789. CXXConstructorDecl *Constructor, bool Elidable,
  9790. MultiExprArg ExprArgs,
  9791. bool HadMultipleCandidates,
  9792. bool IsListInitialization,
  9793. bool IsStdInitListInitialization,
  9794. bool RequiresZeroInit,
  9795. unsigned ConstructKind,
  9796. SourceRange ParenRange) {
  9797. MarkFunctionReferenced(ConstructLoc, Constructor);
  9798. return CXXConstructExpr::Create(
  9799. Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
  9800. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  9801. RequiresZeroInit,
  9802. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  9803. ParenRange);
  9804. }
  9805. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  9806. assert(Field->hasInClassInitializer());
  9807. // If we already have the in-class initializer nothing needs to be done.
  9808. if (Field->getInClassInitializer())
  9809. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  9810. // Maybe we haven't instantiated the in-class initializer. Go check the
  9811. // pattern FieldDecl to see if it has one.
  9812. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  9813. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  9814. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  9815. DeclContext::lookup_result Lookup =
  9816. ClassPattern->lookup(Field->getDeclName());
  9817. assert(Lookup.size() == 1);
  9818. FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
  9819. if (InstantiateInClassInitializer(Loc, Field, Pattern,
  9820. getTemplateInstantiationArgs(Field)))
  9821. return ExprError();
  9822. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  9823. }
  9824. // DR1351:
  9825. // If the brace-or-equal-initializer of a non-static data member
  9826. // invokes a defaulted default constructor of its class or of an
  9827. // enclosing class in a potentially evaluated subexpression, the
  9828. // program is ill-formed.
  9829. //
  9830. // This resolution is unworkable: the exception specification of the
  9831. // default constructor can be needed in an unevaluated context, in
  9832. // particular, in the operand of a noexcept-expression, and we can be
  9833. // unable to compute an exception specification for an enclosed class.
  9834. //
  9835. // Any attempt to resolve the exception specification of a defaulted default
  9836. // constructor before the initializer is lexically complete will ultimately
  9837. // come here at which point we can diagnose it.
  9838. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  9839. if (OutermostClass == ParentRD) {
  9840. Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
  9841. << ParentRD << Field;
  9842. } else {
  9843. Diag(Field->getLocEnd(),
  9844. diag::err_in_class_initializer_not_yet_parsed_outer_class)
  9845. << ParentRD << OutermostClass << Field;
  9846. }
  9847. return ExprError();
  9848. }
  9849. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  9850. if (VD->isInvalidDecl()) return;
  9851. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  9852. if (ClassDecl->isInvalidDecl()) return;
  9853. if (ClassDecl->hasIrrelevantDestructor()) return;
  9854. if (ClassDecl->isDependentContext()) return;
  9855. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  9856. MarkFunctionReferenced(VD->getLocation(), Destructor);
  9857. CheckDestructorAccess(VD->getLocation(), Destructor,
  9858. PDiag(diag::err_access_dtor_var)
  9859. << VD->getDeclName()
  9860. << VD->getType());
  9861. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  9862. if (Destructor->isTrivial()) return;
  9863. if (!VD->hasGlobalStorage()) return;
  9864. // Emit warning for non-trivial dtor in global scope (a real global,
  9865. // class-static, function-static).
  9866. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  9867. // TODO: this should be re-enabled for static locals by !CXAAtExit
  9868. if (!VD->isStaticLocal())
  9869. Diag(VD->getLocation(), diag::warn_global_destructor);
  9870. }
  9871. /// \brief Given a constructor and the set of arguments provided for the
  9872. /// constructor, convert the arguments and add any required default arguments
  9873. /// to form a proper call to this constructor.
  9874. ///
  9875. /// \returns true if an error occurred, false otherwise.
  9876. bool
  9877. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  9878. MultiExprArg ArgsPtr,
  9879. SourceLocation Loc,
  9880. SmallVectorImpl<Expr*> &ConvertedArgs,
  9881. bool AllowExplicit,
  9882. bool IsListInitialization) {
  9883. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  9884. unsigned NumArgs = ArgsPtr.size();
  9885. Expr **Args = ArgsPtr.data();
  9886. const FunctionProtoType *Proto
  9887. = Constructor->getType()->getAs<FunctionProtoType>();
  9888. assert(Proto && "Constructor without a prototype?");
  9889. unsigned NumParams = Proto->getNumParams();
  9890. // If too few arguments are available, we'll fill in the rest with defaults.
  9891. if (NumArgs < NumParams)
  9892. ConvertedArgs.reserve(NumParams);
  9893. else
  9894. ConvertedArgs.reserve(NumArgs);
  9895. VariadicCallType CallType =
  9896. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  9897. SmallVector<Expr *, 8> AllArgs;
  9898. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  9899. Proto, 0,
  9900. llvm::makeArrayRef(Args, NumArgs),
  9901. AllArgs,
  9902. CallType, AllowExplicit,
  9903. IsListInitialization);
  9904. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  9905. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  9906. CheckConstructorCall(Constructor,
  9907. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  9908. Proto, Loc);
  9909. return Invalid;
  9910. }
  9911. static inline bool
  9912. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  9913. const FunctionDecl *FnDecl) {
  9914. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  9915. if (isa<NamespaceDecl>(DC)) {
  9916. return SemaRef.Diag(FnDecl->getLocation(),
  9917. diag::err_operator_new_delete_declared_in_namespace)
  9918. << FnDecl->getDeclName();
  9919. }
  9920. if (isa<TranslationUnitDecl>(DC) &&
  9921. FnDecl->getStorageClass() == SC_Static) {
  9922. return SemaRef.Diag(FnDecl->getLocation(),
  9923. diag::err_operator_new_delete_declared_static)
  9924. << FnDecl->getDeclName();
  9925. }
  9926. return false;
  9927. }
  9928. static inline bool
  9929. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  9930. CanQualType ExpectedResultType,
  9931. CanQualType ExpectedFirstParamType,
  9932. unsigned DependentParamTypeDiag,
  9933. unsigned InvalidParamTypeDiag) {
  9934. QualType ResultType =
  9935. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  9936. // Check that the result type is not dependent.
  9937. if (ResultType->isDependentType())
  9938. return SemaRef.Diag(FnDecl->getLocation(),
  9939. diag::err_operator_new_delete_dependent_result_type)
  9940. << FnDecl->getDeclName() << ExpectedResultType;
  9941. // Check that the result type is what we expect.
  9942. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  9943. return SemaRef.Diag(FnDecl->getLocation(),
  9944. diag::err_operator_new_delete_invalid_result_type)
  9945. << FnDecl->getDeclName() << ExpectedResultType;
  9946. // A function template must have at least 2 parameters.
  9947. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  9948. return SemaRef.Diag(FnDecl->getLocation(),
  9949. diag::err_operator_new_delete_template_too_few_parameters)
  9950. << FnDecl->getDeclName();
  9951. // The function decl must have at least 1 parameter.
  9952. if (FnDecl->getNumParams() == 0)
  9953. return SemaRef.Diag(FnDecl->getLocation(),
  9954. diag::err_operator_new_delete_too_few_parameters)
  9955. << FnDecl->getDeclName();
  9956. // Check the first parameter type is not dependent.
  9957. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  9958. if (FirstParamType->isDependentType())
  9959. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  9960. << FnDecl->getDeclName() << ExpectedFirstParamType;
  9961. // Check that the first parameter type is what we expect.
  9962. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  9963. ExpectedFirstParamType)
  9964. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  9965. << FnDecl->getDeclName() << ExpectedFirstParamType;
  9966. return false;
  9967. }
  9968. static bool
  9969. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  9970. // C++ [basic.stc.dynamic.allocation]p1:
  9971. // A program is ill-formed if an allocation function is declared in a
  9972. // namespace scope other than global scope or declared static in global
  9973. // scope.
  9974. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  9975. return true;
  9976. CanQualType SizeTy =
  9977. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  9978. // C++ [basic.stc.dynamic.allocation]p1:
  9979. // The return type shall be void*. The first parameter shall have type
  9980. // std::size_t.
  9981. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  9982. SizeTy,
  9983. diag::err_operator_new_dependent_param_type,
  9984. diag::err_operator_new_param_type))
  9985. return true;
  9986. // C++ [basic.stc.dynamic.allocation]p1:
  9987. // The first parameter shall not have an associated default argument.
  9988. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  9989. return SemaRef.Diag(FnDecl->getLocation(),
  9990. diag::err_operator_new_default_arg)
  9991. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  9992. return false;
  9993. }
  9994. static bool
  9995. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  9996. // C++ [basic.stc.dynamic.deallocation]p1:
  9997. // A program is ill-formed if deallocation functions are declared in a
  9998. // namespace scope other than global scope or declared static in global
  9999. // scope.
  10000. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  10001. return true;
  10002. // C++ [basic.stc.dynamic.deallocation]p2:
  10003. // Each deallocation function shall return void and its first parameter
  10004. // shall be void*.
  10005. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
  10006. SemaRef.Context.VoidPtrTy,
  10007. diag::err_operator_delete_dependent_param_type,
  10008. diag::err_operator_delete_param_type))
  10009. return true;
  10010. return false;
  10011. }
  10012. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  10013. /// of this overloaded operator is well-formed. If so, returns false;
  10014. /// otherwise, emits appropriate diagnostics and returns true.
  10015. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  10016. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  10017. "Expected an overloaded operator declaration");
  10018. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  10019. // C++ [over.oper]p5:
  10020. // The allocation and deallocation functions, operator new,
  10021. // operator new[], operator delete and operator delete[], are
  10022. // described completely in 3.7.3. The attributes and restrictions
  10023. // found in the rest of this subclause do not apply to them unless
  10024. // explicitly stated in 3.7.3.
  10025. if (Op == OO_Delete || Op == OO_Array_Delete)
  10026. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  10027. if (Op == OO_New || Op == OO_Array_New)
  10028. return CheckOperatorNewDeclaration(*this, FnDecl);
  10029. // C++ [over.oper]p6:
  10030. // An operator function shall either be a non-static member
  10031. // function or be a non-member function and have at least one
  10032. // parameter whose type is a class, a reference to a class, an
  10033. // enumeration, or a reference to an enumeration.
  10034. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  10035. if (MethodDecl->isStatic())
  10036. return Diag(FnDecl->getLocation(),
  10037. diag::err_operator_overload_static) << FnDecl->getDeclName();
  10038. } else {
  10039. bool ClassOrEnumParam = false;
  10040. for (auto Param : FnDecl->params()) {
  10041. QualType ParamType = Param->getType().getNonReferenceType();
  10042. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  10043. ParamType->isEnumeralType()) {
  10044. ClassOrEnumParam = true;
  10045. break;
  10046. }
  10047. }
  10048. if (!ClassOrEnumParam)
  10049. return Diag(FnDecl->getLocation(),
  10050. diag::err_operator_overload_needs_class_or_enum)
  10051. << FnDecl->getDeclName();
  10052. }
  10053. // C++ [over.oper]p8:
  10054. // An operator function cannot have default arguments (8.3.6),
  10055. // except where explicitly stated below.
  10056. //
  10057. // Only the function-call operator allows default arguments
  10058. // (C++ [over.call]p1).
  10059. if (Op != OO_Call) {
  10060. for (auto Param : FnDecl->params()) {
  10061. if (Param->hasDefaultArg())
  10062. return Diag(Param->getLocation(),
  10063. diag::err_operator_overload_default_arg)
  10064. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  10065. }
  10066. }
  10067. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  10068. { false, false, false }
  10069. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  10070. , { Unary, Binary, MemberOnly }
  10071. #include "clang/Basic/OperatorKinds.def"
  10072. };
  10073. bool CanBeUnaryOperator = OperatorUses[Op][0];
  10074. bool CanBeBinaryOperator = OperatorUses[Op][1];
  10075. bool MustBeMemberOperator = OperatorUses[Op][2];
  10076. // C++ [over.oper]p8:
  10077. // [...] Operator functions cannot have more or fewer parameters
  10078. // than the number required for the corresponding operator, as
  10079. // described in the rest of this subclause.
  10080. unsigned NumParams = FnDecl->getNumParams()
  10081. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  10082. if (Op != OO_Call &&
  10083. ((NumParams == 1 && !CanBeUnaryOperator) ||
  10084. (NumParams == 2 && !CanBeBinaryOperator) ||
  10085. (NumParams < 1) || (NumParams > 2))) {
  10086. // We have the wrong number of parameters.
  10087. unsigned ErrorKind;
  10088. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  10089. ErrorKind = 2; // 2 -> unary or binary.
  10090. } else if (CanBeUnaryOperator) {
  10091. ErrorKind = 0; // 0 -> unary
  10092. } else {
  10093. assert(CanBeBinaryOperator &&
  10094. "All non-call overloaded operators are unary or binary!");
  10095. ErrorKind = 1; // 1 -> binary
  10096. }
  10097. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  10098. << FnDecl->getDeclName() << NumParams << ErrorKind;
  10099. }
  10100. // Overloaded operators other than operator() cannot be variadic.
  10101. if (Op != OO_Call &&
  10102. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  10103. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  10104. << FnDecl->getDeclName();
  10105. }
  10106. // Some operators must be non-static member functions.
  10107. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  10108. return Diag(FnDecl->getLocation(),
  10109. diag::err_operator_overload_must_be_member)
  10110. << FnDecl->getDeclName();
  10111. }
  10112. // C++ [over.inc]p1:
  10113. // The user-defined function called operator++ implements the
  10114. // prefix and postfix ++ operator. If this function is a member
  10115. // function with no parameters, or a non-member function with one
  10116. // parameter of class or enumeration type, it defines the prefix
  10117. // increment operator ++ for objects of that type. If the function
  10118. // is a member function with one parameter (which shall be of type
  10119. // int) or a non-member function with two parameters (the second
  10120. // of which shall be of type int), it defines the postfix
  10121. // increment operator ++ for objects of that type.
  10122. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  10123. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  10124. QualType ParamType = LastParam->getType();
  10125. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  10126. !ParamType->isDependentType())
  10127. return Diag(LastParam->getLocation(),
  10128. diag::err_operator_overload_post_incdec_must_be_int)
  10129. << LastParam->getType() << (Op == OO_MinusMinus);
  10130. }
  10131. return false;
  10132. }
  10133. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  10134. /// of this literal operator function is well-formed. If so, returns
  10135. /// false; otherwise, emits appropriate diagnostics and returns true.
  10136. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  10137. if (isa<CXXMethodDecl>(FnDecl)) {
  10138. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  10139. << FnDecl->getDeclName();
  10140. return true;
  10141. }
  10142. if (FnDecl->isExternC()) {
  10143. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  10144. return true;
  10145. }
  10146. bool Valid = false;
  10147. // This might be the definition of a literal operator template.
  10148. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  10149. // This might be a specialization of a literal operator template.
  10150. if (!TpDecl)
  10151. TpDecl = FnDecl->getPrimaryTemplate();
  10152. // template <char...> type operator "" name() and
  10153. // template <class T, T...> type operator "" name() are the only valid
  10154. // template signatures, and the only valid signatures with no parameters.
  10155. if (TpDecl) {
  10156. if (FnDecl->param_size() == 0) {
  10157. // Must have one or two template parameters
  10158. TemplateParameterList *Params = TpDecl->getTemplateParameters();
  10159. if (Params->size() == 1) {
  10160. NonTypeTemplateParmDecl *PmDecl =
  10161. dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
  10162. // The template parameter must be a char parameter pack.
  10163. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  10164. Context.hasSameType(PmDecl->getType(), Context.CharTy))
  10165. Valid = true;
  10166. } else if (Params->size() == 2) {
  10167. TemplateTypeParmDecl *PmType =
  10168. dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
  10169. NonTypeTemplateParmDecl *PmArgs =
  10170. dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
  10171. // The second template parameter must be a parameter pack with the
  10172. // first template parameter as its type.
  10173. if (PmType && PmArgs &&
  10174. !PmType->isTemplateParameterPack() &&
  10175. PmArgs->isTemplateParameterPack()) {
  10176. const TemplateTypeParmType *TArgs =
  10177. PmArgs->getType()->getAs<TemplateTypeParmType>();
  10178. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  10179. TArgs->getIndex() == PmType->getIndex()) {
  10180. Valid = true;
  10181. if (ActiveTemplateInstantiations.empty())
  10182. Diag(FnDecl->getLocation(),
  10183. diag::ext_string_literal_operator_template);
  10184. }
  10185. }
  10186. }
  10187. }
  10188. } else if (FnDecl->param_size()) {
  10189. // Check the first parameter
  10190. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  10191. QualType T = (*Param)->getType().getUnqualifiedType();
  10192. // unsigned long long int, long double, and any character type are allowed
  10193. // as the only parameters.
  10194. if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
  10195. Context.hasSameType(T, Context.LongDoubleTy) ||
  10196. Context.hasSameType(T, Context.CharTy) ||
  10197. Context.hasSameType(T, Context.WideCharTy) ||
  10198. Context.hasSameType(T, Context.Char16Ty) ||
  10199. Context.hasSameType(T, Context.Char32Ty)) {
  10200. if (++Param == FnDecl->param_end())
  10201. Valid = true;
  10202. goto FinishedParams;
  10203. }
  10204. // Otherwise it must be a pointer to const; let's strip those qualifiers.
  10205. const PointerType *PT = T->getAs<PointerType>();
  10206. if (!PT)
  10207. goto FinishedParams;
  10208. T = PT->getPointeeType();
  10209. if (!T.isConstQualified() || T.isVolatileQualified())
  10210. goto FinishedParams;
  10211. T = T.getUnqualifiedType();
  10212. // Move on to the second parameter;
  10213. ++Param;
  10214. // If there is no second parameter, the first must be a const char *
  10215. if (Param == FnDecl->param_end()) {
  10216. if (Context.hasSameType(T, Context.CharTy))
  10217. Valid = true;
  10218. goto FinishedParams;
  10219. }
  10220. // const char *, const wchar_t*, const char16_t*, and const char32_t*
  10221. // are allowed as the first parameter to a two-parameter function
  10222. if (!(Context.hasSameType(T, Context.CharTy) ||
  10223. Context.hasSameType(T, Context.WideCharTy) ||
  10224. Context.hasSameType(T, Context.Char16Ty) ||
  10225. Context.hasSameType(T, Context.Char32Ty)))
  10226. goto FinishedParams;
  10227. // The second and final parameter must be an std::size_t
  10228. T = (*Param)->getType().getUnqualifiedType();
  10229. if (Context.hasSameType(T, Context.getSizeType()) &&
  10230. ++Param == FnDecl->param_end())
  10231. Valid = true;
  10232. }
  10233. // FIXME: This diagnostic is absolutely terrible.
  10234. FinishedParams:
  10235. if (!Valid) {
  10236. Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
  10237. << FnDecl->getDeclName();
  10238. return true;
  10239. }
  10240. // A parameter-declaration-clause containing a default argument is not
  10241. // equivalent to any of the permitted forms.
  10242. for (auto Param : FnDecl->params()) {
  10243. if (Param->hasDefaultArg()) {
  10244. Diag(Param->getDefaultArgRange().getBegin(),
  10245. diag::err_literal_operator_default_argument)
  10246. << Param->getDefaultArgRange();
  10247. break;
  10248. }
  10249. }
  10250. StringRef LiteralName
  10251. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  10252. if (LiteralName[0] != '_') {
  10253. // C++11 [usrlit.suffix]p1:
  10254. // Literal suffix identifiers that do not start with an underscore
  10255. // are reserved for future standardization.
  10256. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  10257. << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  10258. }
  10259. return false;
  10260. }
  10261. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  10262. /// linkage specification, including the language and (if present)
  10263. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  10264. /// language string literal. LBraceLoc, if valid, provides the location of
  10265. /// the '{' brace. Otherwise, this linkage specification does not
  10266. /// have any braces.
  10267. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  10268. Expr *LangStr,
  10269. SourceLocation LBraceLoc) {
  10270. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  10271. if (!Lit->isAscii()) {
  10272. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  10273. << LangStr->getSourceRange();
  10274. return nullptr;
  10275. }
  10276. StringRef Lang = Lit->getString();
  10277. LinkageSpecDecl::LanguageIDs Language;
  10278. if (Lang == "C")
  10279. Language = LinkageSpecDecl::lang_c;
  10280. else if (Lang == "C++")
  10281. Language = LinkageSpecDecl::lang_cxx;
  10282. else {
  10283. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  10284. << LangStr->getSourceRange();
  10285. return nullptr;
  10286. }
  10287. // FIXME: Add all the various semantics of linkage specifications
  10288. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  10289. LangStr->getExprLoc(), Language,
  10290. LBraceLoc.isValid());
  10291. CurContext->addDecl(D);
  10292. PushDeclContext(S, D);
  10293. return D;
  10294. }
  10295. /// ActOnFinishLinkageSpecification - Complete the definition of
  10296. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  10297. /// valid, it's the position of the closing '}' brace in a linkage
  10298. /// specification that uses braces.
  10299. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  10300. Decl *LinkageSpec,
  10301. SourceLocation RBraceLoc) {
  10302. if (RBraceLoc.isValid()) {
  10303. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  10304. LSDecl->setRBraceLoc(RBraceLoc);
  10305. }
  10306. PopDeclContext();
  10307. return LinkageSpec;
  10308. }
  10309. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  10310. AttributeList *AttrList,
  10311. SourceLocation SemiLoc) {
  10312. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  10313. // Attribute declarations appertain to empty declaration so we handle
  10314. // them here.
  10315. if (AttrList)
  10316. ProcessDeclAttributeList(S, ED, AttrList);
  10317. CurContext->addDecl(ED);
  10318. return ED;
  10319. }
  10320. /// \brief Perform semantic analysis for the variable declaration that
  10321. /// occurs within a C++ catch clause, returning the newly-created
  10322. /// variable.
  10323. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  10324. TypeSourceInfo *TInfo,
  10325. SourceLocation StartLoc,
  10326. SourceLocation Loc,
  10327. IdentifierInfo *Name) {
  10328. bool Invalid = false;
  10329. QualType ExDeclType = TInfo->getType();
  10330. // Arrays and functions decay.
  10331. if (ExDeclType->isArrayType())
  10332. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  10333. else if (ExDeclType->isFunctionType())
  10334. ExDeclType = Context.getPointerType(ExDeclType);
  10335. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  10336. // The exception-declaration shall not denote a pointer or reference to an
  10337. // incomplete type, other than [cv] void*.
  10338. // N2844 forbids rvalue references.
  10339. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  10340. Diag(Loc, diag::err_catch_rvalue_ref);
  10341. Invalid = true;
  10342. }
  10343. QualType BaseType = ExDeclType;
  10344. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  10345. unsigned DK = diag::err_catch_incomplete;
  10346. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  10347. BaseType = Ptr->getPointeeType();
  10348. Mode = 1;
  10349. DK = diag::err_catch_incomplete_ptr;
  10350. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  10351. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  10352. BaseType = Ref->getPointeeType();
  10353. Mode = 2;
  10354. DK = diag::err_catch_incomplete_ref;
  10355. }
  10356. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  10357. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  10358. Invalid = true;
  10359. if (!Invalid && !ExDeclType->isDependentType() &&
  10360. RequireNonAbstractType(Loc, ExDeclType,
  10361. diag::err_abstract_type_in_decl,
  10362. AbstractVariableType))
  10363. Invalid = true;
  10364. // Only the non-fragile NeXT runtime currently supports C++ catches
  10365. // of ObjC types, and no runtime supports catching ObjC types by value.
  10366. if (!Invalid && getLangOpts().ObjC1) {
  10367. QualType T = ExDeclType;
  10368. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  10369. T = RT->getPointeeType();
  10370. if (T->isObjCObjectType()) {
  10371. Diag(Loc, diag::err_objc_object_catch);
  10372. Invalid = true;
  10373. } else if (T->isObjCObjectPointerType()) {
  10374. // FIXME: should this be a test for macosx-fragile specifically?
  10375. if (getLangOpts().ObjCRuntime.isFragile())
  10376. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  10377. }
  10378. }
  10379. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  10380. ExDeclType, TInfo, SC_None);
  10381. ExDecl->setExceptionVariable(true);
  10382. // In ARC, infer 'retaining' for variables of retainable type.
  10383. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  10384. Invalid = true;
  10385. if (!Invalid && !ExDeclType->isDependentType()) {
  10386. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  10387. // Insulate this from anything else we might currently be parsing.
  10388. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  10389. // C++ [except.handle]p16:
  10390. // The object declared in an exception-declaration or, if the
  10391. // exception-declaration does not specify a name, a temporary (12.2) is
  10392. // copy-initialized (8.5) from the exception object. [...]
  10393. // The object is destroyed when the handler exits, after the destruction
  10394. // of any automatic objects initialized within the handler.
  10395. //
  10396. // We just pretend to initialize the object with itself, then make sure
  10397. // it can be destroyed later.
  10398. QualType initType = Context.getExceptionObjectType(ExDeclType);
  10399. InitializedEntity entity =
  10400. InitializedEntity::InitializeVariable(ExDecl);
  10401. InitializationKind initKind =
  10402. InitializationKind::CreateCopy(Loc, SourceLocation());
  10403. Expr *opaqueValue =
  10404. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  10405. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  10406. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  10407. if (result.isInvalid())
  10408. Invalid = true;
  10409. else {
  10410. // If the constructor used was non-trivial, set this as the
  10411. // "initializer".
  10412. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  10413. if (!construct->getConstructor()->isTrivial()) {
  10414. Expr *init = MaybeCreateExprWithCleanups(construct);
  10415. ExDecl->setInit(init);
  10416. }
  10417. // And make sure it's destructable.
  10418. FinalizeVarWithDestructor(ExDecl, recordType);
  10419. }
  10420. }
  10421. }
  10422. if (Invalid)
  10423. ExDecl->setInvalidDecl();
  10424. return ExDecl;
  10425. }
  10426. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  10427. /// handler.
  10428. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  10429. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10430. bool Invalid = D.isInvalidType();
  10431. // Check for unexpanded parameter packs.
  10432. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  10433. UPPC_ExceptionType)) {
  10434. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  10435. D.getIdentifierLoc());
  10436. Invalid = true;
  10437. }
  10438. IdentifierInfo *II = D.getIdentifier();
  10439. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  10440. LookupOrdinaryName,
  10441. ForRedeclaration)) {
  10442. // The scope should be freshly made just for us. There is just no way
  10443. // it contains any previous declaration, except for function parameters in
  10444. // a function-try-block's catch statement.
  10445. assert(!S->isDeclScope(PrevDecl));
  10446. if (isDeclInScope(PrevDecl, CurContext, S)) {
  10447. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  10448. << D.getIdentifier();
  10449. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  10450. Invalid = true;
  10451. } else if (PrevDecl->isTemplateParameter())
  10452. // Maybe we will complain about the shadowed template parameter.
  10453. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10454. }
  10455. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  10456. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  10457. << D.getCXXScopeSpec().getRange();
  10458. Invalid = true;
  10459. }
  10460. VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
  10461. D.getLocStart(),
  10462. D.getIdentifierLoc(),
  10463. D.getIdentifier());
  10464. if (Invalid)
  10465. ExDecl->setInvalidDecl();
  10466. // Add the exception declaration into this scope.
  10467. if (II)
  10468. PushOnScopeChains(ExDecl, S);
  10469. else
  10470. CurContext->addDecl(ExDecl);
  10471. ProcessDeclAttributes(S, ExDecl, D);
  10472. return ExDecl;
  10473. }
  10474. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  10475. Expr *AssertExpr,
  10476. Expr *AssertMessageExpr,
  10477. SourceLocation RParenLoc) {
  10478. StringLiteral *AssertMessage =
  10479. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  10480. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  10481. return nullptr;
  10482. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  10483. AssertMessage, RParenLoc, false);
  10484. }
  10485. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  10486. Expr *AssertExpr,
  10487. StringLiteral *AssertMessage,
  10488. SourceLocation RParenLoc,
  10489. bool Failed) {
  10490. assert(AssertExpr != nullptr && "Expected non-null condition");
  10491. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  10492. !Failed) {
  10493. // In a static_assert-declaration, the constant-expression shall be a
  10494. // constant expression that can be contextually converted to bool.
  10495. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  10496. if (Converted.isInvalid())
  10497. Failed = true;
  10498. llvm::APSInt Cond;
  10499. if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
  10500. diag::err_static_assert_expression_is_not_constant,
  10501. /*AllowFold=*/false).isInvalid())
  10502. Failed = true;
  10503. if (!Failed && !Cond) {
  10504. SmallString<256> MsgBuffer;
  10505. llvm::raw_svector_ostream Msg(MsgBuffer);
  10506. if (AssertMessage)
  10507. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  10508. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  10509. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  10510. Failed = true;
  10511. }
  10512. }
  10513. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  10514. AssertExpr, AssertMessage, RParenLoc,
  10515. Failed);
  10516. CurContext->addDecl(Decl);
  10517. return Decl;
  10518. }
  10519. /// \brief Perform semantic analysis of the given friend type declaration.
  10520. ///
  10521. /// \returns A friend declaration that.
  10522. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  10523. SourceLocation FriendLoc,
  10524. TypeSourceInfo *TSInfo) {
  10525. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  10526. QualType T = TSInfo->getType();
  10527. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  10528. // C++03 [class.friend]p2:
  10529. // An elaborated-type-specifier shall be used in a friend declaration
  10530. // for a class.*
  10531. //
  10532. // * The class-key of the elaborated-type-specifier is required.
  10533. if (!ActiveTemplateInstantiations.empty()) {
  10534. // Do not complain about the form of friend template types during
  10535. // template instantiation; we will already have complained when the
  10536. // template was declared.
  10537. } else {
  10538. if (!T->isElaboratedTypeSpecifier()) {
  10539. // If we evaluated the type to a record type, suggest putting
  10540. // a tag in front.
  10541. if (const RecordType *RT = T->getAs<RecordType>()) {
  10542. RecordDecl *RD = RT->getDecl();
  10543. SmallString<16> InsertionText(" ");
  10544. InsertionText += RD->getKindName();
  10545. Diag(TypeRange.getBegin(),
  10546. getLangOpts().CPlusPlus11 ?
  10547. diag::warn_cxx98_compat_unelaborated_friend_type :
  10548. diag::ext_unelaborated_friend_type)
  10549. << (unsigned) RD->getTagKind()
  10550. << T
  10551. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
  10552. InsertionText);
  10553. } else {
  10554. Diag(FriendLoc,
  10555. getLangOpts().CPlusPlus11 ?
  10556. diag::warn_cxx98_compat_nonclass_type_friend :
  10557. diag::ext_nonclass_type_friend)
  10558. << T
  10559. << TypeRange;
  10560. }
  10561. } else if (T->getAs<EnumType>()) {
  10562. Diag(FriendLoc,
  10563. getLangOpts().CPlusPlus11 ?
  10564. diag::warn_cxx98_compat_enum_friend :
  10565. diag::ext_enum_friend)
  10566. << T
  10567. << TypeRange;
  10568. }
  10569. // C++11 [class.friend]p3:
  10570. // A friend declaration that does not declare a function shall have one
  10571. // of the following forms:
  10572. // friend elaborated-type-specifier ;
  10573. // friend simple-type-specifier ;
  10574. // friend typename-specifier ;
  10575. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  10576. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  10577. }
  10578. // If the type specifier in a friend declaration designates a (possibly
  10579. // cv-qualified) class type, that class is declared as a friend; otherwise,
  10580. // the friend declaration is ignored.
  10581. return FriendDecl::Create(Context, CurContext,
  10582. TSInfo->getTypeLoc().getLocStart(), TSInfo,
  10583. FriendLoc);
  10584. }
  10585. /// Handle a friend tag declaration where the scope specifier was
  10586. /// templated.
  10587. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  10588. unsigned TagSpec, SourceLocation TagLoc,
  10589. CXXScopeSpec &SS,
  10590. IdentifierInfo *Name,
  10591. SourceLocation NameLoc,
  10592. AttributeList *Attr,
  10593. MultiTemplateParamsArg TempParamLists) {
  10594. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  10595. bool isExplicitSpecialization = false;
  10596. bool Invalid = false;
  10597. if (TemplateParameterList *TemplateParams =
  10598. MatchTemplateParametersToScopeSpecifier(
  10599. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  10600. isExplicitSpecialization, Invalid)) {
  10601. if (TemplateParams->size() > 0) {
  10602. // This is a declaration of a class template.
  10603. if (Invalid)
  10604. return nullptr;
  10605. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  10606. NameLoc, Attr, TemplateParams, AS_public,
  10607. /*ModulePrivateLoc=*/SourceLocation(),
  10608. FriendLoc, TempParamLists.size() - 1,
  10609. TempParamLists.data()).get();
  10610. } else {
  10611. // The "template<>" header is extraneous.
  10612. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  10613. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  10614. isExplicitSpecialization = true;
  10615. }
  10616. }
  10617. if (Invalid) return nullptr;
  10618. bool isAllExplicitSpecializations = true;
  10619. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  10620. if (TempParamLists[I]->size()) {
  10621. isAllExplicitSpecializations = false;
  10622. break;
  10623. }
  10624. }
  10625. // FIXME: don't ignore attributes.
  10626. // If it's explicit specializations all the way down, just forget
  10627. // about the template header and build an appropriate non-templated
  10628. // friend. TODO: for source fidelity, remember the headers.
  10629. if (isAllExplicitSpecializations) {
  10630. if (SS.isEmpty()) {
  10631. bool Owned = false;
  10632. bool IsDependent = false;
  10633. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  10634. Attr, AS_public,
  10635. /*ModulePrivateLoc=*/SourceLocation(),
  10636. MultiTemplateParamsArg(), Owned, IsDependent,
  10637. /*ScopedEnumKWLoc=*/SourceLocation(),
  10638. /*ScopedEnumUsesClassTag=*/false,
  10639. /*UnderlyingType=*/TypeResult(),
  10640. /*IsTypeSpecifier=*/false);
  10641. }
  10642. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  10643. ElaboratedTypeKeyword Keyword
  10644. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  10645. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  10646. *Name, NameLoc);
  10647. if (T.isNull())
  10648. return nullptr;
  10649. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  10650. if (isa<DependentNameType>(T)) {
  10651. DependentNameTypeLoc TL =
  10652. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  10653. TL.setElaboratedKeywordLoc(TagLoc);
  10654. TL.setQualifierLoc(QualifierLoc);
  10655. TL.setNameLoc(NameLoc);
  10656. } else {
  10657. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  10658. TL.setElaboratedKeywordLoc(TagLoc);
  10659. TL.setQualifierLoc(QualifierLoc);
  10660. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  10661. }
  10662. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  10663. TSI, FriendLoc, TempParamLists);
  10664. Friend->setAccess(AS_public);
  10665. CurContext->addDecl(Friend);
  10666. return Friend;
  10667. }
  10668. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  10669. // Handle the case of a templated-scope friend class. e.g.
  10670. // template <class T> class A<T>::B;
  10671. // FIXME: we don't support these right now.
  10672. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  10673. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  10674. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  10675. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  10676. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  10677. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  10678. TL.setElaboratedKeywordLoc(TagLoc);
  10679. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  10680. TL.setNameLoc(NameLoc);
  10681. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  10682. TSI, FriendLoc, TempParamLists);
  10683. Friend->setAccess(AS_public);
  10684. Friend->setUnsupportedFriend(true);
  10685. CurContext->addDecl(Friend);
  10686. return Friend;
  10687. }
  10688. /// Handle a friend type declaration. This works in tandem with
  10689. /// ActOnTag.
  10690. ///
  10691. /// Notes on friend class templates:
  10692. ///
  10693. /// We generally treat friend class declarations as if they were
  10694. /// declaring a class. So, for example, the elaborated type specifier
  10695. /// in a friend declaration is required to obey the restrictions of a
  10696. /// class-head (i.e. no typedefs in the scope chain), template
  10697. /// parameters are required to match up with simple template-ids, &c.
  10698. /// However, unlike when declaring a template specialization, it's
  10699. /// okay to refer to a template specialization without an empty
  10700. /// template parameter declaration, e.g.
  10701. /// friend class A<T>::B<unsigned>;
  10702. /// We permit this as a special case; if there are any template
  10703. /// parameters present at all, require proper matching, i.e.
  10704. /// template <> template \<class T> friend class A<int>::B;
  10705. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  10706. MultiTemplateParamsArg TempParams) {
  10707. SourceLocation Loc = DS.getLocStart();
  10708. assert(DS.isFriendSpecified());
  10709. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  10710. // Try to convert the decl specifier to a type. This works for
  10711. // friend templates because ActOnTag never produces a ClassTemplateDecl
  10712. // for a TUK_Friend.
  10713. Declarator TheDeclarator(DS, Declarator::MemberContext);
  10714. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  10715. QualType T = TSI->getType();
  10716. if (TheDeclarator.isInvalidType())
  10717. return nullptr;
  10718. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  10719. return nullptr;
  10720. // This is definitely an error in C++98. It's probably meant to
  10721. // be forbidden in C++0x, too, but the specification is just
  10722. // poorly written.
  10723. //
  10724. // The problem is with declarations like the following:
  10725. // template <T> friend A<T>::foo;
  10726. // where deciding whether a class C is a friend or not now hinges
  10727. // on whether there exists an instantiation of A that causes
  10728. // 'foo' to equal C. There are restrictions on class-heads
  10729. // (which we declare (by fiat) elaborated friend declarations to
  10730. // be) that makes this tractable.
  10731. //
  10732. // FIXME: handle "template <> friend class A<T>;", which
  10733. // is possibly well-formed? Who even knows?
  10734. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  10735. Diag(Loc, diag::err_tagless_friend_type_template)
  10736. << DS.getSourceRange();
  10737. return nullptr;
  10738. }
  10739. // C++98 [class.friend]p1: A friend of a class is a function
  10740. // or class that is not a member of the class . . .
  10741. // This is fixed in DR77, which just barely didn't make the C++03
  10742. // deadline. It's also a very silly restriction that seriously
  10743. // affects inner classes and which nobody else seems to implement;
  10744. // thus we never diagnose it, not even in -pedantic.
  10745. //
  10746. // But note that we could warn about it: it's always useless to
  10747. // friend one of your own members (it's not, however, worthless to
  10748. // friend a member of an arbitrary specialization of your template).
  10749. Decl *D;
  10750. if (unsigned NumTempParamLists = TempParams.size())
  10751. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  10752. NumTempParamLists,
  10753. TempParams.data(),
  10754. TSI,
  10755. DS.getFriendSpecLoc());
  10756. else
  10757. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  10758. if (!D)
  10759. return nullptr;
  10760. D->setAccess(AS_public);
  10761. CurContext->addDecl(D);
  10762. return D;
  10763. }
  10764. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  10765. MultiTemplateParamsArg TemplateParams) {
  10766. const DeclSpec &DS = D.getDeclSpec();
  10767. assert(DS.isFriendSpecified());
  10768. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  10769. SourceLocation Loc = D.getIdentifierLoc();
  10770. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10771. // C++ [class.friend]p1
  10772. // A friend of a class is a function or class....
  10773. // Note that this sees through typedefs, which is intended.
  10774. // It *doesn't* see through dependent types, which is correct
  10775. // according to [temp.arg.type]p3:
  10776. // If a declaration acquires a function type through a
  10777. // type dependent on a template-parameter and this causes
  10778. // a declaration that does not use the syntactic form of a
  10779. // function declarator to have a function type, the program
  10780. // is ill-formed.
  10781. if (!TInfo->getType()->isFunctionType()) {
  10782. Diag(Loc, diag::err_unexpected_friend);
  10783. // It might be worthwhile to try to recover by creating an
  10784. // appropriate declaration.
  10785. return nullptr;
  10786. }
  10787. // C++ [namespace.memdef]p3
  10788. // - If a friend declaration in a non-local class first declares a
  10789. // class or function, the friend class or function is a member
  10790. // of the innermost enclosing namespace.
  10791. // - The name of the friend is not found by simple name lookup
  10792. // until a matching declaration is provided in that namespace
  10793. // scope (either before or after the class declaration granting
  10794. // friendship).
  10795. // - If a friend function is called, its name may be found by the
  10796. // name lookup that considers functions from namespaces and
  10797. // classes associated with the types of the function arguments.
  10798. // - When looking for a prior declaration of a class or a function
  10799. // declared as a friend, scopes outside the innermost enclosing
  10800. // namespace scope are not considered.
  10801. CXXScopeSpec &SS = D.getCXXScopeSpec();
  10802. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  10803. DeclarationName Name = NameInfo.getName();
  10804. assert(Name);
  10805. // Check for unexpanded parameter packs.
  10806. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  10807. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  10808. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  10809. return nullptr;
  10810. // The context we found the declaration in, or in which we should
  10811. // create the declaration.
  10812. DeclContext *DC;
  10813. Scope *DCScope = S;
  10814. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  10815. ForRedeclaration);
  10816. // There are five cases here.
  10817. // - There's no scope specifier and we're in a local class. Only look
  10818. // for functions declared in the immediately-enclosing block scope.
  10819. // We recover from invalid scope qualifiers as if they just weren't there.
  10820. FunctionDecl *FunctionContainingLocalClass = nullptr;
  10821. if ((SS.isInvalid() || !SS.isSet()) &&
  10822. (FunctionContainingLocalClass =
  10823. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  10824. // C++11 [class.friend]p11:
  10825. // If a friend declaration appears in a local class and the name
  10826. // specified is an unqualified name, a prior declaration is
  10827. // looked up without considering scopes that are outside the
  10828. // innermost enclosing non-class scope. For a friend function
  10829. // declaration, if there is no prior declaration, the program is
  10830. // ill-formed.
  10831. // Find the innermost enclosing non-class scope. This is the block
  10832. // scope containing the local class definition (or for a nested class,
  10833. // the outer local class).
  10834. DCScope = S->getFnParent();
  10835. // Look up the function name in the scope.
  10836. Previous.clear(LookupLocalFriendName);
  10837. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  10838. if (!Previous.empty()) {
  10839. // All possible previous declarations must have the same context:
  10840. // either they were declared at block scope or they are members of
  10841. // one of the enclosing local classes.
  10842. DC = Previous.getRepresentativeDecl()->getDeclContext();
  10843. } else {
  10844. // This is ill-formed, but provide the context that we would have
  10845. // declared the function in, if we were permitted to, for error recovery.
  10846. DC = FunctionContainingLocalClass;
  10847. }
  10848. adjustContextForLocalExternDecl(DC);
  10849. // C++ [class.friend]p6:
  10850. // A function can be defined in a friend declaration of a class if and
  10851. // only if the class is a non-local class (9.8), the function name is
  10852. // unqualified, and the function has namespace scope.
  10853. if (D.isFunctionDefinition()) {
  10854. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  10855. }
  10856. // - There's no scope specifier, in which case we just go to the
  10857. // appropriate scope and look for a function or function template
  10858. // there as appropriate.
  10859. } else if (SS.isInvalid() || !SS.isSet()) {
  10860. // C++11 [namespace.memdef]p3:
  10861. // If the name in a friend declaration is neither qualified nor
  10862. // a template-id and the declaration is a function or an
  10863. // elaborated-type-specifier, the lookup to determine whether
  10864. // the entity has been previously declared shall not consider
  10865. // any scopes outside the innermost enclosing namespace.
  10866. bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
  10867. // Find the appropriate context according to the above.
  10868. DC = CurContext;
  10869. // Skip class contexts. If someone can cite chapter and verse
  10870. // for this behavior, that would be nice --- it's what GCC and
  10871. // EDG do, and it seems like a reasonable intent, but the spec
  10872. // really only says that checks for unqualified existing
  10873. // declarations should stop at the nearest enclosing namespace,
  10874. // not that they should only consider the nearest enclosing
  10875. // namespace.
  10876. while (DC->isRecord())
  10877. DC = DC->getParent();
  10878. DeclContext *LookupDC = DC;
  10879. while (LookupDC->isTransparentContext())
  10880. LookupDC = LookupDC->getParent();
  10881. while (true) {
  10882. LookupQualifiedName(Previous, LookupDC);
  10883. if (!Previous.empty()) {
  10884. DC = LookupDC;
  10885. break;
  10886. }
  10887. if (isTemplateId) {
  10888. if (isa<TranslationUnitDecl>(LookupDC)) break;
  10889. } else {
  10890. if (LookupDC->isFileContext()) break;
  10891. }
  10892. LookupDC = LookupDC->getParent();
  10893. }
  10894. DCScope = getScopeForDeclContext(S, DC);
  10895. // - There's a non-dependent scope specifier, in which case we
  10896. // compute it and do a previous lookup there for a function
  10897. // or function template.
  10898. } else if (!SS.getScopeRep()->isDependent()) {
  10899. DC = computeDeclContext(SS);
  10900. if (!DC) return nullptr;
  10901. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  10902. LookupQualifiedName(Previous, DC);
  10903. // Ignore things found implicitly in the wrong scope.
  10904. // TODO: better diagnostics for this case. Suggesting the right
  10905. // qualified scope would be nice...
  10906. LookupResult::Filter F = Previous.makeFilter();
  10907. while (F.hasNext()) {
  10908. NamedDecl *D = F.next();
  10909. if (!DC->InEnclosingNamespaceSetOf(
  10910. D->getDeclContext()->getRedeclContext()))
  10911. F.erase();
  10912. }
  10913. F.done();
  10914. if (Previous.empty()) {
  10915. D.setInvalidType();
  10916. Diag(Loc, diag::err_qualified_friend_not_found)
  10917. << Name << TInfo->getType();
  10918. return nullptr;
  10919. }
  10920. // C++ [class.friend]p1: A friend of a class is a function or
  10921. // class that is not a member of the class . . .
  10922. if (DC->Equals(CurContext))
  10923. Diag(DS.getFriendSpecLoc(),
  10924. getLangOpts().CPlusPlus11 ?
  10925. diag::warn_cxx98_compat_friend_is_member :
  10926. diag::err_friend_is_member);
  10927. if (D.isFunctionDefinition()) {
  10928. // C++ [class.friend]p6:
  10929. // A function can be defined in a friend declaration of a class if and
  10930. // only if the class is a non-local class (9.8), the function name is
  10931. // unqualified, and the function has namespace scope.
  10932. SemaDiagnosticBuilder DB
  10933. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  10934. DB << SS.getScopeRep();
  10935. if (DC->isFileContext())
  10936. DB << FixItHint::CreateRemoval(SS.getRange());
  10937. SS.clear();
  10938. }
  10939. // - There's a scope specifier that does not match any template
  10940. // parameter lists, in which case we use some arbitrary context,
  10941. // create a method or method template, and wait for instantiation.
  10942. // - There's a scope specifier that does match some template
  10943. // parameter lists, which we don't handle right now.
  10944. } else {
  10945. if (D.isFunctionDefinition()) {
  10946. // C++ [class.friend]p6:
  10947. // A function can be defined in a friend declaration of a class if and
  10948. // only if the class is a non-local class (9.8), the function name is
  10949. // unqualified, and the function has namespace scope.
  10950. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  10951. << SS.getScopeRep();
  10952. }
  10953. DC = CurContext;
  10954. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  10955. }
  10956. if (!DC->isRecord()) {
  10957. // This implies that it has to be an operator or function.
  10958. if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
  10959. D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
  10960. D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
  10961. Diag(Loc, diag::err_introducing_special_friend) <<
  10962. (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
  10963. D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
  10964. return nullptr;
  10965. }
  10966. }
  10967. // FIXME: This is an egregious hack to cope with cases where the scope stack
  10968. // does not contain the declaration context, i.e., in an out-of-line
  10969. // definition of a class.
  10970. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  10971. if (!DCScope) {
  10972. FakeDCScope.setEntity(DC);
  10973. DCScope = &FakeDCScope;
  10974. }
  10975. bool AddToScope = true;
  10976. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  10977. TemplateParams, AddToScope);
  10978. if (!ND) return nullptr;
  10979. assert(ND->getLexicalDeclContext() == CurContext);
  10980. // If we performed typo correction, we might have added a scope specifier
  10981. // and changed the decl context.
  10982. DC = ND->getDeclContext();
  10983. // Add the function declaration to the appropriate lookup tables,
  10984. // adjusting the redeclarations list as necessary. We don't
  10985. // want to do this yet if the friending class is dependent.
  10986. //
  10987. // Also update the scope-based lookup if the target context's
  10988. // lookup context is in lexical scope.
  10989. if (!CurContext->isDependentContext()) {
  10990. DC = DC->getRedeclContext();
  10991. DC->makeDeclVisibleInContext(ND);
  10992. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  10993. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  10994. }
  10995. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  10996. D.getIdentifierLoc(), ND,
  10997. DS.getFriendSpecLoc());
  10998. FrD->setAccess(AS_public);
  10999. CurContext->addDecl(FrD);
  11000. if (ND->isInvalidDecl()) {
  11001. FrD->setInvalidDecl();
  11002. } else {
  11003. if (DC->isRecord()) CheckFriendAccess(ND);
  11004. FunctionDecl *FD;
  11005. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  11006. FD = FTD->getTemplatedDecl();
  11007. else
  11008. FD = cast<FunctionDecl>(ND);
  11009. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  11010. // default argument expression, that declaration shall be a definition
  11011. // and shall be the only declaration of the function or function
  11012. // template in the translation unit.
  11013. if (functionDeclHasDefaultArgument(FD)) {
  11014. if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
  11015. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  11016. Diag(OldFD->getLocation(), diag::note_previous_declaration);
  11017. } else if (!D.isFunctionDefinition())
  11018. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  11019. }
  11020. // Mark templated-scope function declarations as unsupported.
  11021. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  11022. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  11023. << SS.getScopeRep() << SS.getRange()
  11024. << cast<CXXRecordDecl>(CurContext);
  11025. FrD->setUnsupportedFriend(true);
  11026. }
  11027. }
  11028. return ND;
  11029. }
  11030. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  11031. AdjustDeclIfTemplate(Dcl);
  11032. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  11033. if (!Fn) {
  11034. Diag(DelLoc, diag::err_deleted_non_function);
  11035. return;
  11036. }
  11037. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  11038. // Don't consider the implicit declaration we generate for explicit
  11039. // specializations. FIXME: Do not generate these implicit declarations.
  11040. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  11041. Prev->getPreviousDecl()) &&
  11042. !Prev->isDefined()) {
  11043. Diag(DelLoc, diag::err_deleted_decl_not_first);
  11044. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  11045. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  11046. : diag::note_previous_declaration);
  11047. }
  11048. // If the declaration wasn't the first, we delete the function anyway for
  11049. // recovery.
  11050. Fn = Fn->getCanonicalDecl();
  11051. }
  11052. // dllimport/dllexport cannot be deleted.
  11053. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  11054. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  11055. Fn->setInvalidDecl();
  11056. }
  11057. if (Fn->isDeleted())
  11058. return;
  11059. // See if we're deleting a function which is already known to override a
  11060. // non-deleted virtual function.
  11061. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  11062. bool IssuedDiagnostic = false;
  11063. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  11064. E = MD->end_overridden_methods();
  11065. I != E; ++I) {
  11066. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  11067. if (!IssuedDiagnostic) {
  11068. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  11069. IssuedDiagnostic = true;
  11070. }
  11071. Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  11072. }
  11073. }
  11074. }
  11075. // C++11 [basic.start.main]p3:
  11076. // A program that defines main as deleted [...] is ill-formed.
  11077. if (Fn->isMain())
  11078. Diag(DelLoc, diag::err_deleted_main);
  11079. Fn->setDeletedAsWritten();
  11080. }
  11081. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  11082. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  11083. if (MD) {
  11084. if (MD->getParent()->isDependentType()) {
  11085. MD->setDefaulted();
  11086. MD->setExplicitlyDefaulted();
  11087. return;
  11088. }
  11089. CXXSpecialMember Member = getSpecialMember(MD);
  11090. if (Member == CXXInvalid) {
  11091. if (!MD->isInvalidDecl())
  11092. Diag(DefaultLoc, diag::err_default_special_members);
  11093. return;
  11094. }
  11095. MD->setDefaulted();
  11096. MD->setExplicitlyDefaulted();
  11097. // If this definition appears within the record, do the checking when
  11098. // the record is complete.
  11099. const FunctionDecl *Primary = MD;
  11100. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  11101. // Find the uninstantiated declaration that actually had the '= default'
  11102. // on it.
  11103. Pattern->isDefined(Primary);
  11104. // If the method was defaulted on its first declaration, we will have
  11105. // already performed the checking in CheckCompletedCXXClass. Such a
  11106. // declaration doesn't trigger an implicit definition.
  11107. if (Primary == Primary->getCanonicalDecl())
  11108. return;
  11109. CheckExplicitlyDefaultedSpecialMember(MD);
  11110. if (MD->isInvalidDecl())
  11111. return;
  11112. switch (Member) {
  11113. case CXXDefaultConstructor:
  11114. DefineImplicitDefaultConstructor(DefaultLoc,
  11115. cast<CXXConstructorDecl>(MD));
  11116. break;
  11117. case CXXCopyConstructor:
  11118. DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  11119. break;
  11120. case CXXCopyAssignment:
  11121. DefineImplicitCopyAssignment(DefaultLoc, MD);
  11122. break;
  11123. case CXXDestructor:
  11124. DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  11125. break;
  11126. case CXXMoveConstructor:
  11127. DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  11128. break;
  11129. case CXXMoveAssignment:
  11130. DefineImplicitMoveAssignment(DefaultLoc, MD);
  11131. break;
  11132. case CXXInvalid:
  11133. llvm_unreachable("Invalid special member.");
  11134. }
  11135. } else {
  11136. Diag(DefaultLoc, diag::err_default_special_members);
  11137. }
  11138. }
  11139. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  11140. for (Stmt *SubStmt : S->children()) {
  11141. if (!SubStmt)
  11142. continue;
  11143. if (isa<ReturnStmt>(SubStmt))
  11144. Self.Diag(SubStmt->getLocStart(),
  11145. diag::err_return_in_constructor_handler);
  11146. if (!isa<Expr>(SubStmt))
  11147. SearchForReturnInStmt(Self, SubStmt);
  11148. }
  11149. }
  11150. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  11151. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  11152. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  11153. SearchForReturnInStmt(*this, Handler);
  11154. }
  11155. }
  11156. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  11157. const CXXMethodDecl *Old) {
  11158. const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
  11159. const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
  11160. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  11161. // If the calling conventions match, everything is fine
  11162. if (NewCC == OldCC)
  11163. return false;
  11164. // If the calling conventions mismatch because the new function is static,
  11165. // suppress the calling convention mismatch error; the error about static
  11166. // function override (err_static_overrides_virtual from
  11167. // Sema::CheckFunctionDeclaration) is more clear.
  11168. if (New->getStorageClass() == SC_Static)
  11169. return false;
  11170. Diag(New->getLocation(),
  11171. diag::err_conflicting_overriding_cc_attributes)
  11172. << New->getDeclName() << New->getType() << Old->getType();
  11173. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  11174. return true;
  11175. }
  11176. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  11177. const CXXMethodDecl *Old) {
  11178. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  11179. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  11180. if (Context.hasSameType(NewTy, OldTy) ||
  11181. NewTy->isDependentType() || OldTy->isDependentType())
  11182. return false;
  11183. // Check if the return types are covariant
  11184. QualType NewClassTy, OldClassTy;
  11185. /// Both types must be pointers or references to classes.
  11186. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  11187. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  11188. NewClassTy = NewPT->getPointeeType();
  11189. OldClassTy = OldPT->getPointeeType();
  11190. }
  11191. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  11192. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  11193. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  11194. NewClassTy = NewRT->getPointeeType();
  11195. OldClassTy = OldRT->getPointeeType();
  11196. }
  11197. }
  11198. }
  11199. // The return types aren't either both pointers or references to a class type.
  11200. if (NewClassTy.isNull()) {
  11201. Diag(New->getLocation(),
  11202. diag::err_different_return_type_for_overriding_virtual_function)
  11203. << New->getDeclName() << NewTy << OldTy
  11204. << New->getReturnTypeSourceRange();
  11205. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11206. << Old->getReturnTypeSourceRange();
  11207. return true;
  11208. }
  11209. // C++ [class.virtual]p6:
  11210. // If the return type of D::f differs from the return type of B::f, the
  11211. // class type in the return type of D::f shall be complete at the point of
  11212. // declaration of D::f or shall be the class type D.
  11213. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  11214. if (!RT->isBeingDefined() &&
  11215. RequireCompleteType(New->getLocation(), NewClassTy,
  11216. diag::err_covariant_return_incomplete,
  11217. New->getDeclName()))
  11218. return true;
  11219. }
  11220. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  11221. // Check if the new class derives from the old class.
  11222. if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
  11223. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  11224. << New->getDeclName() << NewTy << OldTy
  11225. << New->getReturnTypeSourceRange();
  11226. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11227. << Old->getReturnTypeSourceRange();
  11228. return true;
  11229. }
  11230. // Check if we the conversion from derived to base is valid.
  11231. if (CheckDerivedToBaseConversion(
  11232. NewClassTy, OldClassTy,
  11233. diag::err_covariant_return_inaccessible_base,
  11234. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  11235. New->getLocation(), New->getReturnTypeSourceRange(),
  11236. New->getDeclName(), nullptr)) {
  11237. // FIXME: this note won't trigger for delayed access control
  11238. // diagnostics, and it's impossible to get an undelayed error
  11239. // here from access control during the original parse because
  11240. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  11241. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11242. << Old->getReturnTypeSourceRange();
  11243. return true;
  11244. }
  11245. }
  11246. // The qualifiers of the return types must be the same.
  11247. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  11248. Diag(New->getLocation(),
  11249. diag::err_covariant_return_type_different_qualifications)
  11250. << New->getDeclName() << NewTy << OldTy
  11251. << New->getReturnTypeSourceRange();
  11252. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11253. << Old->getReturnTypeSourceRange();
  11254. return true;
  11255. };
  11256. // The new class type must have the same or less qualifiers as the old type.
  11257. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  11258. Diag(New->getLocation(),
  11259. diag::err_covariant_return_type_class_type_more_qualified)
  11260. << New->getDeclName() << NewTy << OldTy
  11261. << New->getReturnTypeSourceRange();
  11262. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11263. << Old->getReturnTypeSourceRange();
  11264. return true;
  11265. };
  11266. return false;
  11267. }
  11268. /// \brief Mark the given method pure.
  11269. ///
  11270. /// \param Method the method to be marked pure.
  11271. ///
  11272. /// \param InitRange the source range that covers the "0" initializer.
  11273. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  11274. SourceLocation EndLoc = InitRange.getEnd();
  11275. if (EndLoc.isValid())
  11276. Method->setRangeEnd(EndLoc);
  11277. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  11278. Method->setPure();
  11279. return false;
  11280. }
  11281. if (!Method->isInvalidDecl())
  11282. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  11283. << Method->getDeclName() << InitRange;
  11284. return true;
  11285. }
  11286. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  11287. if (D->getFriendObjectKind())
  11288. Diag(D->getLocation(), diag::err_pure_friend);
  11289. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  11290. CheckPureMethod(M, ZeroLoc);
  11291. else
  11292. Diag(D->getLocation(), diag::err_illegal_initializer);
  11293. }
  11294. /// \brief Determine whether the given declaration is a static data member.
  11295. static bool isStaticDataMember(const Decl *D) {
  11296. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  11297. return Var->isStaticDataMember();
  11298. return false;
  11299. }
  11300. /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
  11301. /// an initializer for the out-of-line declaration 'Dcl'. The scope
  11302. /// is a fresh scope pushed for just this purpose.
  11303. ///
  11304. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  11305. /// static data member of class X, names should be looked up in the scope of
  11306. /// class X.
  11307. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  11308. // If there is no declaration, there was an error parsing it.
  11309. if (!D || D->isInvalidDecl())
  11310. return;
  11311. // We will always have a nested name specifier here, but this declaration
  11312. // might not be out of line if the specifier names the current namespace:
  11313. // extern int n;
  11314. // int ::n = 0;
  11315. if (D->isOutOfLine())
  11316. EnterDeclaratorContext(S, D->getDeclContext());
  11317. // If we are parsing the initializer for a static data member, push a
  11318. // new expression evaluation context that is associated with this static
  11319. // data member.
  11320. if (isStaticDataMember(D))
  11321. PushExpressionEvaluationContext(PotentiallyEvaluated, D);
  11322. }
  11323. /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
  11324. /// initializer for the out-of-line declaration 'D'.
  11325. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  11326. // If there is no declaration, there was an error parsing it.
  11327. if (!D || D->isInvalidDecl())
  11328. return;
  11329. if (isStaticDataMember(D))
  11330. PopExpressionEvaluationContext();
  11331. if (D->isOutOfLine())
  11332. ExitDeclaratorContext(S);
  11333. }
  11334. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  11335. /// C++ if/switch/while/for statement.
  11336. /// e.g: "if (int x = f()) {...}"
  11337. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  11338. // C++ 6.4p2:
  11339. // The declarator shall not specify a function or an array.
  11340. // The type-specifier-seq shall not contain typedef and shall not declare a
  11341. // new class or enumeration.
  11342. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  11343. "Parser allowed 'typedef' as storage class of condition decl.");
  11344. Decl *Dcl = ActOnDeclarator(S, D);
  11345. if (!Dcl)
  11346. return true;
  11347. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  11348. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  11349. << D.getSourceRange();
  11350. return true;
  11351. }
  11352. return Dcl;
  11353. }
  11354. void Sema::LoadExternalVTableUses() {
  11355. if (!ExternalSource)
  11356. return;
  11357. SmallVector<ExternalVTableUse, 4> VTables;
  11358. ExternalSource->ReadUsedVTables(VTables);
  11359. SmallVector<VTableUse, 4> NewUses;
  11360. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  11361. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  11362. = VTablesUsed.find(VTables[I].Record);
  11363. // Even if a definition wasn't required before, it may be required now.
  11364. if (Pos != VTablesUsed.end()) {
  11365. if (!Pos->second && VTables[I].DefinitionRequired)
  11366. Pos->second = true;
  11367. continue;
  11368. }
  11369. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  11370. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  11371. }
  11372. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  11373. }
  11374. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  11375. bool DefinitionRequired) {
  11376. // Ignore any vtable uses in unevaluated operands or for classes that do
  11377. // not have a vtable.
  11378. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  11379. CurContext->isDependentContext() || isUnevaluatedContext())
  11380. return;
  11381. // Try to insert this class into the map.
  11382. LoadExternalVTableUses();
  11383. Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
  11384. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  11385. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  11386. if (!Pos.second) {
  11387. // If we already had an entry, check to see if we are promoting this vtable
  11388. // to require a definition. If so, we need to reappend to the VTableUses
  11389. // list, since we may have already processed the first entry.
  11390. if (DefinitionRequired && !Pos.first->second) {
  11391. Pos.first->second = true;
  11392. } else {
  11393. // Otherwise, we can early exit.
  11394. return;
  11395. }
  11396. } else {
  11397. // The Microsoft ABI requires that we perform the destructor body
  11398. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  11399. // the deleting destructor is emitted with the vtable, not with the
  11400. // destructor definition as in the Itanium ABI.
  11401. // If it has a definition, we do the check at that point instead.
  11402. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  11403. Class->hasUserDeclaredDestructor() &&
  11404. !Class->getDestructor()->isDefined() &&
  11405. !Class->getDestructor()->isDeleted()) {
  11406. CXXDestructorDecl *DD = Class->getDestructor();
  11407. ContextRAII SavedContext(*this, DD);
  11408. CheckDestructor(DD);
  11409. }
  11410. }
  11411. // Local classes need to have their virtual members marked
  11412. // immediately. For all other classes, we mark their virtual members
  11413. // at the end of the translation unit.
  11414. if (Class->isLocalClass())
  11415. MarkVirtualMembersReferenced(Loc, Class);
  11416. else
  11417. VTableUses.push_back(std::make_pair(Class, Loc));
  11418. }
  11419. bool Sema::DefineUsedVTables() {
  11420. LoadExternalVTableUses();
  11421. if (VTableUses.empty())
  11422. return false;
  11423. // Note: The VTableUses vector could grow as a result of marking
  11424. // the members of a class as "used", so we check the size each
  11425. // time through the loop and prefer indices (which are stable) to
  11426. // iterators (which are not).
  11427. bool DefinedAnything = false;
  11428. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  11429. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  11430. if (!Class)
  11431. continue;
  11432. SourceLocation Loc = VTableUses[I].second;
  11433. bool DefineVTable = true;
  11434. // If this class has a key function, but that key function is
  11435. // defined in another translation unit, we don't need to emit the
  11436. // vtable even though we're using it.
  11437. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  11438. if (KeyFunction && !KeyFunction->hasBody()) {
  11439. // The key function is in another translation unit.
  11440. DefineVTable = false;
  11441. TemplateSpecializationKind TSK =
  11442. KeyFunction->getTemplateSpecializationKind();
  11443. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  11444. TSK != TSK_ImplicitInstantiation &&
  11445. "Instantiations don't have key functions");
  11446. (void)TSK;
  11447. } else if (!KeyFunction) {
  11448. // If we have a class with no key function that is the subject
  11449. // of an explicit instantiation declaration, suppress the
  11450. // vtable; it will live with the explicit instantiation
  11451. // definition.
  11452. bool IsExplicitInstantiationDeclaration
  11453. = Class->getTemplateSpecializationKind()
  11454. == TSK_ExplicitInstantiationDeclaration;
  11455. for (auto R : Class->redecls()) {
  11456. TemplateSpecializationKind TSK
  11457. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  11458. if (TSK == TSK_ExplicitInstantiationDeclaration)
  11459. IsExplicitInstantiationDeclaration = true;
  11460. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  11461. IsExplicitInstantiationDeclaration = false;
  11462. break;
  11463. }
  11464. }
  11465. if (IsExplicitInstantiationDeclaration)
  11466. DefineVTable = false;
  11467. }
  11468. // The exception specifications for all virtual members may be needed even
  11469. // if we are not providing an authoritative form of the vtable in this TU.
  11470. // We may choose to emit it available_externally anyway.
  11471. if (!DefineVTable) {
  11472. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  11473. continue;
  11474. }
  11475. // Mark all of the virtual members of this class as referenced, so
  11476. // that we can build a vtable. Then, tell the AST consumer that a
  11477. // vtable for this class is required.
  11478. DefinedAnything = true;
  11479. MarkVirtualMembersReferenced(Loc, Class);
  11480. CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
  11481. if (VTablesUsed[Canonical])
  11482. Consumer.HandleVTable(Class);
  11483. // Optionally warn if we're emitting a weak vtable.
  11484. if (Class->isExternallyVisible() &&
  11485. Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
  11486. const FunctionDecl *KeyFunctionDef = nullptr;
  11487. if (!KeyFunction ||
  11488. (KeyFunction->hasBody(KeyFunctionDef) &&
  11489. KeyFunctionDef->isInlined()))
  11490. Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
  11491. TSK_ExplicitInstantiationDefinition
  11492. ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
  11493. << Class;
  11494. }
  11495. }
  11496. VTableUses.clear();
  11497. return DefinedAnything;
  11498. }
  11499. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  11500. const CXXRecordDecl *RD) {
  11501. for (const auto *I : RD->methods())
  11502. if (I->isVirtual() && !I->isPure())
  11503. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  11504. }
  11505. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  11506. const CXXRecordDecl *RD) {
  11507. // Mark all functions which will appear in RD's vtable as used.
  11508. CXXFinalOverriderMap FinalOverriders;
  11509. RD->getFinalOverriders(FinalOverriders);
  11510. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  11511. E = FinalOverriders.end();
  11512. I != E; ++I) {
  11513. for (OverridingMethods::const_iterator OI = I->second.begin(),
  11514. OE = I->second.end();
  11515. OI != OE; ++OI) {
  11516. assert(OI->second.size() > 0 && "no final overrider");
  11517. CXXMethodDecl *Overrider = OI->second.front().Method;
  11518. // C++ [basic.def.odr]p2:
  11519. // [...] A virtual member function is used if it is not pure. [...]
  11520. if (!Overrider->isPure())
  11521. MarkFunctionReferenced(Loc, Overrider);
  11522. }
  11523. }
  11524. // Only classes that have virtual bases need a VTT.
  11525. if (RD->getNumVBases() == 0)
  11526. return;
  11527. for (const auto &I : RD->bases()) {
  11528. const CXXRecordDecl *Base =
  11529. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  11530. if (Base->getNumVBases() == 0)
  11531. continue;
  11532. MarkVirtualMembersReferenced(Loc, Base);
  11533. }
  11534. }
  11535. /// SetIvarInitializers - This routine builds initialization ASTs for the
  11536. /// Objective-C implementation whose ivars need be initialized.
  11537. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  11538. if (!getLangOpts().CPlusPlus)
  11539. return;
  11540. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  11541. SmallVector<ObjCIvarDecl*, 8> ivars;
  11542. CollectIvarsToConstructOrDestruct(OID, ivars);
  11543. if (ivars.empty())
  11544. return;
  11545. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  11546. for (unsigned i = 0; i < ivars.size(); i++) {
  11547. FieldDecl *Field = ivars[i];
  11548. if (Field->isInvalidDecl())
  11549. continue;
  11550. CXXCtorInitializer *Member;
  11551. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  11552. InitializationKind InitKind =
  11553. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  11554. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  11555. ExprResult MemberInit =
  11556. InitSeq.Perform(*this, InitEntity, InitKind, None);
  11557. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  11558. // Note, MemberInit could actually come back empty if no initialization
  11559. // is required (e.g., because it would call a trivial default constructor)
  11560. if (!MemberInit.get() || MemberInit.isInvalid())
  11561. continue;
  11562. Member =
  11563. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  11564. SourceLocation(),
  11565. MemberInit.getAs<Expr>(),
  11566. SourceLocation());
  11567. AllToInit.push_back(Member);
  11568. // Be sure that the destructor is accessible and is marked as referenced.
  11569. if (const RecordType *RecordTy =
  11570. Context.getBaseElementType(Field->getType())
  11571. ->getAs<RecordType>()) {
  11572. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  11573. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  11574. MarkFunctionReferenced(Field->getLocation(), Destructor);
  11575. CheckDestructorAccess(Field->getLocation(), Destructor,
  11576. PDiag(diag::err_access_dtor_ivar)
  11577. << Context.getBaseElementType(Field->getType()));
  11578. }
  11579. }
  11580. }
  11581. ObjCImplementation->setIvarInitializers(Context,
  11582. AllToInit.data(), AllToInit.size());
  11583. }
  11584. }
  11585. static
  11586. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  11587. llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
  11588. llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
  11589. llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
  11590. Sema &S) {
  11591. if (Ctor->isInvalidDecl())
  11592. return;
  11593. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  11594. // Target may not be determinable yet, for instance if this is a dependent
  11595. // call in an uninstantiated template.
  11596. if (Target) {
  11597. const FunctionDecl *FNTarget = nullptr;
  11598. (void)Target->hasBody(FNTarget);
  11599. Target = const_cast<CXXConstructorDecl*>(
  11600. cast_or_null<CXXConstructorDecl>(FNTarget));
  11601. }
  11602. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  11603. // Avoid dereferencing a null pointer here.
  11604. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  11605. if (!Current.insert(Canonical).second)
  11606. return;
  11607. // We know that beyond here, we aren't chaining into a cycle.
  11608. if (!Target || !Target->isDelegatingConstructor() ||
  11609. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  11610. Valid.insert(Current.begin(), Current.end());
  11611. Current.clear();
  11612. // We've hit a cycle.
  11613. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  11614. Current.count(TCanonical)) {
  11615. // If we haven't diagnosed this cycle yet, do so now.
  11616. if (!Invalid.count(TCanonical)) {
  11617. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  11618. diag::warn_delegating_ctor_cycle)
  11619. << Ctor;
  11620. // Don't add a note for a function delegating directly to itself.
  11621. if (TCanonical != Canonical)
  11622. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  11623. CXXConstructorDecl *C = Target;
  11624. while (C->getCanonicalDecl() != Canonical) {
  11625. const FunctionDecl *FNTarget = nullptr;
  11626. (void)C->getTargetConstructor()->hasBody(FNTarget);
  11627. assert(FNTarget && "Ctor cycle through bodiless function");
  11628. C = const_cast<CXXConstructorDecl*>(
  11629. cast<CXXConstructorDecl>(FNTarget));
  11630. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  11631. }
  11632. }
  11633. Invalid.insert(Current.begin(), Current.end());
  11634. Current.clear();
  11635. } else {
  11636. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  11637. }
  11638. }
  11639. void Sema::CheckDelegatingCtorCycles() {
  11640. llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  11641. for (DelegatingCtorDeclsType::iterator
  11642. I = DelegatingCtorDecls.begin(ExternalSource),
  11643. E = DelegatingCtorDecls.end();
  11644. I != E; ++I)
  11645. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  11646. for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
  11647. CE = Invalid.end();
  11648. CI != CE; ++CI)
  11649. (*CI)->setInvalidDecl();
  11650. }
  11651. namespace {
  11652. /// \brief AST visitor that finds references to the 'this' expression.
  11653. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  11654. Sema &S;
  11655. public:
  11656. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  11657. bool VisitCXXThisExpr(CXXThisExpr *E) {
  11658. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  11659. << E->isImplicit();
  11660. return false;
  11661. }
  11662. };
  11663. }
  11664. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  11665. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  11666. if (!TSInfo)
  11667. return false;
  11668. TypeLoc TL = TSInfo->getTypeLoc();
  11669. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  11670. if (!ProtoTL)
  11671. return false;
  11672. // C++11 [expr.prim.general]p3:
  11673. // [The expression this] shall not appear before the optional
  11674. // cv-qualifier-seq and it shall not appear within the declaration of a
  11675. // static member function (although its type and value category are defined
  11676. // within a static member function as they are within a non-static member
  11677. // function). [ Note: this is because declaration matching does not occur
  11678. // until the complete declarator is known. - end note ]
  11679. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  11680. FindCXXThisExpr Finder(*this);
  11681. // If the return type came after the cv-qualifier-seq, check it now.
  11682. if (Proto->hasTrailingReturn() &&
  11683. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  11684. return true;
  11685. // Check the exception specification.
  11686. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  11687. return true;
  11688. return checkThisInStaticMemberFunctionAttributes(Method);
  11689. }
  11690. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  11691. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  11692. if (!TSInfo)
  11693. return false;
  11694. TypeLoc TL = TSInfo->getTypeLoc();
  11695. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  11696. if (!ProtoTL)
  11697. return false;
  11698. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  11699. FindCXXThisExpr Finder(*this);
  11700. switch (Proto->getExceptionSpecType()) {
  11701. case EST_Unparsed:
  11702. case EST_Uninstantiated:
  11703. case EST_Unevaluated:
  11704. case EST_BasicNoexcept:
  11705. case EST_DynamicNone:
  11706. case EST_MSAny:
  11707. case EST_None:
  11708. break;
  11709. case EST_ComputedNoexcept:
  11710. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  11711. return true;
  11712. case EST_Dynamic:
  11713. for (const auto &E : Proto->exceptions()) {
  11714. if (!Finder.TraverseType(E))
  11715. return true;
  11716. }
  11717. break;
  11718. }
  11719. return false;
  11720. }
  11721. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  11722. FindCXXThisExpr Finder(*this);
  11723. // Check attributes.
  11724. for (const auto *A : Method->attrs()) {
  11725. // FIXME: This should be emitted by tblgen.
  11726. Expr *Arg = nullptr;
  11727. ArrayRef<Expr *> Args;
  11728. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  11729. Arg = G->getArg();
  11730. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  11731. Arg = G->getArg();
  11732. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  11733. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  11734. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  11735. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  11736. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  11737. Arg = ETLF->getSuccessValue();
  11738. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  11739. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  11740. Arg = STLF->getSuccessValue();
  11741. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  11742. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  11743. Arg = LR->getArg();
  11744. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  11745. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  11746. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  11747. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  11748. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  11749. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  11750. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  11751. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  11752. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  11753. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  11754. if (Arg && !Finder.TraverseStmt(Arg))
  11755. return true;
  11756. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  11757. if (!Finder.TraverseStmt(Args[I]))
  11758. return true;
  11759. }
  11760. }
  11761. return false;
  11762. }
  11763. void Sema::checkExceptionSpecification(
  11764. bool IsTopLevel, ExceptionSpecificationType EST,
  11765. ArrayRef<ParsedType> DynamicExceptions,
  11766. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  11767. SmallVectorImpl<QualType> &Exceptions,
  11768. FunctionProtoType::ExceptionSpecInfo &ESI) {
  11769. // HLSL Change Starts
  11770. if (LangOpts.HLSL) {
  11771. assert(DynamicExceptions.size() == 0);
  11772. assert(DynamicExceptionRanges.size() == 0);
  11773. assert(NoexceptExpr == nullptr);
  11774. assert(Exceptions.size() == 0);
  11775. return;
  11776. }
  11777. // HLSL Change Ends
  11778. Exceptions.clear();
  11779. ESI.Type = EST;
  11780. if (EST == EST_Dynamic) {
  11781. Exceptions.reserve(DynamicExceptions.size());
  11782. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  11783. // FIXME: Preserve type source info.
  11784. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  11785. if (IsTopLevel) {
  11786. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  11787. collectUnexpandedParameterPacks(ET, Unexpanded);
  11788. if (!Unexpanded.empty()) {
  11789. DiagnoseUnexpandedParameterPacks(
  11790. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  11791. Unexpanded);
  11792. continue;
  11793. }
  11794. }
  11795. // Check that the type is valid for an exception spec, and
  11796. // drop it if not.
  11797. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  11798. Exceptions.push_back(ET);
  11799. }
  11800. ESI.Exceptions = Exceptions;
  11801. return;
  11802. }
  11803. if (EST == EST_ComputedNoexcept) {
  11804. // If an error occurred, there's no expression here.
  11805. if (NoexceptExpr) {
  11806. assert((NoexceptExpr->isTypeDependent() ||
  11807. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  11808. Context.BoolTy) &&
  11809. "Parser should have made sure that the expression is boolean");
  11810. if (IsTopLevel && NoexceptExpr &&
  11811. DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  11812. ESI.Type = EST_BasicNoexcept;
  11813. return;
  11814. }
  11815. if (!NoexceptExpr->isValueDependent())
  11816. NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
  11817. diag::err_noexcept_needs_constant_expression,
  11818. /*AllowFold*/ false).get();
  11819. ESI.NoexceptExpr = NoexceptExpr;
  11820. }
  11821. return;
  11822. }
  11823. }
  11824. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  11825. ExceptionSpecificationType EST,
  11826. SourceRange SpecificationRange,
  11827. ArrayRef<ParsedType> DynamicExceptions,
  11828. ArrayRef<SourceRange> DynamicExceptionRanges,
  11829. Expr *NoexceptExpr) {
  11830. if (!MethodD)
  11831. return;
  11832. // Dig out the method we're referring to.
  11833. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  11834. MethodD = FunTmpl->getTemplatedDecl();
  11835. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  11836. if (!Method)
  11837. return;
  11838. // Check the exception specification.
  11839. llvm::SmallVector<QualType, 4> Exceptions;
  11840. FunctionProtoType::ExceptionSpecInfo ESI;
  11841. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  11842. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  11843. ESI);
  11844. // Update the exception specification on the function type.
  11845. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  11846. if (Method->isStatic())
  11847. checkThisInStaticMemberFunctionExceptionSpec(Method);
  11848. if (Method->isVirtual()) {
  11849. // Check overrides, which we previously had to delay.
  11850. for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
  11851. OEnd = Method->end_overridden_methods();
  11852. O != OEnd; ++O)
  11853. CheckOverridingFunctionExceptionSpec(Method, *O);
  11854. }
  11855. }
  11856. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  11857. ///
  11858. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  11859. SourceLocation DeclStart,
  11860. Declarator &D, Expr *BitWidth,
  11861. InClassInitStyle InitStyle,
  11862. AccessSpecifier AS,
  11863. AttributeList *MSPropertyAttr) {
  11864. IdentifierInfo *II = D.getIdentifier();
  11865. if (!II) {
  11866. Diag(DeclStart, diag::err_anonymous_property);
  11867. return nullptr;
  11868. }
  11869. SourceLocation Loc = D.getIdentifierLoc();
  11870. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11871. QualType T = TInfo->getType();
  11872. if (getLangOpts().CPlusPlus) {
  11873. CheckExtraCXXDefaultArguments(D);
  11874. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  11875. UPPC_DataMemberType)) {
  11876. D.setInvalidType();
  11877. T = Context.IntTy;
  11878. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  11879. }
  11880. }
  11881. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  11882. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  11883. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  11884. diag::err_invalid_thread)
  11885. << DeclSpec::getSpecifierName(TSCS);
  11886. // Check to see if this name was declared as a member previously
  11887. NamedDecl *PrevDecl = nullptr;
  11888. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  11889. LookupName(Previous, S);
  11890. switch (Previous.getResultKind()) {
  11891. case LookupResult::Found:
  11892. case LookupResult::FoundUnresolvedValue:
  11893. PrevDecl = Previous.getAsSingle<NamedDecl>();
  11894. break;
  11895. case LookupResult::FoundOverloaded:
  11896. PrevDecl = Previous.getRepresentativeDecl();
  11897. break;
  11898. case LookupResult::NotFound:
  11899. case LookupResult::NotFoundInCurrentInstantiation:
  11900. case LookupResult::Ambiguous:
  11901. break;
  11902. }
  11903. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  11904. // Maybe we will complain about the shadowed template parameter.
  11905. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11906. // Just pretend that we didn't see the previous declaration.
  11907. PrevDecl = nullptr;
  11908. }
  11909. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  11910. PrevDecl = nullptr;
  11911. SourceLocation TSSL = D.getLocStart();
  11912. const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
  11913. MSPropertyDecl *NewPD = MSPropertyDecl::Create(
  11914. Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
  11915. ProcessDeclAttributes(TUScope, NewPD, D);
  11916. NewPD->setAccess(AS);
  11917. if (NewPD->isInvalidDecl())
  11918. Record->setInvalidDecl();
  11919. if (D.getDeclSpec().isModulePrivateSpecified())
  11920. NewPD->setModulePrivate();
  11921. if (NewPD->isInvalidDecl() && PrevDecl) {
  11922. // Don't introduce NewFD into scope; there's already something
  11923. // with the same name in the same scope.
  11924. } else if (II) {
  11925. PushOnScopeChains(NewPD, S);
  11926. } else
  11927. Record->addDecl(NewPD);
  11928. return NewPD;
  11929. }