SemaExprCXX.cpp 353 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901
  1. //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// Implements semantic analysis for C++ expressions.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/Template.h"
  14. #include "clang/Sema/SemaInternal.h"
  15. #include "TreeTransform.h"
  16. #include "TypeLocBuilder.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/ASTLambda.h"
  19. #include "clang/AST/CXXInheritance.h"
  20. #include "clang/AST/CharUnits.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/AST/RecursiveASTVisitor.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/Basic/AlignedAllocation.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/Preprocessor.h"
  30. #include "clang/Sema/DeclSpec.h"
  31. #include "clang/Sema/Initialization.h"
  32. #include "clang/Sema/Lookup.h"
  33. #include "clang/Sema/ParsedTemplate.h"
  34. #include "clang/Sema/Scope.h"
  35. #include "clang/Sema/ScopeInfo.h"
  36. #include "clang/Sema/SemaLambda.h"
  37. #include "clang/Sema/TemplateDeduction.h"
  38. #include "llvm/ADT/APInt.h"
  39. #include "llvm/ADT/STLExtras.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. using namespace clang;
  42. using namespace sema;
  43. /// Handle the result of the special case name lookup for inheriting
  44. /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
  45. /// constructor names in member using declarations, even if 'X' is not the
  46. /// name of the corresponding type.
  47. ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
  48. SourceLocation NameLoc,
  49. IdentifierInfo &Name) {
  50. NestedNameSpecifier *NNS = SS.getScopeRep();
  51. // Convert the nested-name-specifier into a type.
  52. QualType Type;
  53. switch (NNS->getKind()) {
  54. case NestedNameSpecifier::TypeSpec:
  55. case NestedNameSpecifier::TypeSpecWithTemplate:
  56. Type = QualType(NNS->getAsType(), 0);
  57. break;
  58. case NestedNameSpecifier::Identifier:
  59. // Strip off the last layer of the nested-name-specifier and build a
  60. // typename type for it.
  61. assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
  62. Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
  63. NNS->getAsIdentifier());
  64. break;
  65. case NestedNameSpecifier::Global:
  66. case NestedNameSpecifier::Super:
  67. case NestedNameSpecifier::Namespace:
  68. case NestedNameSpecifier::NamespaceAlias:
  69. llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
  70. }
  71. // This reference to the type is located entirely at the location of the
  72. // final identifier in the qualified-id.
  73. return CreateParsedType(Type,
  74. Context.getTrivialTypeSourceInfo(Type, NameLoc));
  75. }
  76. ParsedType Sema::getConstructorName(IdentifierInfo &II,
  77. SourceLocation NameLoc,
  78. Scope *S, CXXScopeSpec &SS,
  79. bool EnteringContext) {
  80. CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
  81. assert(CurClass && &II == CurClass->getIdentifier() &&
  82. "not a constructor name");
  83. // When naming a constructor as a member of a dependent context (eg, in a
  84. // friend declaration or an inherited constructor declaration), form an
  85. // unresolved "typename" type.
  86. if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
  87. QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
  88. return ParsedType::make(T);
  89. }
  90. if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
  91. return ParsedType();
  92. // Find the injected-class-name declaration. Note that we make no attempt to
  93. // diagnose cases where the injected-class-name is shadowed: the only
  94. // declaration that can validly shadow the injected-class-name is a
  95. // non-static data member, and if the class contains both a non-static data
  96. // member and a constructor then it is ill-formed (we check that in
  97. // CheckCompletedCXXClass).
  98. CXXRecordDecl *InjectedClassName = nullptr;
  99. for (NamedDecl *ND : CurClass->lookup(&II)) {
  100. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  101. if (RD && RD->isInjectedClassName()) {
  102. InjectedClassName = RD;
  103. break;
  104. }
  105. }
  106. if (!InjectedClassName) {
  107. if (!CurClass->isInvalidDecl()) {
  108. // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
  109. // properly. Work around it here for now.
  110. Diag(SS.getLastQualifierNameLoc(),
  111. diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
  112. }
  113. return ParsedType();
  114. }
  115. QualType T = Context.getTypeDeclType(InjectedClassName);
  116. DiagnoseUseOfDecl(InjectedClassName, NameLoc);
  117. MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
  118. return ParsedType::make(T);
  119. }
  120. ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
  121. IdentifierInfo &II,
  122. SourceLocation NameLoc,
  123. Scope *S, CXXScopeSpec &SS,
  124. ParsedType ObjectTypePtr,
  125. bool EnteringContext) {
  126. // Determine where to perform name lookup.
  127. // FIXME: This area of the standard is very messy, and the current
  128. // wording is rather unclear about which scopes we search for the
  129. // destructor name; see core issues 399 and 555. Issue 399 in
  130. // particular shows where the current description of destructor name
  131. // lookup is completely out of line with existing practice, e.g.,
  132. // this appears to be ill-formed:
  133. //
  134. // namespace N {
  135. // template <typename T> struct S {
  136. // ~S();
  137. // };
  138. // }
  139. //
  140. // void f(N::S<int>* s) {
  141. // s->N::S<int>::~S();
  142. // }
  143. //
  144. // See also PR6358 and PR6359.
  145. //
  146. // For now, we accept all the cases in which the name given could plausibly
  147. // be interpreted as a correct destructor name, issuing off-by-default
  148. // extension diagnostics on the cases that don't strictly conform to the
  149. // C++20 rules. This basically means we always consider looking in the
  150. // nested-name-specifier prefix, the complete nested-name-specifier, and
  151. // the scope, and accept if we find the expected type in any of the three
  152. // places.
  153. if (SS.isInvalid())
  154. return nullptr;
  155. // Whether we've failed with a diagnostic already.
  156. bool Failed = false;
  157. llvm::SmallVector<NamedDecl*, 8> FoundDecls;
  158. llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
  159. // If we have an object type, it's because we are in a
  160. // pseudo-destructor-expression or a member access expression, and
  161. // we know what type we're looking for.
  162. QualType SearchType =
  163. ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
  164. auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
  165. auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
  166. auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
  167. if (!Type)
  168. return false;
  169. if (SearchType.isNull() || SearchType->isDependentType())
  170. return true;
  171. QualType T = Context.getTypeDeclType(Type);
  172. return Context.hasSameUnqualifiedType(T, SearchType);
  173. };
  174. unsigned NumAcceptableResults = 0;
  175. for (NamedDecl *D : Found) {
  176. if (IsAcceptableResult(D))
  177. ++NumAcceptableResults;
  178. // Don't list a class twice in the lookup failure diagnostic if it's
  179. // found by both its injected-class-name and by the name in the enclosing
  180. // scope.
  181. if (auto *RD = dyn_cast<CXXRecordDecl>(D))
  182. if (RD->isInjectedClassName())
  183. D = cast<NamedDecl>(RD->getParent());
  184. if (FoundDeclSet.insert(D).second)
  185. FoundDecls.push_back(D);
  186. }
  187. // As an extension, attempt to "fix" an ambiguity by erasing all non-type
  188. // results, and all non-matching results if we have a search type. It's not
  189. // clear what the right behavior is if destructor lookup hits an ambiguity,
  190. // but other compilers do generally accept at least some kinds of
  191. // ambiguity.
  192. if (Found.isAmbiguous() && NumAcceptableResults == 1) {
  193. Diag(NameLoc, diag::ext_dtor_name_ambiguous);
  194. LookupResult::Filter F = Found.makeFilter();
  195. while (F.hasNext()) {
  196. NamedDecl *D = F.next();
  197. if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
  198. Diag(D->getLocation(), diag::note_destructor_type_here)
  199. << Context.getTypeDeclType(TD);
  200. else
  201. Diag(D->getLocation(), diag::note_destructor_nontype_here);
  202. if (!IsAcceptableResult(D))
  203. F.erase();
  204. }
  205. F.done();
  206. }
  207. if (Found.isAmbiguous())
  208. Failed = true;
  209. if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
  210. if (IsAcceptableResult(Type)) {
  211. QualType T = Context.getTypeDeclType(Type);
  212. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  213. return CreateParsedType(T,
  214. Context.getTrivialTypeSourceInfo(T, NameLoc));
  215. }
  216. }
  217. return nullptr;
  218. };
  219. bool IsDependent = false;
  220. auto LookupInObjectType = [&]() -> ParsedType {
  221. if (Failed || SearchType.isNull())
  222. return nullptr;
  223. IsDependent |= SearchType->isDependentType();
  224. LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
  225. DeclContext *LookupCtx = computeDeclContext(SearchType);
  226. if (!LookupCtx)
  227. return nullptr;
  228. LookupQualifiedName(Found, LookupCtx);
  229. return CheckLookupResult(Found);
  230. };
  231. auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
  232. if (Failed)
  233. return nullptr;
  234. IsDependent |= isDependentScopeSpecifier(LookupSS);
  235. DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
  236. if (!LookupCtx)
  237. return nullptr;
  238. LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
  239. if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
  240. Failed = true;
  241. return nullptr;
  242. }
  243. LookupQualifiedName(Found, LookupCtx);
  244. return CheckLookupResult(Found);
  245. };
  246. auto LookupInScope = [&]() -> ParsedType {
  247. if (Failed || !S)
  248. return nullptr;
  249. LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
  250. LookupName(Found, S);
  251. return CheckLookupResult(Found);
  252. };
  253. // C++2a [basic.lookup.qual]p6:
  254. // In a qualified-id of the form
  255. //
  256. // nested-name-specifier[opt] type-name :: ~ type-name
  257. //
  258. // the second type-name is looked up in the same scope as the first.
  259. //
  260. // We interpret this as meaning that if you do a dual-scope lookup for the
  261. // first name, you also do a dual-scope lookup for the second name, per
  262. // C++ [basic.lookup.classref]p4:
  263. //
  264. // If the id-expression in a class member access is a qualified-id of the
  265. // form
  266. //
  267. // class-name-or-namespace-name :: ...
  268. //
  269. // the class-name-or-namespace-name following the . or -> is first looked
  270. // up in the class of the object expression and the name, if found, is used.
  271. // Otherwise, it is looked up in the context of the entire
  272. // postfix-expression.
  273. //
  274. // This looks in the same scopes as for an unqualified destructor name:
  275. //
  276. // C++ [basic.lookup.classref]p3:
  277. // If the unqualified-id is ~ type-name, the type-name is looked up
  278. // in the context of the entire postfix-expression. If the type T
  279. // of the object expression is of a class type C, the type-name is
  280. // also looked up in the scope of class C. At least one of the
  281. // lookups shall find a name that refers to cv T.
  282. //
  283. // FIXME: The intent is unclear here. Should type-name::~type-name look in
  284. // the scope anyway if it finds a non-matching name declared in the class?
  285. // If both lookups succeed and find a dependent result, which result should
  286. // we retain? (Same question for p->~type-name().)
  287. if (NestedNameSpecifier *Prefix =
  288. SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
  289. // This is
  290. //
  291. // nested-name-specifier type-name :: ~ type-name
  292. //
  293. // Look for the second type-name in the nested-name-specifier.
  294. CXXScopeSpec PrefixSS;
  295. PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
  296. if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
  297. return T;
  298. } else {
  299. // This is one of
  300. //
  301. // type-name :: ~ type-name
  302. // ~ type-name
  303. //
  304. // Look in the scope and (if any) the object type.
  305. if (ParsedType T = LookupInScope())
  306. return T;
  307. if (ParsedType T = LookupInObjectType())
  308. return T;
  309. }
  310. if (Failed)
  311. return nullptr;
  312. if (IsDependent) {
  313. // We didn't find our type, but that's OK: it's dependent anyway.
  314. // FIXME: What if we have no nested-name-specifier?
  315. QualType T = CheckTypenameType(ETK_None, SourceLocation(),
  316. SS.getWithLocInContext(Context),
  317. II, NameLoc);
  318. return ParsedType::make(T);
  319. }
  320. // The remaining cases are all non-standard extensions imitating the behavior
  321. // of various other compilers.
  322. unsigned NumNonExtensionDecls = FoundDecls.size();
  323. if (SS.isSet()) {
  324. // For compatibility with older broken C++ rules and existing code,
  325. //
  326. // nested-name-specifier :: ~ type-name
  327. //
  328. // also looks for type-name within the nested-name-specifier.
  329. if (ParsedType T = LookupInNestedNameSpec(SS)) {
  330. Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
  331. << SS.getRange()
  332. << FixItHint::CreateInsertion(SS.getEndLoc(),
  333. ("::" + II.getName()).str());
  334. return T;
  335. }
  336. // For compatibility with other compilers and older versions of Clang,
  337. //
  338. // nested-name-specifier type-name :: ~ type-name
  339. //
  340. // also looks for type-name in the scope. Unfortunately, we can't
  341. // reasonably apply this fallback for dependent nested-name-specifiers.
  342. if (SS.getScopeRep()->getPrefix()) {
  343. if (ParsedType T = LookupInScope()) {
  344. Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
  345. << FixItHint::CreateRemoval(SS.getRange());
  346. Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
  347. << GetTypeFromParser(T);
  348. return T;
  349. }
  350. }
  351. }
  352. // We didn't find anything matching; tell the user what we did find (if
  353. // anything).
  354. // Don't tell the user about declarations we shouldn't have found.
  355. FoundDecls.resize(NumNonExtensionDecls);
  356. // List types before non-types.
  357. std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
  358. [](NamedDecl *A, NamedDecl *B) {
  359. return isa<TypeDecl>(A->getUnderlyingDecl()) >
  360. isa<TypeDecl>(B->getUnderlyingDecl());
  361. });
  362. // Suggest a fixit to properly name the destroyed type.
  363. auto MakeFixItHint = [&]{
  364. const CXXRecordDecl *Destroyed = nullptr;
  365. // FIXME: If we have a scope specifier, suggest its last component?
  366. if (!SearchType.isNull())
  367. Destroyed = SearchType->getAsCXXRecordDecl();
  368. else if (S)
  369. Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
  370. if (Destroyed)
  371. return FixItHint::CreateReplacement(SourceRange(NameLoc),
  372. Destroyed->getNameAsString());
  373. return FixItHint();
  374. };
  375. if (FoundDecls.empty()) {
  376. // FIXME: Attempt typo-correction?
  377. Diag(NameLoc, diag::err_undeclared_destructor_name)
  378. << &II << MakeFixItHint();
  379. } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
  380. if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
  381. assert(!SearchType.isNull() &&
  382. "should only reject a type result if we have a search type");
  383. QualType T = Context.getTypeDeclType(TD);
  384. Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
  385. << T << SearchType << MakeFixItHint();
  386. } else {
  387. Diag(NameLoc, diag::err_destructor_expr_nontype)
  388. << &II << MakeFixItHint();
  389. }
  390. } else {
  391. Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
  392. : diag::err_destructor_expr_mismatch)
  393. << &II << SearchType << MakeFixItHint();
  394. }
  395. for (NamedDecl *FoundD : FoundDecls) {
  396. if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
  397. Diag(FoundD->getLocation(), diag::note_destructor_type_here)
  398. << Context.getTypeDeclType(TD);
  399. else
  400. Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
  401. << FoundD;
  402. }
  403. return nullptr;
  404. }
  405. ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
  406. ParsedType ObjectType) {
  407. if (DS.getTypeSpecType() == DeclSpec::TST_error)
  408. return nullptr;
  409. if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
  410. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  411. return nullptr;
  412. }
  413. assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
  414. "unexpected type in getDestructorType");
  415. QualType T = BuildDecltypeType(DS.getRepAsExpr());
  416. // If we know the type of the object, check that the correct destructor
  417. // type was named now; we can give better diagnostics this way.
  418. QualType SearchType = GetTypeFromParser(ObjectType);
  419. if (!SearchType.isNull() && !SearchType->isDependentType() &&
  420. !Context.hasSameUnqualifiedType(T, SearchType)) {
  421. Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
  422. << T << SearchType;
  423. return nullptr;
  424. }
  425. return ParsedType::make(T);
  426. }
  427. bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
  428. const UnqualifiedId &Name, bool IsUDSuffix) {
  429. assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
  430. if (!IsUDSuffix) {
  431. // [over.literal] p8
  432. //
  433. // double operator""_Bq(long double); // OK: not a reserved identifier
  434. // double operator"" _Bq(long double); // ill-formed, no diagnostic required
  435. IdentifierInfo *II = Name.Identifier;
  436. ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());
  437. SourceLocation Loc = Name.getEndLoc();
  438. if (isReservedInAllContexts(Status) &&
  439. !PP.getSourceManager().isInSystemHeader(Loc)) {
  440. Diag(Loc, diag::warn_reserved_extern_symbol)
  441. << II << static_cast<int>(Status)
  442. << FixItHint::CreateReplacement(
  443. Name.getSourceRange(),
  444. (StringRef("operator\"\"") + II->getName()).str());
  445. }
  446. }
  447. if (!SS.isValid())
  448. return false;
  449. switch (SS.getScopeRep()->getKind()) {
  450. case NestedNameSpecifier::Identifier:
  451. case NestedNameSpecifier::TypeSpec:
  452. case NestedNameSpecifier::TypeSpecWithTemplate:
  453. // Per C++11 [over.literal]p2, literal operators can only be declared at
  454. // namespace scope. Therefore, this unqualified-id cannot name anything.
  455. // Reject it early, because we have no AST representation for this in the
  456. // case where the scope is dependent.
  457. Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
  458. << SS.getScopeRep();
  459. return true;
  460. case NestedNameSpecifier::Global:
  461. case NestedNameSpecifier::Super:
  462. case NestedNameSpecifier::Namespace:
  463. case NestedNameSpecifier::NamespaceAlias:
  464. return false;
  465. }
  466. llvm_unreachable("unknown nested name specifier kind");
  467. }
  468. /// Build a C++ typeid expression with a type operand.
  469. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
  470. SourceLocation TypeidLoc,
  471. TypeSourceInfo *Operand,
  472. SourceLocation RParenLoc) {
  473. // C++ [expr.typeid]p4:
  474. // The top-level cv-qualifiers of the lvalue expression or the type-id
  475. // that is the operand of typeid are always ignored.
  476. // If the type of the type-id is a class type or a reference to a class
  477. // type, the class shall be completely-defined.
  478. Qualifiers Quals;
  479. QualType T
  480. = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
  481. Quals);
  482. if (T->getAs<RecordType>() &&
  483. RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
  484. return ExprError();
  485. if (T->isVariablyModifiedType())
  486. return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
  487. if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
  488. return ExprError();
  489. return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
  490. SourceRange(TypeidLoc, RParenLoc));
  491. }
  492. /// Build a C++ typeid expression with an expression operand.
  493. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
  494. SourceLocation TypeidLoc,
  495. Expr *E,
  496. SourceLocation RParenLoc) {
  497. bool WasEvaluated = false;
  498. if (E && !E->isTypeDependent()) {
  499. if (E->hasPlaceholderType()) {
  500. ExprResult result = CheckPlaceholderExpr(E);
  501. if (result.isInvalid()) return ExprError();
  502. E = result.get();
  503. }
  504. QualType T = E->getType();
  505. if (const RecordType *RecordT = T->getAs<RecordType>()) {
  506. CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
  507. // C++ [expr.typeid]p3:
  508. // [...] If the type of the expression is a class type, the class
  509. // shall be completely-defined.
  510. if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
  511. return ExprError();
  512. // C++ [expr.typeid]p3:
  513. // When typeid is applied to an expression other than an glvalue of a
  514. // polymorphic class type [...] [the] expression is an unevaluated
  515. // operand. [...]
  516. if (RecordD->isPolymorphic() && E->isGLValue()) {
  517. if (isUnevaluatedContext()) {
  518. // The operand was processed in unevaluated context, switch the
  519. // context and recheck the subexpression.
  520. ExprResult Result = TransformToPotentiallyEvaluated(E);
  521. if (Result.isInvalid())
  522. return ExprError();
  523. E = Result.get();
  524. }
  525. // We require a vtable to query the type at run time.
  526. MarkVTableUsed(TypeidLoc, RecordD);
  527. WasEvaluated = true;
  528. }
  529. }
  530. ExprResult Result = CheckUnevaluatedOperand(E);
  531. if (Result.isInvalid())
  532. return ExprError();
  533. E = Result.get();
  534. // C++ [expr.typeid]p4:
  535. // [...] If the type of the type-id is a reference to a possibly
  536. // cv-qualified type, the result of the typeid expression refers to a
  537. // std::type_info object representing the cv-unqualified referenced
  538. // type.
  539. Qualifiers Quals;
  540. QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
  541. if (!Context.hasSameType(T, UnqualT)) {
  542. T = UnqualT;
  543. E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
  544. }
  545. }
  546. if (E->getType()->isVariablyModifiedType())
  547. return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
  548. << E->getType());
  549. else if (!inTemplateInstantiation() &&
  550. E->HasSideEffects(Context, WasEvaluated)) {
  551. // The expression operand for typeid is in an unevaluated expression
  552. // context, so side effects could result in unintended consequences.
  553. Diag(E->getExprLoc(), WasEvaluated
  554. ? diag::warn_side_effects_typeid
  555. : diag::warn_side_effects_unevaluated_context);
  556. }
  557. return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
  558. SourceRange(TypeidLoc, RParenLoc));
  559. }
  560. /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
  561. ExprResult
  562. Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
  563. bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
  564. // typeid is not supported in OpenCL.
  565. if (getLangOpts().OpenCLCPlusPlus) {
  566. return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
  567. << "typeid");
  568. }
  569. // Find the std::type_info type.
  570. if (!getStdNamespace())
  571. return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
  572. if (!CXXTypeInfoDecl) {
  573. IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
  574. LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
  575. LookupQualifiedName(R, getStdNamespace());
  576. CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
  577. // Microsoft's typeinfo doesn't have type_info in std but in the global
  578. // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
  579. if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
  580. LookupQualifiedName(R, Context.getTranslationUnitDecl());
  581. CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
  582. }
  583. if (!CXXTypeInfoDecl)
  584. return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
  585. }
  586. if (!getLangOpts().RTTI) {
  587. return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
  588. }
  589. QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
  590. if (isType) {
  591. // The operand is a type; handle it as such.
  592. TypeSourceInfo *TInfo = nullptr;
  593. QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
  594. &TInfo);
  595. if (T.isNull())
  596. return ExprError();
  597. if (!TInfo)
  598. TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
  599. return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
  600. }
  601. // The operand is an expression.
  602. ExprResult Result =
  603. BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
  604. if (!getLangOpts().RTTIData && !Result.isInvalid())
  605. if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
  606. if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
  607. Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
  608. << (getDiagnostics().getDiagnosticOptions().getFormat() ==
  609. DiagnosticOptions::MSVC);
  610. return Result;
  611. }
  612. /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
  613. /// a single GUID.
  614. static void
  615. getUuidAttrOfType(Sema &SemaRef, QualType QT,
  616. llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
  617. // Optionally remove one level of pointer, reference or array indirection.
  618. const Type *Ty = QT.getTypePtr();
  619. if (QT->isPointerType() || QT->isReferenceType())
  620. Ty = QT->getPointeeType().getTypePtr();
  621. else if (QT->isArrayType())
  622. Ty = Ty->getBaseElementTypeUnsafe();
  623. const auto *TD = Ty->getAsTagDecl();
  624. if (!TD)
  625. return;
  626. if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
  627. UuidAttrs.insert(Uuid);
  628. return;
  629. }
  630. // __uuidof can grab UUIDs from template arguments.
  631. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
  632. const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
  633. for (const TemplateArgument &TA : TAL.asArray()) {
  634. const UuidAttr *UuidForTA = nullptr;
  635. if (TA.getKind() == TemplateArgument::Type)
  636. getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
  637. else if (TA.getKind() == TemplateArgument::Declaration)
  638. getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
  639. if (UuidForTA)
  640. UuidAttrs.insert(UuidForTA);
  641. }
  642. }
  643. }
  644. /// Build a Microsoft __uuidof expression with a type operand.
  645. ExprResult Sema::BuildCXXUuidof(QualType Type,
  646. SourceLocation TypeidLoc,
  647. TypeSourceInfo *Operand,
  648. SourceLocation RParenLoc) {
  649. MSGuidDecl *Guid = nullptr;
  650. if (!Operand->getType()->isDependentType()) {
  651. llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
  652. getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
  653. if (UuidAttrs.empty())
  654. return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
  655. if (UuidAttrs.size() > 1)
  656. return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
  657. Guid = UuidAttrs.back()->getGuidDecl();
  658. }
  659. return new (Context)
  660. CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
  661. }
  662. /// Build a Microsoft __uuidof expression with an expression operand.
  663. ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
  664. Expr *E, SourceLocation RParenLoc) {
  665. MSGuidDecl *Guid = nullptr;
  666. if (!E->getType()->isDependentType()) {
  667. if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  668. // A null pointer results in {00000000-0000-0000-0000-000000000000}.
  669. Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
  670. } else {
  671. llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
  672. getUuidAttrOfType(*this, E->getType(), UuidAttrs);
  673. if (UuidAttrs.empty())
  674. return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
  675. if (UuidAttrs.size() > 1)
  676. return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
  677. Guid = UuidAttrs.back()->getGuidDecl();
  678. }
  679. }
  680. return new (Context)
  681. CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
  682. }
  683. /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
  684. ExprResult
  685. Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
  686. bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
  687. QualType GuidType = Context.getMSGuidType();
  688. GuidType.addConst();
  689. if (isType) {
  690. // The operand is a type; handle it as such.
  691. TypeSourceInfo *TInfo = nullptr;
  692. QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
  693. &TInfo);
  694. if (T.isNull())
  695. return ExprError();
  696. if (!TInfo)
  697. TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
  698. return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
  699. }
  700. // The operand is an expression.
  701. return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
  702. }
  703. /// ActOnCXXBoolLiteral - Parse {true,false} literals.
  704. ExprResult
  705. Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  706. assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
  707. "Unknown C++ Boolean value!");
  708. return new (Context)
  709. CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
  710. }
  711. /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
  712. ExprResult
  713. Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
  714. return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
  715. }
  716. /// ActOnCXXThrow - Parse throw expressions.
  717. ExprResult
  718. Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
  719. bool IsThrownVarInScope = false;
  720. if (Ex) {
  721. // C++0x [class.copymove]p31:
  722. // When certain criteria are met, an implementation is allowed to omit the
  723. // copy/move construction of a class object [...]
  724. //
  725. // - in a throw-expression, when the operand is the name of a
  726. // non-volatile automatic object (other than a function or catch-
  727. // clause parameter) whose scope does not extend beyond the end of the
  728. // innermost enclosing try-block (if there is one), the copy/move
  729. // operation from the operand to the exception object (15.1) can be
  730. // omitted by constructing the automatic object directly into the
  731. // exception object
  732. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
  733. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  734. if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
  735. for( ; S; S = S->getParent()) {
  736. if (S->isDeclScope(Var)) {
  737. IsThrownVarInScope = true;
  738. break;
  739. }
  740. if (S->getFlags() &
  741. (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
  742. Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
  743. Scope::TryScope))
  744. break;
  745. }
  746. }
  747. }
  748. }
  749. return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
  750. }
  751. ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
  752. bool IsThrownVarInScope) {
  753. // Don't report an error if 'throw' is used in system headers.
  754. if (!getLangOpts().CXXExceptions &&
  755. !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
  756. // Delay error emission for the OpenMP device code.
  757. targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
  758. }
  759. // Exceptions aren't allowed in CUDA device code.
  760. if (getLangOpts().CUDA)
  761. CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
  762. << "throw" << CurrentCUDATarget();
  763. if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
  764. Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
  765. if (Ex && !Ex->isTypeDependent()) {
  766. // Initialize the exception result. This implicitly weeds out
  767. // abstract types or types with inaccessible copy constructors.
  768. // C++0x [class.copymove]p31:
  769. // When certain criteria are met, an implementation is allowed to omit the
  770. // copy/move construction of a class object [...]
  771. //
  772. // - in a throw-expression, when the operand is the name of a
  773. // non-volatile automatic object (other than a function or
  774. // catch-clause
  775. // parameter) whose scope does not extend beyond the end of the
  776. // innermost enclosing try-block (if there is one), the copy/move
  777. // operation from the operand to the exception object (15.1) can be
  778. // omitted by constructing the automatic object directly into the
  779. // exception object
  780. NamedReturnInfo NRInfo =
  781. IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
  782. QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
  783. if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
  784. return ExprError();
  785. InitializedEntity Entity =
  786. InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
  787. ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
  788. if (Res.isInvalid())
  789. return ExprError();
  790. Ex = Res.get();
  791. }
  792. // PPC MMA non-pointer types are not allowed as throw expr types.
  793. if (Ex && Context.getTargetInfo().getTriple().isPPC64())
  794. CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
  795. return new (Context)
  796. CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
  797. }
  798. static void
  799. collectPublicBases(CXXRecordDecl *RD,
  800. llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
  801. llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
  802. llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
  803. bool ParentIsPublic) {
  804. for (const CXXBaseSpecifier &BS : RD->bases()) {
  805. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  806. bool NewSubobject;
  807. // Virtual bases constitute the same subobject. Non-virtual bases are
  808. // always distinct subobjects.
  809. if (BS.isVirtual())
  810. NewSubobject = VBases.insert(BaseDecl).second;
  811. else
  812. NewSubobject = true;
  813. if (NewSubobject)
  814. ++SubobjectsSeen[BaseDecl];
  815. // Only add subobjects which have public access throughout the entire chain.
  816. bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
  817. if (PublicPath)
  818. PublicSubobjectsSeen.insert(BaseDecl);
  819. // Recurse on to each base subobject.
  820. collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
  821. PublicPath);
  822. }
  823. }
  824. static void getUnambiguousPublicSubobjects(
  825. CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
  826. llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
  827. llvm::SmallSet<CXXRecordDecl *, 2> VBases;
  828. llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
  829. SubobjectsSeen[RD] = 1;
  830. PublicSubobjectsSeen.insert(RD);
  831. collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
  832. /*ParentIsPublic=*/true);
  833. for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
  834. // Skip ambiguous objects.
  835. if (SubobjectsSeen[PublicSubobject] > 1)
  836. continue;
  837. Objects.push_back(PublicSubobject);
  838. }
  839. }
  840. /// CheckCXXThrowOperand - Validate the operand of a throw.
  841. bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
  842. QualType ExceptionObjectTy, Expr *E) {
  843. // If the type of the exception would be an incomplete type or a pointer
  844. // to an incomplete type other than (cv) void the program is ill-formed.
  845. QualType Ty = ExceptionObjectTy;
  846. bool isPointer = false;
  847. if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
  848. Ty = Ptr->getPointeeType();
  849. isPointer = true;
  850. }
  851. if (!isPointer || !Ty->isVoidType()) {
  852. if (RequireCompleteType(ThrowLoc, Ty,
  853. isPointer ? diag::err_throw_incomplete_ptr
  854. : diag::err_throw_incomplete,
  855. E->getSourceRange()))
  856. return true;
  857. if (!isPointer && Ty->isSizelessType()) {
  858. Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
  859. return true;
  860. }
  861. if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
  862. diag::err_throw_abstract_type, E))
  863. return true;
  864. }
  865. // If the exception has class type, we need additional handling.
  866. CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  867. if (!RD)
  868. return false;
  869. // If we are throwing a polymorphic class type or pointer thereof,
  870. // exception handling will make use of the vtable.
  871. MarkVTableUsed(ThrowLoc, RD);
  872. // If a pointer is thrown, the referenced object will not be destroyed.
  873. if (isPointer)
  874. return false;
  875. // If the class has a destructor, we must be able to call it.
  876. if (!RD->hasIrrelevantDestructor()) {
  877. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  878. MarkFunctionReferenced(E->getExprLoc(), Destructor);
  879. CheckDestructorAccess(E->getExprLoc(), Destructor,
  880. PDiag(diag::err_access_dtor_exception) << Ty);
  881. if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
  882. return true;
  883. }
  884. }
  885. // The MSVC ABI creates a list of all types which can catch the exception
  886. // object. This list also references the appropriate copy constructor to call
  887. // if the object is caught by value and has a non-trivial copy constructor.
  888. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  889. // We are only interested in the public, unambiguous bases contained within
  890. // the exception object. Bases which are ambiguous or otherwise
  891. // inaccessible are not catchable types.
  892. llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
  893. getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
  894. for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
  895. // Attempt to lookup the copy constructor. Various pieces of machinery
  896. // will spring into action, like template instantiation, which means this
  897. // cannot be a simple walk of the class's decls. Instead, we must perform
  898. // lookup and overload resolution.
  899. CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
  900. if (!CD || CD->isDeleted())
  901. continue;
  902. // Mark the constructor referenced as it is used by this throw expression.
  903. MarkFunctionReferenced(E->getExprLoc(), CD);
  904. // Skip this copy constructor if it is trivial, we don't need to record it
  905. // in the catchable type data.
  906. if (CD->isTrivial())
  907. continue;
  908. // The copy constructor is non-trivial, create a mapping from this class
  909. // type to this constructor.
  910. // N.B. The selection of copy constructor is not sensitive to this
  911. // particular throw-site. Lookup will be performed at the catch-site to
  912. // ensure that the copy constructor is, in fact, accessible (via
  913. // friendship or any other means).
  914. Context.addCopyConstructorForExceptionObject(Subobject, CD);
  915. // We don't keep the instantiated default argument expressions around so
  916. // we must rebuild them here.
  917. for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
  918. if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
  919. return true;
  920. }
  921. }
  922. }
  923. // Under the Itanium C++ ABI, memory for the exception object is allocated by
  924. // the runtime with no ability for the compiler to request additional
  925. // alignment. Warn if the exception type requires alignment beyond the minimum
  926. // guaranteed by the target C++ runtime.
  927. if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
  928. CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
  929. CharUnits ExnObjAlign = Context.getExnObjectAlignment();
  930. if (ExnObjAlign < TypeAlign) {
  931. Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
  932. Diag(ThrowLoc, diag::note_throw_underaligned_obj)
  933. << Ty << (unsigned)TypeAlign.getQuantity()
  934. << (unsigned)ExnObjAlign.getQuantity();
  935. }
  936. }
  937. return false;
  938. }
  939. static QualType adjustCVQualifiersForCXXThisWithinLambda(
  940. ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
  941. DeclContext *CurSemaContext, ASTContext &ASTCtx) {
  942. QualType ClassType = ThisTy->getPointeeType();
  943. LambdaScopeInfo *CurLSI = nullptr;
  944. DeclContext *CurDC = CurSemaContext;
  945. // Iterate through the stack of lambdas starting from the innermost lambda to
  946. // the outermost lambda, checking if '*this' is ever captured by copy - since
  947. // that could change the cv-qualifiers of the '*this' object.
  948. // The object referred to by '*this' starts out with the cv-qualifiers of its
  949. // member function. We then start with the innermost lambda and iterate
  950. // outward checking to see if any lambda performs a by-copy capture of '*this'
  951. // - and if so, any nested lambda must respect the 'constness' of that
  952. // capturing lamdbda's call operator.
  953. //
  954. // Since the FunctionScopeInfo stack is representative of the lexical
  955. // nesting of the lambda expressions during initial parsing (and is the best
  956. // place for querying information about captures about lambdas that are
  957. // partially processed) and perhaps during instantiation of function templates
  958. // that contain lambda expressions that need to be transformed BUT not
  959. // necessarily during instantiation of a nested generic lambda's function call
  960. // operator (which might even be instantiated at the end of the TU) - at which
  961. // time the DeclContext tree is mature enough to query capture information
  962. // reliably - we use a two pronged approach to walk through all the lexically
  963. // enclosing lambda expressions:
  964. //
  965. // 1) Climb down the FunctionScopeInfo stack as long as each item represents
  966. // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
  967. // enclosed by the call-operator of the LSI below it on the stack (while
  968. // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
  969. // the stack represents the innermost lambda.
  970. //
  971. // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
  972. // represents a lambda's call operator. If it does, we must be instantiating
  973. // a generic lambda's call operator (represented by the Current LSI, and
  974. // should be the only scenario where an inconsistency between the LSI and the
  975. // DeclContext should occur), so climb out the DeclContexts if they
  976. // represent lambdas, while querying the corresponding closure types
  977. // regarding capture information.
  978. // 1) Climb down the function scope info stack.
  979. for (int I = FunctionScopes.size();
  980. I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
  981. (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
  982. cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
  983. CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
  984. CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
  985. if (!CurLSI->isCXXThisCaptured())
  986. continue;
  987. auto C = CurLSI->getCXXThisCapture();
  988. if (C.isCopyCapture()) {
  989. ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
  990. if (CurLSI->CallOperator->isConst())
  991. ClassType.addConst();
  992. return ASTCtx.getPointerType(ClassType);
  993. }
  994. }
  995. // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
  996. // can happen during instantiation of its nested generic lambda call
  997. // operator); 2. if we're in a lambda scope (lambda body).
  998. if (CurLSI && isLambdaCallOperator(CurDC)) {
  999. assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
  1000. "While computing 'this' capture-type for a generic lambda, when we "
  1001. "run out of enclosing LSI's, yet the enclosing DC is a "
  1002. "lambda-call-operator we must be (i.e. Current LSI) in a generic "
  1003. "lambda call oeprator");
  1004. assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
  1005. auto IsThisCaptured =
  1006. [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
  1007. IsConst = false;
  1008. IsByCopy = false;
  1009. for (auto &&C : Closure->captures()) {
  1010. if (C.capturesThis()) {
  1011. if (C.getCaptureKind() == LCK_StarThis)
  1012. IsByCopy = true;
  1013. if (Closure->getLambdaCallOperator()->isConst())
  1014. IsConst = true;
  1015. return true;
  1016. }
  1017. }
  1018. return false;
  1019. };
  1020. bool IsByCopyCapture = false;
  1021. bool IsConstCapture = false;
  1022. CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
  1023. while (Closure &&
  1024. IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
  1025. if (IsByCopyCapture) {
  1026. ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
  1027. if (IsConstCapture)
  1028. ClassType.addConst();
  1029. return ASTCtx.getPointerType(ClassType);
  1030. }
  1031. Closure = isLambdaCallOperator(Closure->getParent())
  1032. ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
  1033. : nullptr;
  1034. }
  1035. }
  1036. return ASTCtx.getPointerType(ClassType);
  1037. }
  1038. QualType Sema::getCurrentThisType() {
  1039. DeclContext *DC = getFunctionLevelDeclContext();
  1040. QualType ThisTy = CXXThisTypeOverride;
  1041. if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
  1042. if (method && method->isInstance())
  1043. ThisTy = method->getThisType();
  1044. }
  1045. if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
  1046. inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
  1047. // This is a lambda call operator that is being instantiated as a default
  1048. // initializer. DC must point to the enclosing class type, so we can recover
  1049. // the 'this' type from it.
  1050. QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
  1051. // There are no cv-qualifiers for 'this' within default initializers,
  1052. // per [expr.prim.general]p4.
  1053. ThisTy = Context.getPointerType(ClassTy);
  1054. }
  1055. // If we are within a lambda's call operator, the cv-qualifiers of 'this'
  1056. // might need to be adjusted if the lambda or any of its enclosing lambda's
  1057. // captures '*this' by copy.
  1058. if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
  1059. return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
  1060. CurContext, Context);
  1061. return ThisTy;
  1062. }
  1063. Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
  1064. Decl *ContextDecl,
  1065. Qualifiers CXXThisTypeQuals,
  1066. bool Enabled)
  1067. : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
  1068. {
  1069. if (!Enabled || !ContextDecl)
  1070. return;
  1071. CXXRecordDecl *Record = nullptr;
  1072. if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
  1073. Record = Template->getTemplatedDecl();
  1074. else
  1075. Record = cast<CXXRecordDecl>(ContextDecl);
  1076. QualType T = S.Context.getRecordType(Record);
  1077. T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
  1078. S.CXXThisTypeOverride = S.Context.getPointerType(T);
  1079. this->Enabled = true;
  1080. }
  1081. Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
  1082. if (Enabled) {
  1083. S.CXXThisTypeOverride = OldCXXThisTypeOverride;
  1084. }
  1085. }
  1086. static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
  1087. SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
  1088. assert(!LSI->isCXXThisCaptured());
  1089. // [=, this] {}; // until C++20: Error: this when = is the default
  1090. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
  1091. !Sema.getLangOpts().CPlusPlus20)
  1092. return;
  1093. Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
  1094. << FixItHint::CreateInsertion(
  1095. DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
  1096. }
  1097. bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
  1098. bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
  1099. const bool ByCopy) {
  1100. // We don't need to capture this in an unevaluated context.
  1101. if (isUnevaluatedContext() && !Explicit)
  1102. return true;
  1103. assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
  1104. const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  1105. ? *FunctionScopeIndexToStopAt
  1106. : FunctionScopes.size() - 1;
  1107. // Check that we can capture the *enclosing object* (referred to by '*this')
  1108. // by the capturing-entity/closure (lambda/block/etc) at
  1109. // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
  1110. // Note: The *enclosing object* can only be captured by-value by a
  1111. // closure that is a lambda, using the explicit notation:
  1112. // [*this] { ... }.
  1113. // Every other capture of the *enclosing object* results in its by-reference
  1114. // capture.
  1115. // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
  1116. // stack), we can capture the *enclosing object* only if:
  1117. // - 'L' has an explicit byref or byval capture of the *enclosing object*
  1118. // - or, 'L' has an implicit capture.
  1119. // AND
  1120. // -- there is no enclosing closure
  1121. // -- or, there is some enclosing closure 'E' that has already captured the
  1122. // *enclosing object*, and every intervening closure (if any) between 'E'
  1123. // and 'L' can implicitly capture the *enclosing object*.
  1124. // -- or, every enclosing closure can implicitly capture the
  1125. // *enclosing object*
  1126. unsigned NumCapturingClosures = 0;
  1127. for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
  1128. if (CapturingScopeInfo *CSI =
  1129. dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
  1130. if (CSI->CXXThisCaptureIndex != 0) {
  1131. // 'this' is already being captured; there isn't anything more to do.
  1132. CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
  1133. break;
  1134. }
  1135. LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
  1136. if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
  1137. // This context can't implicitly capture 'this'; fail out.
  1138. if (BuildAndDiagnose) {
  1139. Diag(Loc, diag::err_this_capture)
  1140. << (Explicit && idx == MaxFunctionScopesIndex);
  1141. if (!Explicit)
  1142. buildLambdaThisCaptureFixit(*this, LSI);
  1143. }
  1144. return true;
  1145. }
  1146. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
  1147. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
  1148. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
  1149. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
  1150. (Explicit && idx == MaxFunctionScopesIndex)) {
  1151. // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
  1152. // iteration through can be an explicit capture, all enclosing closures,
  1153. // if any, must perform implicit captures.
  1154. // This closure can capture 'this'; continue looking upwards.
  1155. NumCapturingClosures++;
  1156. continue;
  1157. }
  1158. // This context can't implicitly capture 'this'; fail out.
  1159. if (BuildAndDiagnose)
  1160. Diag(Loc, diag::err_this_capture)
  1161. << (Explicit && idx == MaxFunctionScopesIndex);
  1162. if (!Explicit)
  1163. buildLambdaThisCaptureFixit(*this, LSI);
  1164. return true;
  1165. }
  1166. break;
  1167. }
  1168. if (!BuildAndDiagnose) return false;
  1169. // If we got here, then the closure at MaxFunctionScopesIndex on the
  1170. // FunctionScopes stack, can capture the *enclosing object*, so capture it
  1171. // (including implicit by-reference captures in any enclosing closures).
  1172. // In the loop below, respect the ByCopy flag only for the closure requesting
  1173. // the capture (i.e. first iteration through the loop below). Ignore it for
  1174. // all enclosing closure's up to NumCapturingClosures (since they must be
  1175. // implicitly capturing the *enclosing object* by reference (see loop
  1176. // above)).
  1177. assert((!ByCopy ||
  1178. isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
  1179. "Only a lambda can capture the enclosing object (referred to by "
  1180. "*this) by copy");
  1181. QualType ThisTy = getCurrentThisType();
  1182. for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
  1183. --idx, --NumCapturingClosures) {
  1184. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
  1185. // The type of the corresponding data member (not a 'this' pointer if 'by
  1186. // copy').
  1187. QualType CaptureType = ThisTy;
  1188. if (ByCopy) {
  1189. // If we are capturing the object referred to by '*this' by copy, ignore
  1190. // any cv qualifiers inherited from the type of the member function for
  1191. // the type of the closure-type's corresponding data member and any use
  1192. // of 'this'.
  1193. CaptureType = ThisTy->getPointeeType();
  1194. CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
  1195. }
  1196. bool isNested = NumCapturingClosures > 1;
  1197. CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
  1198. }
  1199. return false;
  1200. }
  1201. ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
  1202. /// C++ 9.3.2: In the body of a non-static member function, the keyword this
  1203. /// is a non-lvalue expression whose value is the address of the object for
  1204. /// which the function is called.
  1205. QualType ThisTy = getCurrentThisType();
  1206. if (ThisTy.isNull())
  1207. return Diag(Loc, diag::err_invalid_this_use);
  1208. return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
  1209. }
  1210. Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
  1211. bool IsImplicit) {
  1212. auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
  1213. MarkThisReferenced(This);
  1214. return This;
  1215. }
  1216. void Sema::MarkThisReferenced(CXXThisExpr *This) {
  1217. CheckCXXThisCapture(This->getExprLoc());
  1218. }
  1219. bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
  1220. // If we're outside the body of a member function, then we'll have a specified
  1221. // type for 'this'.
  1222. if (CXXThisTypeOverride.isNull())
  1223. return false;
  1224. // Determine whether we're looking into a class that's currently being
  1225. // defined.
  1226. CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
  1227. return Class && Class->isBeingDefined();
  1228. }
  1229. /// Parse construction of a specified type.
  1230. /// Can be interpreted either as function-style casting ("int(x)")
  1231. /// or class type construction ("ClassType(x,y,z)")
  1232. /// or creation of a value-initialized type ("int()").
  1233. ExprResult
  1234. Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
  1235. SourceLocation LParenOrBraceLoc,
  1236. MultiExprArg exprs,
  1237. SourceLocation RParenOrBraceLoc,
  1238. bool ListInitialization) {
  1239. if (!TypeRep)
  1240. return ExprError();
  1241. TypeSourceInfo *TInfo;
  1242. QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
  1243. if (!TInfo)
  1244. TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
  1245. auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
  1246. RParenOrBraceLoc, ListInitialization);
  1247. // Avoid creating a non-type-dependent expression that contains typos.
  1248. // Non-type-dependent expressions are liable to be discarded without
  1249. // checking for embedded typos.
  1250. if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
  1251. !Result.get()->isTypeDependent())
  1252. Result = CorrectDelayedTyposInExpr(Result.get());
  1253. else if (Result.isInvalid())
  1254. Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
  1255. RParenOrBraceLoc, exprs, Ty);
  1256. return Result;
  1257. }
  1258. ExprResult
  1259. Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
  1260. SourceLocation LParenOrBraceLoc,
  1261. MultiExprArg Exprs,
  1262. SourceLocation RParenOrBraceLoc,
  1263. bool ListInitialization) {
  1264. QualType Ty = TInfo->getType();
  1265. SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
  1266. assert((!ListInitialization ||
  1267. (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
  1268. "List initialization must have initializer list as expression.");
  1269. SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
  1270. InitializedEntity Entity =
  1271. InitializedEntity::InitializeTemporary(Context, TInfo);
  1272. InitializationKind Kind =
  1273. Exprs.size()
  1274. ? ListInitialization
  1275. ? InitializationKind::CreateDirectList(
  1276. TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
  1277. : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
  1278. RParenOrBraceLoc)
  1279. : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
  1280. RParenOrBraceLoc);
  1281. // C++1z [expr.type.conv]p1:
  1282. // If the type is a placeholder for a deduced class type, [...perform class
  1283. // template argument deduction...]
  1284. DeducedType *Deduced = Ty->getContainedDeducedType();
  1285. if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
  1286. Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
  1287. Kind, Exprs);
  1288. if (Ty.isNull())
  1289. return ExprError();
  1290. Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
  1291. }
  1292. if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
  1293. // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
  1294. // directly. We work around this by dropping the locations of the braces.
  1295. SourceRange Locs = ListInitialization
  1296. ? SourceRange()
  1297. : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
  1298. return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(),
  1299. TInfo, Locs.getBegin(), Exprs,
  1300. Locs.getEnd());
  1301. }
  1302. // C++ [expr.type.conv]p1:
  1303. // If the expression list is a parenthesized single expression, the type
  1304. // conversion expression is equivalent (in definedness, and if defined in
  1305. // meaning) to the corresponding cast expression.
  1306. if (Exprs.size() == 1 && !ListInitialization &&
  1307. !isa<InitListExpr>(Exprs[0])) {
  1308. Expr *Arg = Exprs[0];
  1309. return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
  1310. RParenOrBraceLoc);
  1311. }
  1312. // For an expression of the form T(), T shall not be an array type.
  1313. QualType ElemTy = Ty;
  1314. if (Ty->isArrayType()) {
  1315. if (!ListInitialization)
  1316. return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
  1317. << FullRange);
  1318. ElemTy = Context.getBaseElementType(Ty);
  1319. }
  1320. // Only construct objects with object types.
  1321. // The standard doesn't explicitly forbid function types here, but that's an
  1322. // obvious oversight, as there's no way to dynamically construct a function
  1323. // in general.
  1324. if (Ty->isFunctionType())
  1325. return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
  1326. << Ty << FullRange);
  1327. // C++17 [expr.type.conv]p2:
  1328. // If the type is cv void and the initializer is (), the expression is a
  1329. // prvalue of the specified type that performs no initialization.
  1330. if (!Ty->isVoidType() &&
  1331. RequireCompleteType(TyBeginLoc, ElemTy,
  1332. diag::err_invalid_incomplete_type_use, FullRange))
  1333. return ExprError();
  1334. // Otherwise, the expression is a prvalue of the specified type whose
  1335. // result object is direct-initialized (11.6) with the initializer.
  1336. InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
  1337. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
  1338. if (Result.isInvalid())
  1339. return Result;
  1340. Expr *Inner = Result.get();
  1341. if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
  1342. Inner = BTE->getSubExpr();
  1343. if (!isa<CXXTemporaryObjectExpr>(Inner) &&
  1344. !isa<CXXScalarValueInitExpr>(Inner)) {
  1345. // If we created a CXXTemporaryObjectExpr, that node also represents the
  1346. // functional cast. Otherwise, create an explicit cast to represent
  1347. // the syntactic form of a functional-style cast that was used here.
  1348. //
  1349. // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
  1350. // would give a more consistent AST representation than using a
  1351. // CXXTemporaryObjectExpr. It's also weird that the functional cast
  1352. // is sometimes handled by initialization and sometimes not.
  1353. QualType ResultType = Result.get()->getType();
  1354. SourceRange Locs = ListInitialization
  1355. ? SourceRange()
  1356. : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
  1357. Result = CXXFunctionalCastExpr::Create(
  1358. Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
  1359. Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
  1360. Locs.getBegin(), Locs.getEnd());
  1361. }
  1362. return Result;
  1363. }
  1364. bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
  1365. // [CUDA] Ignore this function, if we can't call it.
  1366. const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
  1367. if (getLangOpts().CUDA) {
  1368. auto CallPreference = IdentifyCUDAPreference(Caller, Method);
  1369. // If it's not callable at all, it's not the right function.
  1370. if (CallPreference < CFP_WrongSide)
  1371. return false;
  1372. if (CallPreference == CFP_WrongSide) {
  1373. // Maybe. We have to check if there are better alternatives.
  1374. DeclContext::lookup_result R =
  1375. Method->getDeclContext()->lookup(Method->getDeclName());
  1376. for (const auto *D : R) {
  1377. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  1378. if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide)
  1379. return false;
  1380. }
  1381. }
  1382. // We've found no better variants.
  1383. }
  1384. }
  1385. SmallVector<const FunctionDecl*, 4> PreventedBy;
  1386. bool Result = Method->isUsualDeallocationFunction(PreventedBy);
  1387. if (Result || !getLangOpts().CUDA || PreventedBy.empty())
  1388. return Result;
  1389. // In case of CUDA, return true if none of the 1-argument deallocator
  1390. // functions are actually callable.
  1391. return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
  1392. assert(FD->getNumParams() == 1 &&
  1393. "Only single-operand functions should be in PreventedBy");
  1394. return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
  1395. });
  1396. }
  1397. /// Determine whether the given function is a non-placement
  1398. /// deallocation function.
  1399. static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
  1400. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
  1401. return S.isUsualDeallocationFunction(Method);
  1402. if (FD->getOverloadedOperator() != OO_Delete &&
  1403. FD->getOverloadedOperator() != OO_Array_Delete)
  1404. return false;
  1405. unsigned UsualParams = 1;
  1406. if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
  1407. S.Context.hasSameUnqualifiedType(
  1408. FD->getParamDecl(UsualParams)->getType(),
  1409. S.Context.getSizeType()))
  1410. ++UsualParams;
  1411. if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
  1412. S.Context.hasSameUnqualifiedType(
  1413. FD->getParamDecl(UsualParams)->getType(),
  1414. S.Context.getTypeDeclType(S.getStdAlignValT())))
  1415. ++UsualParams;
  1416. return UsualParams == FD->getNumParams();
  1417. }
  1418. namespace {
  1419. struct UsualDeallocFnInfo {
  1420. UsualDeallocFnInfo() : Found(), FD(nullptr) {}
  1421. UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
  1422. : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
  1423. Destroying(false), HasSizeT(false), HasAlignValT(false),
  1424. CUDAPref(Sema::CFP_Native) {
  1425. // A function template declaration is never a usual deallocation function.
  1426. if (!FD)
  1427. return;
  1428. unsigned NumBaseParams = 1;
  1429. if (FD->isDestroyingOperatorDelete()) {
  1430. Destroying = true;
  1431. ++NumBaseParams;
  1432. }
  1433. if (NumBaseParams < FD->getNumParams() &&
  1434. S.Context.hasSameUnqualifiedType(
  1435. FD->getParamDecl(NumBaseParams)->getType(),
  1436. S.Context.getSizeType())) {
  1437. ++NumBaseParams;
  1438. HasSizeT = true;
  1439. }
  1440. if (NumBaseParams < FD->getNumParams() &&
  1441. FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
  1442. ++NumBaseParams;
  1443. HasAlignValT = true;
  1444. }
  1445. // In CUDA, determine how much we'd like / dislike to call this.
  1446. if (S.getLangOpts().CUDA)
  1447. if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  1448. CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
  1449. }
  1450. explicit operator bool() const { return FD; }
  1451. bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
  1452. bool WantAlign) const {
  1453. // C++ P0722:
  1454. // A destroying operator delete is preferred over a non-destroying
  1455. // operator delete.
  1456. if (Destroying != Other.Destroying)
  1457. return Destroying;
  1458. // C++17 [expr.delete]p10:
  1459. // If the type has new-extended alignment, a function with a parameter
  1460. // of type std::align_val_t is preferred; otherwise a function without
  1461. // such a parameter is preferred
  1462. if (HasAlignValT != Other.HasAlignValT)
  1463. return HasAlignValT == WantAlign;
  1464. if (HasSizeT != Other.HasSizeT)
  1465. return HasSizeT == WantSize;
  1466. // Use CUDA call preference as a tiebreaker.
  1467. return CUDAPref > Other.CUDAPref;
  1468. }
  1469. DeclAccessPair Found;
  1470. FunctionDecl *FD;
  1471. bool Destroying, HasSizeT, HasAlignValT;
  1472. Sema::CUDAFunctionPreference CUDAPref;
  1473. };
  1474. }
  1475. /// Determine whether a type has new-extended alignment. This may be called when
  1476. /// the type is incomplete (for a delete-expression with an incomplete pointee
  1477. /// type), in which case it will conservatively return false if the alignment is
  1478. /// not known.
  1479. static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
  1480. return S.getLangOpts().AlignedAllocation &&
  1481. S.getASTContext().getTypeAlignIfKnown(AllocType) >
  1482. S.getASTContext().getTargetInfo().getNewAlign();
  1483. }
  1484. /// Select the correct "usual" deallocation function to use from a selection of
  1485. /// deallocation functions (either global or class-scope).
  1486. static UsualDeallocFnInfo resolveDeallocationOverload(
  1487. Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
  1488. llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
  1489. UsualDeallocFnInfo Best;
  1490. for (auto I = R.begin(), E = R.end(); I != E; ++I) {
  1491. UsualDeallocFnInfo Info(S, I.getPair());
  1492. if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
  1493. Info.CUDAPref == Sema::CFP_Never)
  1494. continue;
  1495. if (!Best) {
  1496. Best = Info;
  1497. if (BestFns)
  1498. BestFns->push_back(Info);
  1499. continue;
  1500. }
  1501. if (Best.isBetterThan(Info, WantSize, WantAlign))
  1502. continue;
  1503. // If more than one preferred function is found, all non-preferred
  1504. // functions are eliminated from further consideration.
  1505. if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
  1506. BestFns->clear();
  1507. Best = Info;
  1508. if (BestFns)
  1509. BestFns->push_back(Info);
  1510. }
  1511. return Best;
  1512. }
  1513. /// Determine whether a given type is a class for which 'delete[]' would call
  1514. /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
  1515. /// we need to store the array size (even if the type is
  1516. /// trivially-destructible).
  1517. static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
  1518. QualType allocType) {
  1519. const RecordType *record =
  1520. allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
  1521. if (!record) return false;
  1522. // Try to find an operator delete[] in class scope.
  1523. DeclarationName deleteName =
  1524. S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
  1525. LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
  1526. S.LookupQualifiedName(ops, record->getDecl());
  1527. // We're just doing this for information.
  1528. ops.suppressDiagnostics();
  1529. // Very likely: there's no operator delete[].
  1530. if (ops.empty()) return false;
  1531. // If it's ambiguous, it should be illegal to call operator delete[]
  1532. // on this thing, so it doesn't matter if we allocate extra space or not.
  1533. if (ops.isAmbiguous()) return false;
  1534. // C++17 [expr.delete]p10:
  1535. // If the deallocation functions have class scope, the one without a
  1536. // parameter of type std::size_t is selected.
  1537. auto Best = resolveDeallocationOverload(
  1538. S, ops, /*WantSize*/false,
  1539. /*WantAlign*/hasNewExtendedAlignment(S, allocType));
  1540. return Best && Best.HasSizeT;
  1541. }
  1542. /// Parsed a C++ 'new' expression (C++ 5.3.4).
  1543. ///
  1544. /// E.g.:
  1545. /// @code new (memory) int[size][4] @endcode
  1546. /// or
  1547. /// @code ::new Foo(23, "hello") @endcode
  1548. ///
  1549. /// \param StartLoc The first location of the expression.
  1550. /// \param UseGlobal True if 'new' was prefixed with '::'.
  1551. /// \param PlacementLParen Opening paren of the placement arguments.
  1552. /// \param PlacementArgs Placement new arguments.
  1553. /// \param PlacementRParen Closing paren of the placement arguments.
  1554. /// \param TypeIdParens If the type is in parens, the source range.
  1555. /// \param D The type to be allocated, as well as array dimensions.
  1556. /// \param Initializer The initializing expression or initializer-list, or null
  1557. /// if there is none.
  1558. ExprResult
  1559. Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
  1560. SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
  1561. SourceLocation PlacementRParen, SourceRange TypeIdParens,
  1562. Declarator &D, Expr *Initializer) {
  1563. Optional<Expr *> ArraySize;
  1564. // If the specified type is an array, unwrap it and save the expression.
  1565. if (D.getNumTypeObjects() > 0 &&
  1566. D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
  1567. DeclaratorChunk &Chunk = D.getTypeObject(0);
  1568. if (D.getDeclSpec().hasAutoTypeSpec())
  1569. return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
  1570. << D.getSourceRange());
  1571. if (Chunk.Arr.hasStatic)
  1572. return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
  1573. << D.getSourceRange());
  1574. if (!Chunk.Arr.NumElts && !Initializer)
  1575. return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
  1576. << D.getSourceRange());
  1577. ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
  1578. D.DropFirstTypeObject();
  1579. }
  1580. // Every dimension shall be of constant size.
  1581. if (ArraySize) {
  1582. for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
  1583. if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
  1584. break;
  1585. DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
  1586. if (Expr *NumElts = (Expr *)Array.NumElts) {
  1587. if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
  1588. // FIXME: GCC permits constant folding here. We should either do so consistently
  1589. // or not do so at all, rather than changing behavior in C++14 onwards.
  1590. if (getLangOpts().CPlusPlus14) {
  1591. // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
  1592. // shall be a converted constant expression (5.19) of type std::size_t
  1593. // and shall evaluate to a strictly positive value.
  1594. llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
  1595. Array.NumElts
  1596. = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
  1597. CCEK_ArrayBound)
  1598. .get();
  1599. } else {
  1600. Array.NumElts =
  1601. VerifyIntegerConstantExpression(
  1602. NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
  1603. .get();
  1604. }
  1605. if (!Array.NumElts)
  1606. return ExprError();
  1607. }
  1608. }
  1609. }
  1610. }
  1611. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
  1612. QualType AllocType = TInfo->getType();
  1613. if (D.isInvalidType())
  1614. return ExprError();
  1615. SourceRange DirectInitRange;
  1616. if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
  1617. DirectInitRange = List->getSourceRange();
  1618. return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
  1619. PlacementLParen, PlacementArgs, PlacementRParen,
  1620. TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
  1621. Initializer);
  1622. }
  1623. static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
  1624. Expr *Init) {
  1625. if (!Init)
  1626. return true;
  1627. if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
  1628. return PLE->getNumExprs() == 0;
  1629. if (isa<ImplicitValueInitExpr>(Init))
  1630. return true;
  1631. else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
  1632. return !CCE->isListInitialization() &&
  1633. CCE->getConstructor()->isDefaultConstructor();
  1634. else if (Style == CXXNewExpr::ListInit) {
  1635. assert(isa<InitListExpr>(Init) &&
  1636. "Shouldn't create list CXXConstructExprs for arrays.");
  1637. return true;
  1638. }
  1639. return false;
  1640. }
  1641. bool
  1642. Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
  1643. if (!getLangOpts().AlignedAllocationUnavailable)
  1644. return false;
  1645. if (FD.isDefined())
  1646. return false;
  1647. Optional<unsigned> AlignmentParam;
  1648. if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
  1649. AlignmentParam.hasValue())
  1650. return true;
  1651. return false;
  1652. }
  1653. // Emit a diagnostic if an aligned allocation/deallocation function that is not
  1654. // implemented in the standard library is selected.
  1655. void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
  1656. SourceLocation Loc) {
  1657. if (isUnavailableAlignedAllocationFunction(FD)) {
  1658. const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
  1659. StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
  1660. getASTContext().getTargetInfo().getPlatformName());
  1661. VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
  1662. OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
  1663. bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
  1664. Diag(Loc, diag::err_aligned_allocation_unavailable)
  1665. << IsDelete << FD.getType().getAsString() << OSName
  1666. << OSVersion.getAsString() << OSVersion.empty();
  1667. Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
  1668. }
  1669. }
  1670. ExprResult
  1671. Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
  1672. SourceLocation PlacementLParen,
  1673. MultiExprArg PlacementArgs,
  1674. SourceLocation PlacementRParen,
  1675. SourceRange TypeIdParens,
  1676. QualType AllocType,
  1677. TypeSourceInfo *AllocTypeInfo,
  1678. Optional<Expr *> ArraySize,
  1679. SourceRange DirectInitRange,
  1680. Expr *Initializer) {
  1681. SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
  1682. SourceLocation StartLoc = Range.getBegin();
  1683. CXXNewExpr::InitializationStyle initStyle;
  1684. if (DirectInitRange.isValid()) {
  1685. assert(Initializer && "Have parens but no initializer.");
  1686. initStyle = CXXNewExpr::CallInit;
  1687. } else if (Initializer && isa<InitListExpr>(Initializer))
  1688. initStyle = CXXNewExpr::ListInit;
  1689. else {
  1690. assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
  1691. isa<CXXConstructExpr>(Initializer)) &&
  1692. "Initializer expression that cannot have been implicitly created.");
  1693. initStyle = CXXNewExpr::NoInit;
  1694. }
  1695. Expr **Inits = &Initializer;
  1696. unsigned NumInits = Initializer ? 1 : 0;
  1697. if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
  1698. assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
  1699. Inits = List->getExprs();
  1700. NumInits = List->getNumExprs();
  1701. }
  1702. // C++11 [expr.new]p15:
  1703. // A new-expression that creates an object of type T initializes that
  1704. // object as follows:
  1705. InitializationKind Kind
  1706. // - If the new-initializer is omitted, the object is default-
  1707. // initialized (8.5); if no initialization is performed,
  1708. // the object has indeterminate value
  1709. = initStyle == CXXNewExpr::NoInit
  1710. ? InitializationKind::CreateDefault(TypeRange.getBegin())
  1711. // - Otherwise, the new-initializer is interpreted according to
  1712. // the
  1713. // initialization rules of 8.5 for direct-initialization.
  1714. : initStyle == CXXNewExpr::ListInit
  1715. ? InitializationKind::CreateDirectList(
  1716. TypeRange.getBegin(), Initializer->getBeginLoc(),
  1717. Initializer->getEndLoc())
  1718. : InitializationKind::CreateDirect(TypeRange.getBegin(),
  1719. DirectInitRange.getBegin(),
  1720. DirectInitRange.getEnd());
  1721. // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  1722. auto *Deduced = AllocType->getContainedDeducedType();
  1723. if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
  1724. if (ArraySize)
  1725. return ExprError(
  1726. Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
  1727. diag::err_deduced_class_template_compound_type)
  1728. << /*array*/ 2
  1729. << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
  1730. InitializedEntity Entity
  1731. = InitializedEntity::InitializeNew(StartLoc, AllocType);
  1732. AllocType = DeduceTemplateSpecializationFromInitializer(
  1733. AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
  1734. if (AllocType.isNull())
  1735. return ExprError();
  1736. } else if (Deduced) {
  1737. bool Braced = (initStyle == CXXNewExpr::ListInit);
  1738. if (NumInits == 1) {
  1739. if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
  1740. Inits = p->getInits();
  1741. NumInits = p->getNumInits();
  1742. Braced = true;
  1743. }
  1744. }
  1745. if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
  1746. return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
  1747. << AllocType << TypeRange);
  1748. if (NumInits > 1) {
  1749. Expr *FirstBad = Inits[1];
  1750. return ExprError(Diag(FirstBad->getBeginLoc(),
  1751. diag::err_auto_new_ctor_multiple_expressions)
  1752. << AllocType << TypeRange);
  1753. }
  1754. if (Braced && !getLangOpts().CPlusPlus17)
  1755. Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
  1756. << AllocType << TypeRange;
  1757. Expr *Deduce = Inits[0];
  1758. QualType DeducedType;
  1759. if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
  1760. return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
  1761. << AllocType << Deduce->getType()
  1762. << TypeRange << Deduce->getSourceRange());
  1763. if (DeducedType.isNull())
  1764. return ExprError();
  1765. AllocType = DeducedType;
  1766. }
  1767. // Per C++0x [expr.new]p5, the type being constructed may be a
  1768. // typedef of an array type.
  1769. if (!ArraySize) {
  1770. if (const ConstantArrayType *Array
  1771. = Context.getAsConstantArrayType(AllocType)) {
  1772. ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
  1773. Context.getSizeType(),
  1774. TypeRange.getEnd());
  1775. AllocType = Array->getElementType();
  1776. }
  1777. }
  1778. if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
  1779. return ExprError();
  1780. // In ARC, infer 'retaining' for the allocated
  1781. if (getLangOpts().ObjCAutoRefCount &&
  1782. AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
  1783. AllocType->isObjCLifetimeType()) {
  1784. AllocType = Context.getLifetimeQualifiedType(AllocType,
  1785. AllocType->getObjCARCImplicitLifetime());
  1786. }
  1787. QualType ResultType = Context.getPointerType(AllocType);
  1788. if (ArraySize && *ArraySize &&
  1789. (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
  1790. ExprResult result = CheckPlaceholderExpr(*ArraySize);
  1791. if (result.isInvalid()) return ExprError();
  1792. ArraySize = result.get();
  1793. }
  1794. // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
  1795. // integral or enumeration type with a non-negative value."
  1796. // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
  1797. // enumeration type, or a class type for which a single non-explicit
  1798. // conversion function to integral or unscoped enumeration type exists.
  1799. // C++1y [expr.new]p6: The expression [...] is implicitly converted to
  1800. // std::size_t.
  1801. llvm::Optional<uint64_t> KnownArraySize;
  1802. if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
  1803. ExprResult ConvertedSize;
  1804. if (getLangOpts().CPlusPlus14) {
  1805. assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
  1806. ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
  1807. AA_Converting);
  1808. if (!ConvertedSize.isInvalid() &&
  1809. (*ArraySize)->getType()->getAs<RecordType>())
  1810. // Diagnose the compatibility of this conversion.
  1811. Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
  1812. << (*ArraySize)->getType() << 0 << "'size_t'";
  1813. } else {
  1814. class SizeConvertDiagnoser : public ICEConvertDiagnoser {
  1815. protected:
  1816. Expr *ArraySize;
  1817. public:
  1818. SizeConvertDiagnoser(Expr *ArraySize)
  1819. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
  1820. ArraySize(ArraySize) {}
  1821. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  1822. QualType T) override {
  1823. return S.Diag(Loc, diag::err_array_size_not_integral)
  1824. << S.getLangOpts().CPlusPlus11 << T;
  1825. }
  1826. SemaDiagnosticBuilder diagnoseIncomplete(
  1827. Sema &S, SourceLocation Loc, QualType T) override {
  1828. return S.Diag(Loc, diag::err_array_size_incomplete_type)
  1829. << T << ArraySize->getSourceRange();
  1830. }
  1831. SemaDiagnosticBuilder diagnoseExplicitConv(
  1832. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  1833. return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
  1834. }
  1835. SemaDiagnosticBuilder noteExplicitConv(
  1836. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  1837. return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
  1838. << ConvTy->isEnumeralType() << ConvTy;
  1839. }
  1840. SemaDiagnosticBuilder diagnoseAmbiguous(
  1841. Sema &S, SourceLocation Loc, QualType T) override {
  1842. return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
  1843. }
  1844. SemaDiagnosticBuilder noteAmbiguous(
  1845. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  1846. return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
  1847. << ConvTy->isEnumeralType() << ConvTy;
  1848. }
  1849. SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
  1850. QualType T,
  1851. QualType ConvTy) override {
  1852. return S.Diag(Loc,
  1853. S.getLangOpts().CPlusPlus11
  1854. ? diag::warn_cxx98_compat_array_size_conversion
  1855. : diag::ext_array_size_conversion)
  1856. << T << ConvTy->isEnumeralType() << ConvTy;
  1857. }
  1858. } SizeDiagnoser(*ArraySize);
  1859. ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
  1860. SizeDiagnoser);
  1861. }
  1862. if (ConvertedSize.isInvalid())
  1863. return ExprError();
  1864. ArraySize = ConvertedSize.get();
  1865. QualType SizeType = (*ArraySize)->getType();
  1866. if (!SizeType->isIntegralOrUnscopedEnumerationType())
  1867. return ExprError();
  1868. // C++98 [expr.new]p7:
  1869. // The expression in a direct-new-declarator shall have integral type
  1870. // with a non-negative value.
  1871. //
  1872. // Let's see if this is a constant < 0. If so, we reject it out of hand,
  1873. // per CWG1464. Otherwise, if it's not a constant, we must have an
  1874. // unparenthesized array type.
  1875. // We've already performed any required implicit conversion to integer or
  1876. // unscoped enumeration type.
  1877. // FIXME: Per CWG1464, we are required to check the value prior to
  1878. // converting to size_t. This will never find a negative array size in
  1879. // C++14 onwards, because Value is always unsigned here!
  1880. if (Optional<llvm::APSInt> Value =
  1881. (*ArraySize)->getIntegerConstantExpr(Context)) {
  1882. if (Value->isSigned() && Value->isNegative()) {
  1883. return ExprError(Diag((*ArraySize)->getBeginLoc(),
  1884. diag::err_typecheck_negative_array_size)
  1885. << (*ArraySize)->getSourceRange());
  1886. }
  1887. if (!AllocType->isDependentType()) {
  1888. unsigned ActiveSizeBits =
  1889. ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);
  1890. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
  1891. return ExprError(
  1892. Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
  1893. << toString(*Value, 10) << (*ArraySize)->getSourceRange());
  1894. }
  1895. KnownArraySize = Value->getZExtValue();
  1896. } else if (TypeIdParens.isValid()) {
  1897. // Can't have dynamic array size when the type-id is in parentheses.
  1898. Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
  1899. << (*ArraySize)->getSourceRange()
  1900. << FixItHint::CreateRemoval(TypeIdParens.getBegin())
  1901. << FixItHint::CreateRemoval(TypeIdParens.getEnd());
  1902. TypeIdParens = SourceRange();
  1903. }
  1904. // Note that we do *not* convert the argument in any way. It can
  1905. // be signed, larger than size_t, whatever.
  1906. }
  1907. FunctionDecl *OperatorNew = nullptr;
  1908. FunctionDecl *OperatorDelete = nullptr;
  1909. unsigned Alignment =
  1910. AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
  1911. unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
  1912. bool PassAlignment = getLangOpts().AlignedAllocation &&
  1913. Alignment > NewAlignment;
  1914. AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
  1915. if (!AllocType->isDependentType() &&
  1916. !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
  1917. FindAllocationFunctions(
  1918. StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
  1919. AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
  1920. OperatorNew, OperatorDelete))
  1921. return ExprError();
  1922. // If this is an array allocation, compute whether the usual array
  1923. // deallocation function for the type has a size_t parameter.
  1924. bool UsualArrayDeleteWantsSize = false;
  1925. if (ArraySize && !AllocType->isDependentType())
  1926. UsualArrayDeleteWantsSize =
  1927. doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
  1928. SmallVector<Expr *, 8> AllPlaceArgs;
  1929. if (OperatorNew) {
  1930. auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
  1931. VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
  1932. : VariadicDoesNotApply;
  1933. // We've already converted the placement args, just fill in any default
  1934. // arguments. Skip the first parameter because we don't have a corresponding
  1935. // argument. Skip the second parameter too if we're passing in the
  1936. // alignment; we've already filled it in.
  1937. unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
  1938. if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
  1939. NumImplicitArgs, PlacementArgs, AllPlaceArgs,
  1940. CallType))
  1941. return ExprError();
  1942. if (!AllPlaceArgs.empty())
  1943. PlacementArgs = AllPlaceArgs;
  1944. // We would like to perform some checking on the given `operator new` call,
  1945. // but the PlacementArgs does not contain the implicit arguments,
  1946. // namely allocation size and maybe allocation alignment,
  1947. // so we need to conjure them.
  1948. QualType SizeTy = Context.getSizeType();
  1949. unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
  1950. llvm::APInt SingleEltSize(
  1951. SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
  1952. // How many bytes do we want to allocate here?
  1953. llvm::Optional<llvm::APInt> AllocationSize;
  1954. if (!ArraySize.hasValue() && !AllocType->isDependentType()) {
  1955. // For non-array operator new, we only want to allocate one element.
  1956. AllocationSize = SingleEltSize;
  1957. } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) {
  1958. // For array operator new, only deal with static array size case.
  1959. bool Overflow;
  1960. AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
  1961. .umul_ov(SingleEltSize, Overflow);
  1962. (void)Overflow;
  1963. assert(
  1964. !Overflow &&
  1965. "Expected that all the overflows would have been handled already.");
  1966. }
  1967. IntegerLiteral AllocationSizeLiteral(
  1968. Context, AllocationSize.getValueOr(llvm::APInt::getZero(SizeTyWidth)),
  1969. SizeTy, SourceLocation());
  1970. // Otherwise, if we failed to constant-fold the allocation size, we'll
  1971. // just give up and pass-in something opaque, that isn't a null pointer.
  1972. OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
  1973. OK_Ordinary, /*SourceExpr=*/nullptr);
  1974. // Let's synthesize the alignment argument in case we will need it.
  1975. // Since we *really* want to allocate these on stack, this is slightly ugly
  1976. // because there might not be a `std::align_val_t` type.
  1977. EnumDecl *StdAlignValT = getStdAlignValT();
  1978. QualType AlignValT =
  1979. StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;
  1980. IntegerLiteral AlignmentLiteral(
  1981. Context,
  1982. llvm::APInt(Context.getTypeSize(SizeTy),
  1983. Alignment / Context.getCharWidth()),
  1984. SizeTy, SourceLocation());
  1985. ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
  1986. CK_IntegralCast, &AlignmentLiteral,
  1987. VK_PRValue, FPOptionsOverride());
  1988. // Adjust placement args by prepending conjured size and alignment exprs.
  1989. llvm::SmallVector<Expr *, 8> CallArgs;
  1990. CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
  1991. CallArgs.emplace_back(AllocationSize.hasValue()
  1992. ? static_cast<Expr *>(&AllocationSizeLiteral)
  1993. : &OpaqueAllocationSize);
  1994. if (PassAlignment)
  1995. CallArgs.emplace_back(&DesiredAlignment);
  1996. CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
  1997. DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
  1998. checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
  1999. /*IsMemberFunction=*/false, StartLoc, Range, CallType);
  2000. // Warn if the type is over-aligned and is being allocated by (unaligned)
  2001. // global operator new.
  2002. if (PlacementArgs.empty() && !PassAlignment &&
  2003. (OperatorNew->isImplicit() ||
  2004. (OperatorNew->getBeginLoc().isValid() &&
  2005. getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
  2006. if (Alignment > NewAlignment)
  2007. Diag(StartLoc, diag::warn_overaligned_type)
  2008. << AllocType
  2009. << unsigned(Alignment / Context.getCharWidth())
  2010. << unsigned(NewAlignment / Context.getCharWidth());
  2011. }
  2012. }
  2013. // Array 'new' can't have any initializers except empty parentheses.
  2014. // Initializer lists are also allowed, in C++11. Rely on the parser for the
  2015. // dialect distinction.
  2016. if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
  2017. SourceRange InitRange(Inits[0]->getBeginLoc(),
  2018. Inits[NumInits - 1]->getEndLoc());
  2019. Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
  2020. return ExprError();
  2021. }
  2022. // If we can perform the initialization, and we've not already done so,
  2023. // do it now.
  2024. if (!AllocType->isDependentType() &&
  2025. !Expr::hasAnyTypeDependentArguments(
  2026. llvm::makeArrayRef(Inits, NumInits))) {
  2027. // The type we initialize is the complete type, including the array bound.
  2028. QualType InitType;
  2029. if (KnownArraySize)
  2030. InitType = Context.getConstantArrayType(
  2031. AllocType,
  2032. llvm::APInt(Context.getTypeSize(Context.getSizeType()),
  2033. *KnownArraySize),
  2034. *ArraySize, ArrayType::Normal, 0);
  2035. else if (ArraySize)
  2036. InitType =
  2037. Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
  2038. else
  2039. InitType = AllocType;
  2040. InitializedEntity Entity
  2041. = InitializedEntity::InitializeNew(StartLoc, InitType);
  2042. InitializationSequence InitSeq(*this, Entity, Kind,
  2043. MultiExprArg(Inits, NumInits));
  2044. ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
  2045. MultiExprArg(Inits, NumInits));
  2046. if (FullInit.isInvalid())
  2047. return ExprError();
  2048. // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
  2049. // we don't want the initialized object to be destructed.
  2050. // FIXME: We should not create these in the first place.
  2051. if (CXXBindTemporaryExpr *Binder =
  2052. dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
  2053. FullInit = Binder->getSubExpr();
  2054. Initializer = FullInit.get();
  2055. // FIXME: If we have a KnownArraySize, check that the array bound of the
  2056. // initializer is no greater than that constant value.
  2057. if (ArraySize && !*ArraySize) {
  2058. auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
  2059. if (CAT) {
  2060. // FIXME: Track that the array size was inferred rather than explicitly
  2061. // specified.
  2062. ArraySize = IntegerLiteral::Create(
  2063. Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
  2064. } else {
  2065. Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
  2066. << Initializer->getSourceRange();
  2067. }
  2068. }
  2069. }
  2070. // Mark the new and delete operators as referenced.
  2071. if (OperatorNew) {
  2072. if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
  2073. return ExprError();
  2074. MarkFunctionReferenced(StartLoc, OperatorNew);
  2075. }
  2076. if (OperatorDelete) {
  2077. if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
  2078. return ExprError();
  2079. MarkFunctionReferenced(StartLoc, OperatorDelete);
  2080. }
  2081. return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
  2082. PassAlignment, UsualArrayDeleteWantsSize,
  2083. PlacementArgs, TypeIdParens, ArraySize, initStyle,
  2084. Initializer, ResultType, AllocTypeInfo, Range,
  2085. DirectInitRange);
  2086. }
  2087. /// Checks that a type is suitable as the allocated type
  2088. /// in a new-expression.
  2089. bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
  2090. SourceRange R) {
  2091. // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
  2092. // abstract class type or array thereof.
  2093. if (AllocType->isFunctionType())
  2094. return Diag(Loc, diag::err_bad_new_type)
  2095. << AllocType << 0 << R;
  2096. else if (AllocType->isReferenceType())
  2097. return Diag(Loc, diag::err_bad_new_type)
  2098. << AllocType << 1 << R;
  2099. else if (!AllocType->isDependentType() &&
  2100. RequireCompleteSizedType(
  2101. Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
  2102. return true;
  2103. else if (RequireNonAbstractType(Loc, AllocType,
  2104. diag::err_allocation_of_abstract_type))
  2105. return true;
  2106. else if (AllocType->isVariablyModifiedType())
  2107. return Diag(Loc, diag::err_variably_modified_new_type)
  2108. << AllocType;
  2109. else if (AllocType.getAddressSpace() != LangAS::Default &&
  2110. !getLangOpts().OpenCLCPlusPlus)
  2111. return Diag(Loc, diag::err_address_space_qualified_new)
  2112. << AllocType.getUnqualifiedType()
  2113. << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
  2114. else if (getLangOpts().ObjCAutoRefCount) {
  2115. if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
  2116. QualType BaseAllocType = Context.getBaseElementType(AT);
  2117. if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
  2118. BaseAllocType->isObjCLifetimeType())
  2119. return Diag(Loc, diag::err_arc_new_array_without_ownership)
  2120. << BaseAllocType;
  2121. }
  2122. }
  2123. return false;
  2124. }
  2125. static bool resolveAllocationOverload(
  2126. Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
  2127. bool &PassAlignment, FunctionDecl *&Operator,
  2128. OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
  2129. OverloadCandidateSet Candidates(R.getNameLoc(),
  2130. OverloadCandidateSet::CSK_Normal);
  2131. for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
  2132. Alloc != AllocEnd; ++Alloc) {
  2133. // Even member operator new/delete are implicitly treated as
  2134. // static, so don't use AddMemberCandidate.
  2135. NamedDecl *D = (*Alloc)->getUnderlyingDecl();
  2136. if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
  2137. S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
  2138. /*ExplicitTemplateArgs=*/nullptr, Args,
  2139. Candidates,
  2140. /*SuppressUserConversions=*/false);
  2141. continue;
  2142. }
  2143. FunctionDecl *Fn = cast<FunctionDecl>(D);
  2144. S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
  2145. /*SuppressUserConversions=*/false);
  2146. }
  2147. // Do the resolution.
  2148. OverloadCandidateSet::iterator Best;
  2149. switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
  2150. case OR_Success: {
  2151. // Got one!
  2152. FunctionDecl *FnDecl = Best->Function;
  2153. if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
  2154. Best->FoundDecl) == Sema::AR_inaccessible)
  2155. return true;
  2156. Operator = FnDecl;
  2157. return false;
  2158. }
  2159. case OR_No_Viable_Function:
  2160. // C++17 [expr.new]p13:
  2161. // If no matching function is found and the allocated object type has
  2162. // new-extended alignment, the alignment argument is removed from the
  2163. // argument list, and overload resolution is performed again.
  2164. if (PassAlignment) {
  2165. PassAlignment = false;
  2166. AlignArg = Args[1];
  2167. Args.erase(Args.begin() + 1);
  2168. return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
  2169. Operator, &Candidates, AlignArg,
  2170. Diagnose);
  2171. }
  2172. // MSVC will fall back on trying to find a matching global operator new
  2173. // if operator new[] cannot be found. Also, MSVC will leak by not
  2174. // generating a call to operator delete or operator delete[], but we
  2175. // will not replicate that bug.
  2176. // FIXME: Find out how this interacts with the std::align_val_t fallback
  2177. // once MSVC implements it.
  2178. if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
  2179. S.Context.getLangOpts().MSVCCompat) {
  2180. R.clear();
  2181. R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
  2182. S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
  2183. // FIXME: This will give bad diagnostics pointing at the wrong functions.
  2184. return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
  2185. Operator, /*Candidates=*/nullptr,
  2186. /*AlignArg=*/nullptr, Diagnose);
  2187. }
  2188. if (Diagnose) {
  2189. // If this is an allocation of the form 'new (p) X' for some object
  2190. // pointer p (or an expression that will decay to such a pointer),
  2191. // diagnose the missing inclusion of <new>.
  2192. if (!R.isClassLookup() && Args.size() == 2 &&
  2193. (Args[1]->getType()->isObjectPointerType() ||
  2194. Args[1]->getType()->isArrayType())) {
  2195. S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
  2196. << R.getLookupName() << Range;
  2197. // Listing the candidates is unlikely to be useful; skip it.
  2198. return true;
  2199. }
  2200. // Finish checking all candidates before we note any. This checking can
  2201. // produce additional diagnostics so can't be interleaved with our
  2202. // emission of notes.
  2203. //
  2204. // For an aligned allocation, separately check the aligned and unaligned
  2205. // candidates with their respective argument lists.
  2206. SmallVector<OverloadCandidate*, 32> Cands;
  2207. SmallVector<OverloadCandidate*, 32> AlignedCands;
  2208. llvm::SmallVector<Expr*, 4> AlignedArgs;
  2209. if (AlignedCandidates) {
  2210. auto IsAligned = [](OverloadCandidate &C) {
  2211. return C.Function->getNumParams() > 1 &&
  2212. C.Function->getParamDecl(1)->getType()->isAlignValT();
  2213. };
  2214. auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
  2215. AlignedArgs.reserve(Args.size() + 1);
  2216. AlignedArgs.push_back(Args[0]);
  2217. AlignedArgs.push_back(AlignArg);
  2218. AlignedArgs.append(Args.begin() + 1, Args.end());
  2219. AlignedCands = AlignedCandidates->CompleteCandidates(
  2220. S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
  2221. Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
  2222. R.getNameLoc(), IsUnaligned);
  2223. } else {
  2224. Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
  2225. R.getNameLoc());
  2226. }
  2227. S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
  2228. << R.getLookupName() << Range;
  2229. if (AlignedCandidates)
  2230. AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
  2231. R.getNameLoc());
  2232. Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
  2233. }
  2234. return true;
  2235. case OR_Ambiguous:
  2236. if (Diagnose) {
  2237. Candidates.NoteCandidates(
  2238. PartialDiagnosticAt(R.getNameLoc(),
  2239. S.PDiag(diag::err_ovl_ambiguous_call)
  2240. << R.getLookupName() << Range),
  2241. S, OCD_AmbiguousCandidates, Args);
  2242. }
  2243. return true;
  2244. case OR_Deleted: {
  2245. if (Diagnose) {
  2246. Candidates.NoteCandidates(
  2247. PartialDiagnosticAt(R.getNameLoc(),
  2248. S.PDiag(diag::err_ovl_deleted_call)
  2249. << R.getLookupName() << Range),
  2250. S, OCD_AllCandidates, Args);
  2251. }
  2252. return true;
  2253. }
  2254. }
  2255. llvm_unreachable("Unreachable, bad result from BestViableFunction");
  2256. }
  2257. bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
  2258. AllocationFunctionScope NewScope,
  2259. AllocationFunctionScope DeleteScope,
  2260. QualType AllocType, bool IsArray,
  2261. bool &PassAlignment, MultiExprArg PlaceArgs,
  2262. FunctionDecl *&OperatorNew,
  2263. FunctionDecl *&OperatorDelete,
  2264. bool Diagnose) {
  2265. // --- Choosing an allocation function ---
  2266. // C++ 5.3.4p8 - 14 & 18
  2267. // 1) If looking in AFS_Global scope for allocation functions, only look in
  2268. // the global scope. Else, if AFS_Class, only look in the scope of the
  2269. // allocated class. If AFS_Both, look in both.
  2270. // 2) If an array size is given, look for operator new[], else look for
  2271. // operator new.
  2272. // 3) The first argument is always size_t. Append the arguments from the
  2273. // placement form.
  2274. SmallVector<Expr*, 8> AllocArgs;
  2275. AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
  2276. // We don't care about the actual value of these arguments.
  2277. // FIXME: Should the Sema create the expression and embed it in the syntax
  2278. // tree? Or should the consumer just recalculate the value?
  2279. // FIXME: Using a dummy value will interact poorly with attribute enable_if.
  2280. IntegerLiteral Size(
  2281. Context, llvm::APInt::getZero(Context.getTargetInfo().getPointerWidth(0)),
  2282. Context.getSizeType(), SourceLocation());
  2283. AllocArgs.push_back(&Size);
  2284. QualType AlignValT = Context.VoidTy;
  2285. if (PassAlignment) {
  2286. DeclareGlobalNewDelete();
  2287. AlignValT = Context.getTypeDeclType(getStdAlignValT());
  2288. }
  2289. CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
  2290. if (PassAlignment)
  2291. AllocArgs.push_back(&Align);
  2292. AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
  2293. // C++ [expr.new]p8:
  2294. // If the allocated type is a non-array type, the allocation
  2295. // function's name is operator new and the deallocation function's
  2296. // name is operator delete. If the allocated type is an array
  2297. // type, the allocation function's name is operator new[] and the
  2298. // deallocation function's name is operator delete[].
  2299. DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
  2300. IsArray ? OO_Array_New : OO_New);
  2301. QualType AllocElemType = Context.getBaseElementType(AllocType);
  2302. // Find the allocation function.
  2303. {
  2304. LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
  2305. // C++1z [expr.new]p9:
  2306. // If the new-expression begins with a unary :: operator, the allocation
  2307. // function's name is looked up in the global scope. Otherwise, if the
  2308. // allocated type is a class type T or array thereof, the allocation
  2309. // function's name is looked up in the scope of T.
  2310. if (AllocElemType->isRecordType() && NewScope != AFS_Global)
  2311. LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
  2312. // We can see ambiguity here if the allocation function is found in
  2313. // multiple base classes.
  2314. if (R.isAmbiguous())
  2315. return true;
  2316. // If this lookup fails to find the name, or if the allocated type is not
  2317. // a class type, the allocation function's name is looked up in the
  2318. // global scope.
  2319. if (R.empty()) {
  2320. if (NewScope == AFS_Class)
  2321. return true;
  2322. LookupQualifiedName(R, Context.getTranslationUnitDecl());
  2323. }
  2324. if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
  2325. if (PlaceArgs.empty()) {
  2326. Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
  2327. } else {
  2328. Diag(StartLoc, diag::err_openclcxx_placement_new);
  2329. }
  2330. return true;
  2331. }
  2332. assert(!R.empty() && "implicitly declared allocation functions not found");
  2333. assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
  2334. // We do our own custom access checks below.
  2335. R.suppressDiagnostics();
  2336. if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
  2337. OperatorNew, /*Candidates=*/nullptr,
  2338. /*AlignArg=*/nullptr, Diagnose))
  2339. return true;
  2340. }
  2341. // We don't need an operator delete if we're running under -fno-exceptions.
  2342. if (!getLangOpts().Exceptions) {
  2343. OperatorDelete = nullptr;
  2344. return false;
  2345. }
  2346. // Note, the name of OperatorNew might have been changed from array to
  2347. // non-array by resolveAllocationOverload.
  2348. DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
  2349. OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
  2350. ? OO_Array_Delete
  2351. : OO_Delete);
  2352. // C++ [expr.new]p19:
  2353. //
  2354. // If the new-expression begins with a unary :: operator, the
  2355. // deallocation function's name is looked up in the global
  2356. // scope. Otherwise, if the allocated type is a class type T or an
  2357. // array thereof, the deallocation function's name is looked up in
  2358. // the scope of T. If this lookup fails to find the name, or if
  2359. // the allocated type is not a class type or array thereof, the
  2360. // deallocation function's name is looked up in the global scope.
  2361. LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
  2362. if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
  2363. auto *RD =
  2364. cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
  2365. LookupQualifiedName(FoundDelete, RD);
  2366. }
  2367. if (FoundDelete.isAmbiguous())
  2368. return true; // FIXME: clean up expressions?
  2369. // Filter out any destroying operator deletes. We can't possibly call such a
  2370. // function in this context, because we're handling the case where the object
  2371. // was not successfully constructed.
  2372. // FIXME: This is not covered by the language rules yet.
  2373. {
  2374. LookupResult::Filter Filter = FoundDelete.makeFilter();
  2375. while (Filter.hasNext()) {
  2376. auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
  2377. if (FD && FD->isDestroyingOperatorDelete())
  2378. Filter.erase();
  2379. }
  2380. Filter.done();
  2381. }
  2382. bool FoundGlobalDelete = FoundDelete.empty();
  2383. if (FoundDelete.empty()) {
  2384. FoundDelete.clear(LookupOrdinaryName);
  2385. if (DeleteScope == AFS_Class)
  2386. return true;
  2387. DeclareGlobalNewDelete();
  2388. LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
  2389. }
  2390. FoundDelete.suppressDiagnostics();
  2391. SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
  2392. // Whether we're looking for a placement operator delete is dictated
  2393. // by whether we selected a placement operator new, not by whether
  2394. // we had explicit placement arguments. This matters for things like
  2395. // struct A { void *operator new(size_t, int = 0); ... };
  2396. // A *a = new A()
  2397. //
  2398. // We don't have any definition for what a "placement allocation function"
  2399. // is, but we assume it's any allocation function whose
  2400. // parameter-declaration-clause is anything other than (size_t).
  2401. //
  2402. // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
  2403. // This affects whether an exception from the constructor of an overaligned
  2404. // type uses the sized or non-sized form of aligned operator delete.
  2405. bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
  2406. OperatorNew->isVariadic();
  2407. if (isPlacementNew) {
  2408. // C++ [expr.new]p20:
  2409. // A declaration of a placement deallocation function matches the
  2410. // declaration of a placement allocation function if it has the
  2411. // same number of parameters and, after parameter transformations
  2412. // (8.3.5), all parameter types except the first are
  2413. // identical. [...]
  2414. //
  2415. // To perform this comparison, we compute the function type that
  2416. // the deallocation function should have, and use that type both
  2417. // for template argument deduction and for comparison purposes.
  2418. QualType ExpectedFunctionType;
  2419. {
  2420. auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
  2421. SmallVector<QualType, 4> ArgTypes;
  2422. ArgTypes.push_back(Context.VoidPtrTy);
  2423. for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
  2424. ArgTypes.push_back(Proto->getParamType(I));
  2425. FunctionProtoType::ExtProtoInfo EPI;
  2426. // FIXME: This is not part of the standard's rule.
  2427. EPI.Variadic = Proto->isVariadic();
  2428. ExpectedFunctionType
  2429. = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
  2430. }
  2431. for (LookupResult::iterator D = FoundDelete.begin(),
  2432. DEnd = FoundDelete.end();
  2433. D != DEnd; ++D) {
  2434. FunctionDecl *Fn = nullptr;
  2435. if (FunctionTemplateDecl *FnTmpl =
  2436. dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
  2437. // Perform template argument deduction to try to match the
  2438. // expected function type.
  2439. TemplateDeductionInfo Info(StartLoc);
  2440. if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
  2441. Info))
  2442. continue;
  2443. } else
  2444. Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
  2445. if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
  2446. ExpectedFunctionType,
  2447. /*AdjustExcpetionSpec*/true),
  2448. ExpectedFunctionType))
  2449. Matches.push_back(std::make_pair(D.getPair(), Fn));
  2450. }
  2451. if (getLangOpts().CUDA)
  2452. EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
  2453. } else {
  2454. // C++1y [expr.new]p22:
  2455. // For a non-placement allocation function, the normal deallocation
  2456. // function lookup is used
  2457. //
  2458. // Per [expr.delete]p10, this lookup prefers a member operator delete
  2459. // without a size_t argument, but prefers a non-member operator delete
  2460. // with a size_t where possible (which it always is in this case).
  2461. llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
  2462. UsualDeallocFnInfo Selected = resolveDeallocationOverload(
  2463. *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
  2464. /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
  2465. &BestDeallocFns);
  2466. if (Selected)
  2467. Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
  2468. else {
  2469. // If we failed to select an operator, all remaining functions are viable
  2470. // but ambiguous.
  2471. for (auto Fn : BestDeallocFns)
  2472. Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
  2473. }
  2474. }
  2475. // C++ [expr.new]p20:
  2476. // [...] If the lookup finds a single matching deallocation
  2477. // function, that function will be called; otherwise, no
  2478. // deallocation function will be called.
  2479. if (Matches.size() == 1) {
  2480. OperatorDelete = Matches[0].second;
  2481. // C++1z [expr.new]p23:
  2482. // If the lookup finds a usual deallocation function (3.7.4.2)
  2483. // with a parameter of type std::size_t and that function, considered
  2484. // as a placement deallocation function, would have been
  2485. // selected as a match for the allocation function, the program
  2486. // is ill-formed.
  2487. if (getLangOpts().CPlusPlus11 && isPlacementNew &&
  2488. isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
  2489. UsualDeallocFnInfo Info(*this,
  2490. DeclAccessPair::make(OperatorDelete, AS_public));
  2491. // Core issue, per mail to core reflector, 2016-10-09:
  2492. // If this is a member operator delete, and there is a corresponding
  2493. // non-sized member operator delete, this isn't /really/ a sized
  2494. // deallocation function, it just happens to have a size_t parameter.
  2495. bool IsSizedDelete = Info.HasSizeT;
  2496. if (IsSizedDelete && !FoundGlobalDelete) {
  2497. auto NonSizedDelete =
  2498. resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
  2499. /*WantAlign*/Info.HasAlignValT);
  2500. if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
  2501. NonSizedDelete.HasAlignValT == Info.HasAlignValT)
  2502. IsSizedDelete = false;
  2503. }
  2504. if (IsSizedDelete) {
  2505. SourceRange R = PlaceArgs.empty()
  2506. ? SourceRange()
  2507. : SourceRange(PlaceArgs.front()->getBeginLoc(),
  2508. PlaceArgs.back()->getEndLoc());
  2509. Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
  2510. if (!OperatorDelete->isImplicit())
  2511. Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
  2512. << DeleteName;
  2513. }
  2514. }
  2515. CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
  2516. Matches[0].first);
  2517. } else if (!Matches.empty()) {
  2518. // We found multiple suitable operators. Per [expr.new]p20, that means we
  2519. // call no 'operator delete' function, but we should at least warn the user.
  2520. // FIXME: Suppress this warning if the construction cannot throw.
  2521. Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
  2522. << DeleteName << AllocElemType;
  2523. for (auto &Match : Matches)
  2524. Diag(Match.second->getLocation(),
  2525. diag::note_member_declared_here) << DeleteName;
  2526. }
  2527. return false;
  2528. }
  2529. /// DeclareGlobalNewDelete - Declare the global forms of operator new and
  2530. /// delete. These are:
  2531. /// @code
  2532. /// // C++03:
  2533. /// void* operator new(std::size_t) throw(std::bad_alloc);
  2534. /// void* operator new[](std::size_t) throw(std::bad_alloc);
  2535. /// void operator delete(void *) throw();
  2536. /// void operator delete[](void *) throw();
  2537. /// // C++11:
  2538. /// void* operator new(std::size_t);
  2539. /// void* operator new[](std::size_t);
  2540. /// void operator delete(void *) noexcept;
  2541. /// void operator delete[](void *) noexcept;
  2542. /// // C++1y:
  2543. /// void* operator new(std::size_t);
  2544. /// void* operator new[](std::size_t);
  2545. /// void operator delete(void *) noexcept;
  2546. /// void operator delete[](void *) noexcept;
  2547. /// void operator delete(void *, std::size_t) noexcept;
  2548. /// void operator delete[](void *, std::size_t) noexcept;
  2549. /// @endcode
  2550. /// Note that the placement and nothrow forms of new are *not* implicitly
  2551. /// declared. Their use requires including \<new\>.
  2552. void Sema::DeclareGlobalNewDelete() {
  2553. if (GlobalNewDeleteDeclared)
  2554. return;
  2555. // The implicitly declared new and delete operators
  2556. // are not supported in OpenCL.
  2557. if (getLangOpts().OpenCLCPlusPlus)
  2558. return;
  2559. // C++ [basic.std.dynamic]p2:
  2560. // [...] The following allocation and deallocation functions (18.4) are
  2561. // implicitly declared in global scope in each translation unit of a
  2562. // program
  2563. //
  2564. // C++03:
  2565. // void* operator new(std::size_t) throw(std::bad_alloc);
  2566. // void* operator new[](std::size_t) throw(std::bad_alloc);
  2567. // void operator delete(void*) throw();
  2568. // void operator delete[](void*) throw();
  2569. // C++11:
  2570. // void* operator new(std::size_t);
  2571. // void* operator new[](std::size_t);
  2572. // void operator delete(void*) noexcept;
  2573. // void operator delete[](void*) noexcept;
  2574. // C++1y:
  2575. // void* operator new(std::size_t);
  2576. // void* operator new[](std::size_t);
  2577. // void operator delete(void*) noexcept;
  2578. // void operator delete[](void*) noexcept;
  2579. // void operator delete(void*, std::size_t) noexcept;
  2580. // void operator delete[](void*, std::size_t) noexcept;
  2581. //
  2582. // These implicit declarations introduce only the function names operator
  2583. // new, operator new[], operator delete, operator delete[].
  2584. //
  2585. // Here, we need to refer to std::bad_alloc, so we will implicitly declare
  2586. // "std" or "bad_alloc" as necessary to form the exception specification.
  2587. // However, we do not make these implicit declarations visible to name
  2588. // lookup.
  2589. if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
  2590. // The "std::bad_alloc" class has not yet been declared, so build it
  2591. // implicitly.
  2592. StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
  2593. getOrCreateStdNamespace(),
  2594. SourceLocation(), SourceLocation(),
  2595. &PP.getIdentifierTable().get("bad_alloc"),
  2596. nullptr);
  2597. getStdBadAlloc()->setImplicit(true);
  2598. }
  2599. if (!StdAlignValT && getLangOpts().AlignedAllocation) {
  2600. // The "std::align_val_t" enum class has not yet been declared, so build it
  2601. // implicitly.
  2602. auto *AlignValT = EnumDecl::Create(
  2603. Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
  2604. &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
  2605. AlignValT->setIntegerType(Context.getSizeType());
  2606. AlignValT->setPromotionType(Context.getSizeType());
  2607. AlignValT->setImplicit(true);
  2608. StdAlignValT = AlignValT;
  2609. }
  2610. GlobalNewDeleteDeclared = true;
  2611. QualType VoidPtr = Context.getPointerType(Context.VoidTy);
  2612. QualType SizeT = Context.getSizeType();
  2613. auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
  2614. QualType Return, QualType Param) {
  2615. llvm::SmallVector<QualType, 3> Params;
  2616. Params.push_back(Param);
  2617. // Create up to four variants of the function (sized/aligned).
  2618. bool HasSizedVariant = getLangOpts().SizedDeallocation &&
  2619. (Kind == OO_Delete || Kind == OO_Array_Delete);
  2620. bool HasAlignedVariant = getLangOpts().AlignedAllocation;
  2621. int NumSizeVariants = (HasSizedVariant ? 2 : 1);
  2622. int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
  2623. for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
  2624. if (Sized)
  2625. Params.push_back(SizeT);
  2626. for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
  2627. if (Aligned)
  2628. Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
  2629. DeclareGlobalAllocationFunction(
  2630. Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
  2631. if (Aligned)
  2632. Params.pop_back();
  2633. }
  2634. }
  2635. };
  2636. DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
  2637. DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
  2638. DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
  2639. DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
  2640. }
  2641. /// DeclareGlobalAllocationFunction - Declares a single implicit global
  2642. /// allocation function if it doesn't already exist.
  2643. void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
  2644. QualType Return,
  2645. ArrayRef<QualType> Params) {
  2646. DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
  2647. // Check if this function is already declared.
  2648. DeclContext::lookup_result R = GlobalCtx->lookup(Name);
  2649. for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
  2650. Alloc != AllocEnd; ++Alloc) {
  2651. // Only look at non-template functions, as it is the predefined,
  2652. // non-templated allocation function we are trying to declare here.
  2653. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
  2654. if (Func->getNumParams() == Params.size()) {
  2655. llvm::SmallVector<QualType, 3> FuncParams;
  2656. for (auto *P : Func->parameters())
  2657. FuncParams.push_back(
  2658. Context.getCanonicalType(P->getType().getUnqualifiedType()));
  2659. if (llvm::makeArrayRef(FuncParams) == Params) {
  2660. // Make the function visible to name lookup, even if we found it in
  2661. // an unimported module. It either is an implicitly-declared global
  2662. // allocation function, or is suppressing that function.
  2663. Func->setVisibleDespiteOwningModule();
  2664. return;
  2665. }
  2666. }
  2667. }
  2668. }
  2669. FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
  2670. /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
  2671. QualType BadAllocType;
  2672. bool HasBadAllocExceptionSpec
  2673. = (Name.getCXXOverloadedOperator() == OO_New ||
  2674. Name.getCXXOverloadedOperator() == OO_Array_New);
  2675. if (HasBadAllocExceptionSpec) {
  2676. if (!getLangOpts().CPlusPlus11) {
  2677. BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
  2678. assert(StdBadAlloc && "Must have std::bad_alloc declared");
  2679. EPI.ExceptionSpec.Type = EST_Dynamic;
  2680. EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
  2681. }
  2682. if (getLangOpts().NewInfallible) {
  2683. EPI.ExceptionSpec.Type = EST_DynamicNone;
  2684. }
  2685. } else {
  2686. EPI.ExceptionSpec =
  2687. getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
  2688. }
  2689. auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
  2690. QualType FnType = Context.getFunctionType(Return, Params, EPI);
  2691. FunctionDecl *Alloc = FunctionDecl::Create(
  2692. Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
  2693. /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
  2694. true);
  2695. Alloc->setImplicit();
  2696. // Global allocation functions should always be visible.
  2697. Alloc->setVisibleDespiteOwningModule();
  2698. if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible)
  2699. Alloc->addAttr(
  2700. ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
  2701. Alloc->addAttr(VisibilityAttr::CreateImplicit(
  2702. Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
  2703. ? VisibilityAttr::Hidden
  2704. : VisibilityAttr::Default));
  2705. llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
  2706. for (QualType T : Params) {
  2707. ParamDecls.push_back(ParmVarDecl::Create(
  2708. Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
  2709. /*TInfo=*/nullptr, SC_None, nullptr));
  2710. ParamDecls.back()->setImplicit();
  2711. }
  2712. Alloc->setParams(ParamDecls);
  2713. if (ExtraAttr)
  2714. Alloc->addAttr(ExtraAttr);
  2715. AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
  2716. Context.getTranslationUnitDecl()->addDecl(Alloc);
  2717. IdResolver.tryAddTopLevelDecl(Alloc, Name);
  2718. };
  2719. if (!LangOpts.CUDA)
  2720. CreateAllocationFunctionDecl(nullptr);
  2721. else {
  2722. // Host and device get their own declaration so each can be
  2723. // defined or re-declared independently.
  2724. CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
  2725. CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
  2726. }
  2727. }
  2728. FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
  2729. bool CanProvideSize,
  2730. bool Overaligned,
  2731. DeclarationName Name) {
  2732. DeclareGlobalNewDelete();
  2733. LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
  2734. LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
  2735. // FIXME: It's possible for this to result in ambiguity, through a
  2736. // user-declared variadic operator delete or the enable_if attribute. We
  2737. // should probably not consider those cases to be usual deallocation
  2738. // functions. But for now we just make an arbitrary choice in that case.
  2739. auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
  2740. Overaligned);
  2741. assert(Result.FD && "operator delete missing from global scope?");
  2742. return Result.FD;
  2743. }
  2744. FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
  2745. CXXRecordDecl *RD) {
  2746. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  2747. FunctionDecl *OperatorDelete = nullptr;
  2748. if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
  2749. return nullptr;
  2750. if (OperatorDelete)
  2751. return OperatorDelete;
  2752. // If there's no class-specific operator delete, look up the global
  2753. // non-array delete.
  2754. return FindUsualDeallocationFunction(
  2755. Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
  2756. Name);
  2757. }
  2758. bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
  2759. DeclarationName Name,
  2760. FunctionDecl *&Operator, bool Diagnose) {
  2761. LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
  2762. // Try to find operator delete/operator delete[] in class scope.
  2763. LookupQualifiedName(Found, RD);
  2764. if (Found.isAmbiguous())
  2765. return true;
  2766. Found.suppressDiagnostics();
  2767. bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
  2768. // C++17 [expr.delete]p10:
  2769. // If the deallocation functions have class scope, the one without a
  2770. // parameter of type std::size_t is selected.
  2771. llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
  2772. resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
  2773. /*WantAlign*/ Overaligned, &Matches);
  2774. // If we could find an overload, use it.
  2775. if (Matches.size() == 1) {
  2776. Operator = cast<CXXMethodDecl>(Matches[0].FD);
  2777. // FIXME: DiagnoseUseOfDecl?
  2778. if (Operator->isDeleted()) {
  2779. if (Diagnose) {
  2780. Diag(StartLoc, diag::err_deleted_function_use);
  2781. NoteDeletedFunction(Operator);
  2782. }
  2783. return true;
  2784. }
  2785. if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
  2786. Matches[0].Found, Diagnose) == AR_inaccessible)
  2787. return true;
  2788. return false;
  2789. }
  2790. // We found multiple suitable operators; complain about the ambiguity.
  2791. // FIXME: The standard doesn't say to do this; it appears that the intent
  2792. // is that this should never happen.
  2793. if (!Matches.empty()) {
  2794. if (Diagnose) {
  2795. Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
  2796. << Name << RD;
  2797. for (auto &Match : Matches)
  2798. Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
  2799. }
  2800. return true;
  2801. }
  2802. // We did find operator delete/operator delete[] declarations, but
  2803. // none of them were suitable.
  2804. if (!Found.empty()) {
  2805. if (Diagnose) {
  2806. Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
  2807. << Name << RD;
  2808. for (NamedDecl *D : Found)
  2809. Diag(D->getUnderlyingDecl()->getLocation(),
  2810. diag::note_member_declared_here) << Name;
  2811. }
  2812. return true;
  2813. }
  2814. Operator = nullptr;
  2815. return false;
  2816. }
  2817. namespace {
  2818. /// Checks whether delete-expression, and new-expression used for
  2819. /// initializing deletee have the same array form.
  2820. class MismatchingNewDeleteDetector {
  2821. public:
  2822. enum MismatchResult {
  2823. /// Indicates that there is no mismatch or a mismatch cannot be proven.
  2824. NoMismatch,
  2825. /// Indicates that variable is initialized with mismatching form of \a new.
  2826. VarInitMismatches,
  2827. /// Indicates that member is initialized with mismatching form of \a new.
  2828. MemberInitMismatches,
  2829. /// Indicates that 1 or more constructors' definitions could not been
  2830. /// analyzed, and they will be checked again at the end of translation unit.
  2831. AnalyzeLater
  2832. };
  2833. /// \param EndOfTU True, if this is the final analysis at the end of
  2834. /// translation unit. False, if this is the initial analysis at the point
  2835. /// delete-expression was encountered.
  2836. explicit MismatchingNewDeleteDetector(bool EndOfTU)
  2837. : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
  2838. HasUndefinedConstructors(false) {}
  2839. /// Checks whether pointee of a delete-expression is initialized with
  2840. /// matching form of new-expression.
  2841. ///
  2842. /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
  2843. /// point where delete-expression is encountered, then a warning will be
  2844. /// issued immediately. If return value is \c AnalyzeLater at the point where
  2845. /// delete-expression is seen, then member will be analyzed at the end of
  2846. /// translation unit. \c AnalyzeLater is returned iff at least one constructor
  2847. /// couldn't be analyzed. If at least one constructor initializes the member
  2848. /// with matching type of new, the return value is \c NoMismatch.
  2849. MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
  2850. /// Analyzes a class member.
  2851. /// \param Field Class member to analyze.
  2852. /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
  2853. /// for deleting the \p Field.
  2854. MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
  2855. FieldDecl *Field;
  2856. /// List of mismatching new-expressions used for initialization of the pointee
  2857. llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
  2858. /// Indicates whether delete-expression was in array form.
  2859. bool IsArrayForm;
  2860. private:
  2861. const bool EndOfTU;
  2862. /// Indicates that there is at least one constructor without body.
  2863. bool HasUndefinedConstructors;
  2864. /// Returns \c CXXNewExpr from given initialization expression.
  2865. /// \param E Expression used for initializing pointee in delete-expression.
  2866. /// E can be a single-element \c InitListExpr consisting of new-expression.
  2867. const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
  2868. /// Returns whether member is initialized with mismatching form of
  2869. /// \c new either by the member initializer or in-class initialization.
  2870. ///
  2871. /// If bodies of all constructors are not visible at the end of translation
  2872. /// unit or at least one constructor initializes member with the matching
  2873. /// form of \c new, mismatch cannot be proven, and this function will return
  2874. /// \c NoMismatch.
  2875. MismatchResult analyzeMemberExpr(const MemberExpr *ME);
  2876. /// Returns whether variable is initialized with mismatching form of
  2877. /// \c new.
  2878. ///
  2879. /// If variable is initialized with matching form of \c new or variable is not
  2880. /// initialized with a \c new expression, this function will return true.
  2881. /// If variable is initialized with mismatching form of \c new, returns false.
  2882. /// \param D Variable to analyze.
  2883. bool hasMatchingVarInit(const DeclRefExpr *D);
  2884. /// Checks whether the constructor initializes pointee with mismatching
  2885. /// form of \c new.
  2886. ///
  2887. /// Returns true, if member is initialized with matching form of \c new in
  2888. /// member initializer list. Returns false, if member is initialized with the
  2889. /// matching form of \c new in this constructor's initializer or given
  2890. /// constructor isn't defined at the point where delete-expression is seen, or
  2891. /// member isn't initialized by the constructor.
  2892. bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
  2893. /// Checks whether member is initialized with matching form of
  2894. /// \c new in member initializer list.
  2895. bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
  2896. /// Checks whether member is initialized with mismatching form of \c new by
  2897. /// in-class initializer.
  2898. MismatchResult analyzeInClassInitializer();
  2899. };
  2900. }
  2901. MismatchingNewDeleteDetector::MismatchResult
  2902. MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
  2903. NewExprs.clear();
  2904. assert(DE && "Expected delete-expression");
  2905. IsArrayForm = DE->isArrayForm();
  2906. const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
  2907. if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
  2908. return analyzeMemberExpr(ME);
  2909. } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
  2910. if (!hasMatchingVarInit(D))
  2911. return VarInitMismatches;
  2912. }
  2913. return NoMismatch;
  2914. }
  2915. const CXXNewExpr *
  2916. MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
  2917. assert(E != nullptr && "Expected a valid initializer expression");
  2918. E = E->IgnoreParenImpCasts();
  2919. if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
  2920. if (ILE->getNumInits() == 1)
  2921. E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
  2922. }
  2923. return dyn_cast_or_null<const CXXNewExpr>(E);
  2924. }
  2925. bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
  2926. const CXXCtorInitializer *CI) {
  2927. const CXXNewExpr *NE = nullptr;
  2928. if (Field == CI->getMember() &&
  2929. (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
  2930. if (NE->isArray() == IsArrayForm)
  2931. return true;
  2932. else
  2933. NewExprs.push_back(NE);
  2934. }
  2935. return false;
  2936. }
  2937. bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
  2938. const CXXConstructorDecl *CD) {
  2939. if (CD->isImplicit())
  2940. return false;
  2941. const FunctionDecl *Definition = CD;
  2942. if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
  2943. HasUndefinedConstructors = true;
  2944. return EndOfTU;
  2945. }
  2946. for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
  2947. if (hasMatchingNewInCtorInit(CI))
  2948. return true;
  2949. }
  2950. return false;
  2951. }
  2952. MismatchingNewDeleteDetector::MismatchResult
  2953. MismatchingNewDeleteDetector::analyzeInClassInitializer() {
  2954. assert(Field != nullptr && "This should be called only for members");
  2955. const Expr *InitExpr = Field->getInClassInitializer();
  2956. if (!InitExpr)
  2957. return EndOfTU ? NoMismatch : AnalyzeLater;
  2958. if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
  2959. if (NE->isArray() != IsArrayForm) {
  2960. NewExprs.push_back(NE);
  2961. return MemberInitMismatches;
  2962. }
  2963. }
  2964. return NoMismatch;
  2965. }
  2966. MismatchingNewDeleteDetector::MismatchResult
  2967. MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
  2968. bool DeleteWasArrayForm) {
  2969. assert(Field != nullptr && "Analysis requires a valid class member.");
  2970. this->Field = Field;
  2971. IsArrayForm = DeleteWasArrayForm;
  2972. const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
  2973. for (const auto *CD : RD->ctors()) {
  2974. if (hasMatchingNewInCtor(CD))
  2975. return NoMismatch;
  2976. }
  2977. if (HasUndefinedConstructors)
  2978. return EndOfTU ? NoMismatch : AnalyzeLater;
  2979. if (!NewExprs.empty())
  2980. return MemberInitMismatches;
  2981. return Field->hasInClassInitializer() ? analyzeInClassInitializer()
  2982. : NoMismatch;
  2983. }
  2984. MismatchingNewDeleteDetector::MismatchResult
  2985. MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
  2986. assert(ME != nullptr && "Expected a member expression");
  2987. if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  2988. return analyzeField(F, IsArrayForm);
  2989. return NoMismatch;
  2990. }
  2991. bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
  2992. const CXXNewExpr *NE = nullptr;
  2993. if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
  2994. if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
  2995. NE->isArray() != IsArrayForm) {
  2996. NewExprs.push_back(NE);
  2997. }
  2998. }
  2999. return NewExprs.empty();
  3000. }
  3001. static void
  3002. DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
  3003. const MismatchingNewDeleteDetector &Detector) {
  3004. SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
  3005. FixItHint H;
  3006. if (!Detector.IsArrayForm)
  3007. H = FixItHint::CreateInsertion(EndOfDelete, "[]");
  3008. else {
  3009. SourceLocation RSquare = Lexer::findLocationAfterToken(
  3010. DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
  3011. SemaRef.getLangOpts(), true);
  3012. if (RSquare.isValid())
  3013. H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
  3014. }
  3015. SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
  3016. << Detector.IsArrayForm << H;
  3017. for (const auto *NE : Detector.NewExprs)
  3018. SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
  3019. << Detector.IsArrayForm;
  3020. }
  3021. void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
  3022. if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
  3023. return;
  3024. MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
  3025. switch (Detector.analyzeDeleteExpr(DE)) {
  3026. case MismatchingNewDeleteDetector::VarInitMismatches:
  3027. case MismatchingNewDeleteDetector::MemberInitMismatches: {
  3028. DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
  3029. break;
  3030. }
  3031. case MismatchingNewDeleteDetector::AnalyzeLater: {
  3032. DeleteExprs[Detector.Field].push_back(
  3033. std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
  3034. break;
  3035. }
  3036. case MismatchingNewDeleteDetector::NoMismatch:
  3037. break;
  3038. }
  3039. }
  3040. void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
  3041. bool DeleteWasArrayForm) {
  3042. MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
  3043. switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
  3044. case MismatchingNewDeleteDetector::VarInitMismatches:
  3045. llvm_unreachable("This analysis should have been done for class members.");
  3046. case MismatchingNewDeleteDetector::AnalyzeLater:
  3047. llvm_unreachable("Analysis cannot be postponed any point beyond end of "
  3048. "translation unit.");
  3049. case MismatchingNewDeleteDetector::MemberInitMismatches:
  3050. DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
  3051. break;
  3052. case MismatchingNewDeleteDetector::NoMismatch:
  3053. break;
  3054. }
  3055. }
  3056. /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
  3057. /// @code ::delete ptr; @endcode
  3058. /// or
  3059. /// @code delete [] ptr; @endcode
  3060. ExprResult
  3061. Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
  3062. bool ArrayForm, Expr *ExE) {
  3063. // C++ [expr.delete]p1:
  3064. // The operand shall have a pointer type, or a class type having a single
  3065. // non-explicit conversion function to a pointer type. The result has type
  3066. // void.
  3067. //
  3068. // DR599 amends "pointer type" to "pointer to object type" in both cases.
  3069. ExprResult Ex = ExE;
  3070. FunctionDecl *OperatorDelete = nullptr;
  3071. bool ArrayFormAsWritten = ArrayForm;
  3072. bool UsualArrayDeleteWantsSize = false;
  3073. if (!Ex.get()->isTypeDependent()) {
  3074. // Perform lvalue-to-rvalue cast, if needed.
  3075. Ex = DefaultLvalueConversion(Ex.get());
  3076. if (Ex.isInvalid())
  3077. return ExprError();
  3078. QualType Type = Ex.get()->getType();
  3079. class DeleteConverter : public ContextualImplicitConverter {
  3080. public:
  3081. DeleteConverter() : ContextualImplicitConverter(false, true) {}
  3082. bool match(QualType ConvType) override {
  3083. // FIXME: If we have an operator T* and an operator void*, we must pick
  3084. // the operator T*.
  3085. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  3086. if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
  3087. return true;
  3088. return false;
  3089. }
  3090. SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
  3091. QualType T) override {
  3092. return S.Diag(Loc, diag::err_delete_operand) << T;
  3093. }
  3094. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  3095. QualType T) override {
  3096. return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
  3097. }
  3098. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  3099. QualType T,
  3100. QualType ConvTy) override {
  3101. return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
  3102. }
  3103. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  3104. QualType ConvTy) override {
  3105. return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
  3106. << ConvTy;
  3107. }
  3108. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  3109. QualType T) override {
  3110. return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
  3111. }
  3112. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  3113. QualType ConvTy) override {
  3114. return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
  3115. << ConvTy;
  3116. }
  3117. SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
  3118. QualType T,
  3119. QualType ConvTy) override {
  3120. llvm_unreachable("conversion functions are permitted");
  3121. }
  3122. } Converter;
  3123. Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
  3124. if (Ex.isInvalid())
  3125. return ExprError();
  3126. Type = Ex.get()->getType();
  3127. if (!Converter.match(Type))
  3128. // FIXME: PerformContextualImplicitConversion should return ExprError
  3129. // itself in this case.
  3130. return ExprError();
  3131. QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
  3132. QualType PointeeElem = Context.getBaseElementType(Pointee);
  3133. if (Pointee.getAddressSpace() != LangAS::Default &&
  3134. !getLangOpts().OpenCLCPlusPlus)
  3135. return Diag(Ex.get()->getBeginLoc(),
  3136. diag::err_address_space_qualified_delete)
  3137. << Pointee.getUnqualifiedType()
  3138. << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
  3139. CXXRecordDecl *PointeeRD = nullptr;
  3140. if (Pointee->isVoidType() && !isSFINAEContext()) {
  3141. // The C++ standard bans deleting a pointer to a non-object type, which
  3142. // effectively bans deletion of "void*". However, most compilers support
  3143. // this, so we treat it as a warning unless we're in a SFINAE context.
  3144. Diag(StartLoc, diag::ext_delete_void_ptr_operand)
  3145. << Type << Ex.get()->getSourceRange();
  3146. } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
  3147. Pointee->isSizelessType()) {
  3148. return ExprError(Diag(StartLoc, diag::err_delete_operand)
  3149. << Type << Ex.get()->getSourceRange());
  3150. } else if (!Pointee->isDependentType()) {
  3151. // FIXME: This can result in errors if the definition was imported from a
  3152. // module but is hidden.
  3153. if (!RequireCompleteType(StartLoc, Pointee,
  3154. diag::warn_delete_incomplete, Ex.get())) {
  3155. if (const RecordType *RT = PointeeElem->getAs<RecordType>())
  3156. PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
  3157. }
  3158. }
  3159. if (Pointee->isArrayType() && !ArrayForm) {
  3160. Diag(StartLoc, diag::warn_delete_array_type)
  3161. << Type << Ex.get()->getSourceRange()
  3162. << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
  3163. ArrayForm = true;
  3164. }
  3165. DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
  3166. ArrayForm ? OO_Array_Delete : OO_Delete);
  3167. if (PointeeRD) {
  3168. if (!UseGlobal &&
  3169. FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
  3170. OperatorDelete))
  3171. return ExprError();
  3172. // If we're allocating an array of records, check whether the
  3173. // usual operator delete[] has a size_t parameter.
  3174. if (ArrayForm) {
  3175. // If the user specifically asked to use the global allocator,
  3176. // we'll need to do the lookup into the class.
  3177. if (UseGlobal)
  3178. UsualArrayDeleteWantsSize =
  3179. doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
  3180. // Otherwise, the usual operator delete[] should be the
  3181. // function we just found.
  3182. else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
  3183. UsualArrayDeleteWantsSize =
  3184. UsualDeallocFnInfo(*this,
  3185. DeclAccessPair::make(OperatorDelete, AS_public))
  3186. .HasSizeT;
  3187. }
  3188. if (!PointeeRD->hasIrrelevantDestructor())
  3189. if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
  3190. MarkFunctionReferenced(StartLoc,
  3191. const_cast<CXXDestructorDecl*>(Dtor));
  3192. if (DiagnoseUseOfDecl(Dtor, StartLoc))
  3193. return ExprError();
  3194. }
  3195. CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
  3196. /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
  3197. /*WarnOnNonAbstractTypes=*/!ArrayForm,
  3198. SourceLocation());
  3199. }
  3200. if (!OperatorDelete) {
  3201. if (getLangOpts().OpenCLCPlusPlus) {
  3202. Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
  3203. return ExprError();
  3204. }
  3205. bool IsComplete = isCompleteType(StartLoc, Pointee);
  3206. bool CanProvideSize =
  3207. IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
  3208. Pointee.isDestructedType());
  3209. bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
  3210. // Look for a global declaration.
  3211. OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
  3212. Overaligned, DeleteName);
  3213. }
  3214. MarkFunctionReferenced(StartLoc, OperatorDelete);
  3215. // Check access and ambiguity of destructor if we're going to call it.
  3216. // Note that this is required even for a virtual delete.
  3217. bool IsVirtualDelete = false;
  3218. if (PointeeRD) {
  3219. if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
  3220. CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
  3221. PDiag(diag::err_access_dtor) << PointeeElem);
  3222. IsVirtualDelete = Dtor->isVirtual();
  3223. }
  3224. }
  3225. DiagnoseUseOfDecl(OperatorDelete, StartLoc);
  3226. // Convert the operand to the type of the first parameter of operator
  3227. // delete. This is only necessary if we selected a destroying operator
  3228. // delete that we are going to call (non-virtually); converting to void*
  3229. // is trivial and left to AST consumers to handle.
  3230. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  3231. if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
  3232. Qualifiers Qs = Pointee.getQualifiers();
  3233. if (Qs.hasCVRQualifiers()) {
  3234. // Qualifiers are irrelevant to this conversion; we're only looking
  3235. // for access and ambiguity.
  3236. Qs.removeCVRQualifiers();
  3237. QualType Unqual = Context.getPointerType(
  3238. Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
  3239. Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
  3240. }
  3241. Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
  3242. if (Ex.isInvalid())
  3243. return ExprError();
  3244. }
  3245. }
  3246. CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
  3247. Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
  3248. UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
  3249. AnalyzeDeleteExprMismatch(Result);
  3250. return Result;
  3251. }
  3252. static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
  3253. bool IsDelete,
  3254. FunctionDecl *&Operator) {
  3255. DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
  3256. IsDelete ? OO_Delete : OO_New);
  3257. LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
  3258. S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
  3259. assert(!R.empty() && "implicitly declared allocation functions not found");
  3260. assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
  3261. // We do our own custom access checks below.
  3262. R.suppressDiagnostics();
  3263. SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
  3264. OverloadCandidateSet Candidates(R.getNameLoc(),
  3265. OverloadCandidateSet::CSK_Normal);
  3266. for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
  3267. FnOvl != FnOvlEnd; ++FnOvl) {
  3268. // Even member operator new/delete are implicitly treated as
  3269. // static, so don't use AddMemberCandidate.
  3270. NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
  3271. if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
  3272. S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
  3273. /*ExplicitTemplateArgs=*/nullptr, Args,
  3274. Candidates,
  3275. /*SuppressUserConversions=*/false);
  3276. continue;
  3277. }
  3278. FunctionDecl *Fn = cast<FunctionDecl>(D);
  3279. S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
  3280. /*SuppressUserConversions=*/false);
  3281. }
  3282. SourceRange Range = TheCall->getSourceRange();
  3283. // Do the resolution.
  3284. OverloadCandidateSet::iterator Best;
  3285. switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
  3286. case OR_Success: {
  3287. // Got one!
  3288. FunctionDecl *FnDecl = Best->Function;
  3289. assert(R.getNamingClass() == nullptr &&
  3290. "class members should not be considered");
  3291. if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
  3292. S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
  3293. << (IsDelete ? 1 : 0) << Range;
  3294. S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
  3295. << R.getLookupName() << FnDecl->getSourceRange();
  3296. return true;
  3297. }
  3298. Operator = FnDecl;
  3299. return false;
  3300. }
  3301. case OR_No_Viable_Function:
  3302. Candidates.NoteCandidates(
  3303. PartialDiagnosticAt(R.getNameLoc(),
  3304. S.PDiag(diag::err_ovl_no_viable_function_in_call)
  3305. << R.getLookupName() << Range),
  3306. S, OCD_AllCandidates, Args);
  3307. return true;
  3308. case OR_Ambiguous:
  3309. Candidates.NoteCandidates(
  3310. PartialDiagnosticAt(R.getNameLoc(),
  3311. S.PDiag(diag::err_ovl_ambiguous_call)
  3312. << R.getLookupName() << Range),
  3313. S, OCD_AmbiguousCandidates, Args);
  3314. return true;
  3315. case OR_Deleted: {
  3316. Candidates.NoteCandidates(
  3317. PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
  3318. << R.getLookupName() << Range),
  3319. S, OCD_AllCandidates, Args);
  3320. return true;
  3321. }
  3322. }
  3323. llvm_unreachable("Unreachable, bad result from BestViableFunction");
  3324. }
  3325. ExprResult
  3326. Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
  3327. bool IsDelete) {
  3328. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  3329. if (!getLangOpts().CPlusPlus) {
  3330. Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
  3331. << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
  3332. << "C++";
  3333. return ExprError();
  3334. }
  3335. // CodeGen assumes it can find the global new and delete to call,
  3336. // so ensure that they are declared.
  3337. DeclareGlobalNewDelete();
  3338. FunctionDecl *OperatorNewOrDelete = nullptr;
  3339. if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
  3340. OperatorNewOrDelete))
  3341. return ExprError();
  3342. assert(OperatorNewOrDelete && "should be found");
  3343. DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
  3344. MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
  3345. TheCall->setType(OperatorNewOrDelete->getReturnType());
  3346. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  3347. QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
  3348. InitializedEntity Entity =
  3349. InitializedEntity::InitializeParameter(Context, ParamTy, false);
  3350. ExprResult Arg = PerformCopyInitialization(
  3351. Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
  3352. if (Arg.isInvalid())
  3353. return ExprError();
  3354. TheCall->setArg(i, Arg.get());
  3355. }
  3356. auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
  3357. assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
  3358. "Callee expected to be implicit cast to a builtin function pointer");
  3359. Callee->setType(OperatorNewOrDelete->getType());
  3360. return TheCallResult;
  3361. }
  3362. void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
  3363. bool IsDelete, bool CallCanBeVirtual,
  3364. bool WarnOnNonAbstractTypes,
  3365. SourceLocation DtorLoc) {
  3366. if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
  3367. return;
  3368. // C++ [expr.delete]p3:
  3369. // In the first alternative (delete object), if the static type of the
  3370. // object to be deleted is different from its dynamic type, the static
  3371. // type shall be a base class of the dynamic type of the object to be
  3372. // deleted and the static type shall have a virtual destructor or the
  3373. // behavior is undefined.
  3374. //
  3375. const CXXRecordDecl *PointeeRD = dtor->getParent();
  3376. // Note: a final class cannot be derived from, no issue there
  3377. if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
  3378. return;
  3379. // If the superclass is in a system header, there's nothing that can be done.
  3380. // The `delete` (where we emit the warning) can be in a system header,
  3381. // what matters for this warning is where the deleted type is defined.
  3382. if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
  3383. return;
  3384. QualType ClassType = dtor->getThisType()->getPointeeType();
  3385. if (PointeeRD->isAbstract()) {
  3386. // If the class is abstract, we warn by default, because we're
  3387. // sure the code has undefined behavior.
  3388. Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
  3389. << ClassType;
  3390. } else if (WarnOnNonAbstractTypes) {
  3391. // Otherwise, if this is not an array delete, it's a bit suspect,
  3392. // but not necessarily wrong.
  3393. Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
  3394. << ClassType;
  3395. }
  3396. if (!IsDelete) {
  3397. std::string TypeStr;
  3398. ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
  3399. Diag(DtorLoc, diag::note_delete_non_virtual)
  3400. << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
  3401. }
  3402. }
  3403. Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
  3404. SourceLocation StmtLoc,
  3405. ConditionKind CK) {
  3406. ExprResult E =
  3407. CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
  3408. if (E.isInvalid())
  3409. return ConditionError();
  3410. return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
  3411. CK == ConditionKind::ConstexprIf);
  3412. }
  3413. /// Check the use of the given variable as a C++ condition in an if,
  3414. /// while, do-while, or switch statement.
  3415. ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
  3416. SourceLocation StmtLoc,
  3417. ConditionKind CK) {
  3418. if (ConditionVar->isInvalidDecl())
  3419. return ExprError();
  3420. QualType T = ConditionVar->getType();
  3421. // C++ [stmt.select]p2:
  3422. // The declarator shall not specify a function or an array.
  3423. if (T->isFunctionType())
  3424. return ExprError(Diag(ConditionVar->getLocation(),
  3425. diag::err_invalid_use_of_function_type)
  3426. << ConditionVar->getSourceRange());
  3427. else if (T->isArrayType())
  3428. return ExprError(Diag(ConditionVar->getLocation(),
  3429. diag::err_invalid_use_of_array_type)
  3430. << ConditionVar->getSourceRange());
  3431. ExprResult Condition = BuildDeclRefExpr(
  3432. ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
  3433. ConditionVar->getLocation());
  3434. switch (CK) {
  3435. case ConditionKind::Boolean:
  3436. return CheckBooleanCondition(StmtLoc, Condition.get());
  3437. case ConditionKind::ConstexprIf:
  3438. return CheckBooleanCondition(StmtLoc, Condition.get(), true);
  3439. case ConditionKind::Switch:
  3440. return CheckSwitchCondition(StmtLoc, Condition.get());
  3441. }
  3442. llvm_unreachable("unexpected condition kind");
  3443. }
  3444. /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
  3445. ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
  3446. // C++11 6.4p4:
  3447. // The value of a condition that is an initialized declaration in a statement
  3448. // other than a switch statement is the value of the declared variable
  3449. // implicitly converted to type bool. If that conversion is ill-formed, the
  3450. // program is ill-formed.
  3451. // The value of a condition that is an expression is the value of the
  3452. // expression, implicitly converted to bool.
  3453. //
  3454. // C++2b 8.5.2p2
  3455. // If the if statement is of the form if constexpr, the value of the condition
  3456. // is contextually converted to bool and the converted expression shall be
  3457. // a constant expression.
  3458. //
  3459. ExprResult E = PerformContextuallyConvertToBool(CondExpr);
  3460. if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
  3461. return E;
  3462. // FIXME: Return this value to the caller so they don't need to recompute it.
  3463. llvm::APSInt Cond;
  3464. E = VerifyIntegerConstantExpression(
  3465. E.get(), &Cond,
  3466. diag::err_constexpr_if_condition_expression_is_not_constant);
  3467. return E;
  3468. }
  3469. /// Helper function to determine whether this is the (deprecated) C++
  3470. /// conversion from a string literal to a pointer to non-const char or
  3471. /// non-const wchar_t (for narrow and wide string literals,
  3472. /// respectively).
  3473. bool
  3474. Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
  3475. // Look inside the implicit cast, if it exists.
  3476. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
  3477. From = Cast->getSubExpr();
  3478. // A string literal (2.13.4) that is not a wide string literal can
  3479. // be converted to an rvalue of type "pointer to char"; a wide
  3480. // string literal can be converted to an rvalue of type "pointer
  3481. // to wchar_t" (C++ 4.2p2).
  3482. if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
  3483. if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
  3484. if (const BuiltinType *ToPointeeType
  3485. = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
  3486. // This conversion is considered only when there is an
  3487. // explicit appropriate pointer target type (C++ 4.2p2).
  3488. if (!ToPtrType->getPointeeType().hasQualifiers()) {
  3489. switch (StrLit->getKind()) {
  3490. case StringLiteral::UTF8:
  3491. case StringLiteral::UTF16:
  3492. case StringLiteral::UTF32:
  3493. // We don't allow UTF literals to be implicitly converted
  3494. break;
  3495. case StringLiteral::Ascii:
  3496. return (ToPointeeType->getKind() == BuiltinType::Char_U ||
  3497. ToPointeeType->getKind() == BuiltinType::Char_S);
  3498. case StringLiteral::Wide:
  3499. return Context.typesAreCompatible(Context.getWideCharType(),
  3500. QualType(ToPointeeType, 0));
  3501. }
  3502. }
  3503. }
  3504. return false;
  3505. }
  3506. static ExprResult BuildCXXCastArgument(Sema &S,
  3507. SourceLocation CastLoc,
  3508. QualType Ty,
  3509. CastKind Kind,
  3510. CXXMethodDecl *Method,
  3511. DeclAccessPair FoundDecl,
  3512. bool HadMultipleCandidates,
  3513. Expr *From) {
  3514. switch (Kind) {
  3515. default: llvm_unreachable("Unhandled cast kind!");
  3516. case CK_ConstructorConversion: {
  3517. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
  3518. SmallVector<Expr*, 8> ConstructorArgs;
  3519. if (S.RequireNonAbstractType(CastLoc, Ty,
  3520. diag::err_allocation_of_abstract_type))
  3521. return ExprError();
  3522. if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
  3523. ConstructorArgs))
  3524. return ExprError();
  3525. S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
  3526. InitializedEntity::InitializeTemporary(Ty));
  3527. if (S.DiagnoseUseOfDecl(Method, CastLoc))
  3528. return ExprError();
  3529. ExprResult Result = S.BuildCXXConstructExpr(
  3530. CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
  3531. ConstructorArgs, HadMultipleCandidates,
  3532. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  3533. CXXConstructExpr::CK_Complete, SourceRange());
  3534. if (Result.isInvalid())
  3535. return ExprError();
  3536. return S.MaybeBindToTemporary(Result.getAs<Expr>());
  3537. }
  3538. case CK_UserDefinedConversion: {
  3539. assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
  3540. S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
  3541. if (S.DiagnoseUseOfDecl(Method, CastLoc))
  3542. return ExprError();
  3543. // Create an implicit call expr that calls it.
  3544. CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
  3545. ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
  3546. HadMultipleCandidates);
  3547. if (Result.isInvalid())
  3548. return ExprError();
  3549. // Record usage of conversion in an implicit cast.
  3550. Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
  3551. CK_UserDefinedConversion, Result.get(),
  3552. nullptr, Result.get()->getValueKind(),
  3553. S.CurFPFeatureOverrides());
  3554. return S.MaybeBindToTemporary(Result.get());
  3555. }
  3556. }
  3557. }
  3558. /// PerformImplicitConversion - Perform an implicit conversion of the
  3559. /// expression From to the type ToType using the pre-computed implicit
  3560. /// conversion sequence ICS. Returns the converted
  3561. /// expression. Action is the kind of conversion we're performing,
  3562. /// used in the error message.
  3563. ExprResult
  3564. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  3565. const ImplicitConversionSequence &ICS,
  3566. AssignmentAction Action,
  3567. CheckedConversionKind CCK) {
  3568. // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
  3569. if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
  3570. return From;
  3571. switch (ICS.getKind()) {
  3572. case ImplicitConversionSequence::StandardConversion: {
  3573. ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
  3574. Action, CCK);
  3575. if (Res.isInvalid())
  3576. return ExprError();
  3577. From = Res.get();
  3578. break;
  3579. }
  3580. case ImplicitConversionSequence::UserDefinedConversion: {
  3581. FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
  3582. CastKind CastKind;
  3583. QualType BeforeToType;
  3584. assert(FD && "no conversion function for user-defined conversion seq");
  3585. if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
  3586. CastKind = CK_UserDefinedConversion;
  3587. // If the user-defined conversion is specified by a conversion function,
  3588. // the initial standard conversion sequence converts the source type to
  3589. // the implicit object parameter of the conversion function.
  3590. BeforeToType = Context.getTagDeclType(Conv->getParent());
  3591. } else {
  3592. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
  3593. CastKind = CK_ConstructorConversion;
  3594. // Do no conversion if dealing with ... for the first conversion.
  3595. if (!ICS.UserDefined.EllipsisConversion) {
  3596. // If the user-defined conversion is specified by a constructor, the
  3597. // initial standard conversion sequence converts the source type to
  3598. // the type required by the argument of the constructor
  3599. BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
  3600. }
  3601. }
  3602. // Watch out for ellipsis conversion.
  3603. if (!ICS.UserDefined.EllipsisConversion) {
  3604. ExprResult Res =
  3605. PerformImplicitConversion(From, BeforeToType,
  3606. ICS.UserDefined.Before, AA_Converting,
  3607. CCK);
  3608. if (Res.isInvalid())
  3609. return ExprError();
  3610. From = Res.get();
  3611. }
  3612. ExprResult CastArg = BuildCXXCastArgument(
  3613. *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
  3614. cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
  3615. ICS.UserDefined.HadMultipleCandidates, From);
  3616. if (CastArg.isInvalid())
  3617. return ExprError();
  3618. From = CastArg.get();
  3619. // C++ [over.match.oper]p7:
  3620. // [...] the second standard conversion sequence of a user-defined
  3621. // conversion sequence is not applied.
  3622. if (CCK == CCK_ForBuiltinOverloadedOp)
  3623. return From;
  3624. return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
  3625. AA_Converting, CCK);
  3626. }
  3627. case ImplicitConversionSequence::AmbiguousConversion:
  3628. ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
  3629. PDiag(diag::err_typecheck_ambiguous_condition)
  3630. << From->getSourceRange());
  3631. return ExprError();
  3632. case ImplicitConversionSequence::EllipsisConversion:
  3633. llvm_unreachable("Cannot perform an ellipsis conversion");
  3634. case ImplicitConversionSequence::BadConversion:
  3635. Sema::AssignConvertType ConvTy =
  3636. CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
  3637. bool Diagnosed = DiagnoseAssignmentResult(
  3638. ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
  3639. ToType, From->getType(), From, Action);
  3640. assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
  3641. return ExprError();
  3642. }
  3643. // Everything went well.
  3644. return From;
  3645. }
  3646. /// PerformImplicitConversion - Perform an implicit conversion of the
  3647. /// expression From to the type ToType by following the standard
  3648. /// conversion sequence SCS. Returns the converted
  3649. /// expression. Flavor is the context in which we're performing this
  3650. /// conversion, for use in error messages.
  3651. ExprResult
  3652. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  3653. const StandardConversionSequence& SCS,
  3654. AssignmentAction Action,
  3655. CheckedConversionKind CCK) {
  3656. bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
  3657. // Overall FIXME: we are recomputing too many types here and doing far too
  3658. // much extra work. What this means is that we need to keep track of more
  3659. // information that is computed when we try the implicit conversion initially,
  3660. // so that we don't need to recompute anything here.
  3661. QualType FromType = From->getType();
  3662. if (SCS.CopyConstructor) {
  3663. // FIXME: When can ToType be a reference type?
  3664. assert(!ToType->isReferenceType());
  3665. if (SCS.Second == ICK_Derived_To_Base) {
  3666. SmallVector<Expr*, 8> ConstructorArgs;
  3667. if (CompleteConstructorCall(
  3668. cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
  3669. /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
  3670. return ExprError();
  3671. return BuildCXXConstructExpr(
  3672. /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
  3673. SCS.FoundCopyConstructor, SCS.CopyConstructor,
  3674. ConstructorArgs, /*HadMultipleCandidates*/ false,
  3675. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  3676. CXXConstructExpr::CK_Complete, SourceRange());
  3677. }
  3678. return BuildCXXConstructExpr(
  3679. /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
  3680. SCS.FoundCopyConstructor, SCS.CopyConstructor,
  3681. From, /*HadMultipleCandidates*/ false,
  3682. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  3683. CXXConstructExpr::CK_Complete, SourceRange());
  3684. }
  3685. // Resolve overloaded function references.
  3686. if (Context.hasSameType(FromType, Context.OverloadTy)) {
  3687. DeclAccessPair Found;
  3688. FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
  3689. true, Found);
  3690. if (!Fn)
  3691. return ExprError();
  3692. if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
  3693. return ExprError();
  3694. From = FixOverloadedFunctionReference(From, Found, Fn);
  3695. FromType = From->getType();
  3696. }
  3697. // If we're converting to an atomic type, first convert to the corresponding
  3698. // non-atomic type.
  3699. QualType ToAtomicType;
  3700. if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
  3701. ToAtomicType = ToType;
  3702. ToType = ToAtomic->getValueType();
  3703. }
  3704. QualType InitialFromType = FromType;
  3705. // Perform the first implicit conversion.
  3706. switch (SCS.First) {
  3707. case ICK_Identity:
  3708. if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
  3709. FromType = FromAtomic->getValueType().getUnqualifiedType();
  3710. From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
  3711. From, /*BasePath=*/nullptr, VK_PRValue,
  3712. FPOptionsOverride());
  3713. }
  3714. break;
  3715. case ICK_Lvalue_To_Rvalue: {
  3716. assert(From->getObjectKind() != OK_ObjCProperty);
  3717. ExprResult FromRes = DefaultLvalueConversion(From);
  3718. if (FromRes.isInvalid())
  3719. return ExprError();
  3720. From = FromRes.get();
  3721. FromType = From->getType();
  3722. break;
  3723. }
  3724. case ICK_Array_To_Pointer:
  3725. FromType = Context.getArrayDecayedType(FromType);
  3726. From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
  3727. /*BasePath=*/nullptr, CCK)
  3728. .get();
  3729. break;
  3730. case ICK_Function_To_Pointer:
  3731. FromType = Context.getPointerType(FromType);
  3732. From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
  3733. VK_PRValue, /*BasePath=*/nullptr, CCK)
  3734. .get();
  3735. break;
  3736. default:
  3737. llvm_unreachable("Improper first standard conversion");
  3738. }
  3739. // Perform the second implicit conversion
  3740. switch (SCS.Second) {
  3741. case ICK_Identity:
  3742. // C++ [except.spec]p5:
  3743. // [For] assignment to and initialization of pointers to functions,
  3744. // pointers to member functions, and references to functions: the
  3745. // target entity shall allow at least the exceptions allowed by the
  3746. // source value in the assignment or initialization.
  3747. switch (Action) {
  3748. case AA_Assigning:
  3749. case AA_Initializing:
  3750. // Note, function argument passing and returning are initialization.
  3751. case AA_Passing:
  3752. case AA_Returning:
  3753. case AA_Sending:
  3754. case AA_Passing_CFAudited:
  3755. if (CheckExceptionSpecCompatibility(From, ToType))
  3756. return ExprError();
  3757. break;
  3758. case AA_Casting:
  3759. case AA_Converting:
  3760. // Casts and implicit conversions are not initialization, so are not
  3761. // checked for exception specification mismatches.
  3762. break;
  3763. }
  3764. // Nothing else to do.
  3765. break;
  3766. case ICK_Integral_Promotion:
  3767. case ICK_Integral_Conversion:
  3768. if (ToType->isBooleanType()) {
  3769. assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
  3770. SCS.Second == ICK_Integral_Promotion &&
  3771. "only enums with fixed underlying type can promote to bool");
  3772. From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
  3773. /*BasePath=*/nullptr, CCK)
  3774. .get();
  3775. } else {
  3776. From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
  3777. /*BasePath=*/nullptr, CCK)
  3778. .get();
  3779. }
  3780. break;
  3781. case ICK_Floating_Promotion:
  3782. case ICK_Floating_Conversion:
  3783. From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
  3784. /*BasePath=*/nullptr, CCK)
  3785. .get();
  3786. break;
  3787. case ICK_Complex_Promotion:
  3788. case ICK_Complex_Conversion: {
  3789. QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
  3790. QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
  3791. CastKind CK;
  3792. if (FromEl->isRealFloatingType()) {
  3793. if (ToEl->isRealFloatingType())
  3794. CK = CK_FloatingComplexCast;
  3795. else
  3796. CK = CK_FloatingComplexToIntegralComplex;
  3797. } else if (ToEl->isRealFloatingType()) {
  3798. CK = CK_IntegralComplexToFloatingComplex;
  3799. } else {
  3800. CK = CK_IntegralComplexCast;
  3801. }
  3802. From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
  3803. CCK)
  3804. .get();
  3805. break;
  3806. }
  3807. case ICK_Floating_Integral:
  3808. if (ToType->isRealFloatingType())
  3809. From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
  3810. /*BasePath=*/nullptr, CCK)
  3811. .get();
  3812. else
  3813. From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
  3814. /*BasePath=*/nullptr, CCK)
  3815. .get();
  3816. break;
  3817. case ICK_Compatible_Conversion:
  3818. From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
  3819. /*BasePath=*/nullptr, CCK).get();
  3820. break;
  3821. case ICK_Writeback_Conversion:
  3822. case ICK_Pointer_Conversion: {
  3823. if (SCS.IncompatibleObjC && Action != AA_Casting) {
  3824. // Diagnose incompatible Objective-C conversions
  3825. if (Action == AA_Initializing || Action == AA_Assigning)
  3826. Diag(From->getBeginLoc(),
  3827. diag::ext_typecheck_convert_incompatible_pointer)
  3828. << ToType << From->getType() << Action << From->getSourceRange()
  3829. << 0;
  3830. else
  3831. Diag(From->getBeginLoc(),
  3832. diag::ext_typecheck_convert_incompatible_pointer)
  3833. << From->getType() << ToType << Action << From->getSourceRange()
  3834. << 0;
  3835. if (From->getType()->isObjCObjectPointerType() &&
  3836. ToType->isObjCObjectPointerType())
  3837. EmitRelatedResultTypeNote(From);
  3838. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  3839. !CheckObjCARCUnavailableWeakConversion(ToType,
  3840. From->getType())) {
  3841. if (Action == AA_Initializing)
  3842. Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
  3843. else
  3844. Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
  3845. << (Action == AA_Casting) << From->getType() << ToType
  3846. << From->getSourceRange();
  3847. }
  3848. // Defer address space conversion to the third conversion.
  3849. QualType FromPteeType = From->getType()->getPointeeType();
  3850. QualType ToPteeType = ToType->getPointeeType();
  3851. QualType NewToType = ToType;
  3852. if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
  3853. FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
  3854. NewToType = Context.removeAddrSpaceQualType(ToPteeType);
  3855. NewToType = Context.getAddrSpaceQualType(NewToType,
  3856. FromPteeType.getAddressSpace());
  3857. if (ToType->isObjCObjectPointerType())
  3858. NewToType = Context.getObjCObjectPointerType(NewToType);
  3859. else if (ToType->isBlockPointerType())
  3860. NewToType = Context.getBlockPointerType(NewToType);
  3861. else
  3862. NewToType = Context.getPointerType(NewToType);
  3863. }
  3864. CastKind Kind;
  3865. CXXCastPath BasePath;
  3866. if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
  3867. return ExprError();
  3868. // Make sure we extend blocks if necessary.
  3869. // FIXME: doing this here is really ugly.
  3870. if (Kind == CK_BlockPointerToObjCPointerCast) {
  3871. ExprResult E = From;
  3872. (void) PrepareCastToObjCObjectPointer(E);
  3873. From = E.get();
  3874. }
  3875. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
  3876. CheckObjCConversion(SourceRange(), NewToType, From, CCK);
  3877. From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
  3878. .get();
  3879. break;
  3880. }
  3881. case ICK_Pointer_Member: {
  3882. CastKind Kind;
  3883. CXXCastPath BasePath;
  3884. if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
  3885. return ExprError();
  3886. if (CheckExceptionSpecCompatibility(From, ToType))
  3887. return ExprError();
  3888. // We may not have been able to figure out what this member pointer resolved
  3889. // to up until this exact point. Attempt to lock-in it's inheritance model.
  3890. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  3891. (void)isCompleteType(From->getExprLoc(), From->getType());
  3892. (void)isCompleteType(From->getExprLoc(), ToType);
  3893. }
  3894. From =
  3895. ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
  3896. break;
  3897. }
  3898. case ICK_Boolean_Conversion:
  3899. // Perform half-to-boolean conversion via float.
  3900. if (From->getType()->isHalfType()) {
  3901. From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
  3902. FromType = Context.FloatTy;
  3903. }
  3904. From = ImpCastExprToType(From, Context.BoolTy,
  3905. ScalarTypeToBooleanCastKind(FromType), VK_PRValue,
  3906. /*BasePath=*/nullptr, CCK)
  3907. .get();
  3908. break;
  3909. case ICK_Derived_To_Base: {
  3910. CXXCastPath BasePath;
  3911. if (CheckDerivedToBaseConversion(
  3912. From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
  3913. From->getSourceRange(), &BasePath, CStyle))
  3914. return ExprError();
  3915. From = ImpCastExprToType(From, ToType.getNonReferenceType(),
  3916. CK_DerivedToBase, From->getValueKind(),
  3917. &BasePath, CCK).get();
  3918. break;
  3919. }
  3920. case ICK_Vector_Conversion:
  3921. From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
  3922. /*BasePath=*/nullptr, CCK)
  3923. .get();
  3924. break;
  3925. case ICK_SVE_Vector_Conversion:
  3926. From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
  3927. /*BasePath=*/nullptr, CCK)
  3928. .get();
  3929. break;
  3930. case ICK_Vector_Splat: {
  3931. // Vector splat from any arithmetic type to a vector.
  3932. Expr *Elem = prepareVectorSplat(ToType, From).get();
  3933. From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
  3934. /*BasePath=*/nullptr, CCK)
  3935. .get();
  3936. break;
  3937. }
  3938. case ICK_Complex_Real:
  3939. // Case 1. x -> _Complex y
  3940. if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
  3941. QualType ElType = ToComplex->getElementType();
  3942. bool isFloatingComplex = ElType->isRealFloatingType();
  3943. // x -> y
  3944. if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
  3945. // do nothing
  3946. } else if (From->getType()->isRealFloatingType()) {
  3947. From = ImpCastExprToType(From, ElType,
  3948. isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
  3949. } else {
  3950. assert(From->getType()->isIntegerType());
  3951. From = ImpCastExprToType(From, ElType,
  3952. isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
  3953. }
  3954. // y -> _Complex y
  3955. From = ImpCastExprToType(From, ToType,
  3956. isFloatingComplex ? CK_FloatingRealToComplex
  3957. : CK_IntegralRealToComplex).get();
  3958. // Case 2. _Complex x -> y
  3959. } else {
  3960. auto *FromComplex = From->getType()->castAs<ComplexType>();
  3961. QualType ElType = FromComplex->getElementType();
  3962. bool isFloatingComplex = ElType->isRealFloatingType();
  3963. // _Complex x -> x
  3964. From = ImpCastExprToType(From, ElType,
  3965. isFloatingComplex ? CK_FloatingComplexToReal
  3966. : CK_IntegralComplexToReal,
  3967. VK_PRValue, /*BasePath=*/nullptr, CCK)
  3968. .get();
  3969. // x -> y
  3970. if (Context.hasSameUnqualifiedType(ElType, ToType)) {
  3971. // do nothing
  3972. } else if (ToType->isRealFloatingType()) {
  3973. From = ImpCastExprToType(From, ToType,
  3974. isFloatingComplex ? CK_FloatingCast
  3975. : CK_IntegralToFloating,
  3976. VK_PRValue, /*BasePath=*/nullptr, CCK)
  3977. .get();
  3978. } else {
  3979. assert(ToType->isIntegerType());
  3980. From = ImpCastExprToType(From, ToType,
  3981. isFloatingComplex ? CK_FloatingToIntegral
  3982. : CK_IntegralCast,
  3983. VK_PRValue, /*BasePath=*/nullptr, CCK)
  3984. .get();
  3985. }
  3986. }
  3987. break;
  3988. case ICK_Block_Pointer_Conversion: {
  3989. LangAS AddrSpaceL =
  3990. ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
  3991. LangAS AddrSpaceR =
  3992. FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
  3993. assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
  3994. "Invalid cast");
  3995. CastKind Kind =
  3996. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  3997. From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
  3998. VK_PRValue, /*BasePath=*/nullptr, CCK)
  3999. .get();
  4000. break;
  4001. }
  4002. case ICK_TransparentUnionConversion: {
  4003. ExprResult FromRes = From;
  4004. Sema::AssignConvertType ConvTy =
  4005. CheckTransparentUnionArgumentConstraints(ToType, FromRes);
  4006. if (FromRes.isInvalid())
  4007. return ExprError();
  4008. From = FromRes.get();
  4009. assert ((ConvTy == Sema::Compatible) &&
  4010. "Improper transparent union conversion");
  4011. (void)ConvTy;
  4012. break;
  4013. }
  4014. case ICK_Zero_Event_Conversion:
  4015. case ICK_Zero_Queue_Conversion:
  4016. From = ImpCastExprToType(From, ToType,
  4017. CK_ZeroToOCLOpaqueType,
  4018. From->getValueKind()).get();
  4019. break;
  4020. case ICK_Lvalue_To_Rvalue:
  4021. case ICK_Array_To_Pointer:
  4022. case ICK_Function_To_Pointer:
  4023. case ICK_Function_Conversion:
  4024. case ICK_Qualification:
  4025. case ICK_Num_Conversion_Kinds:
  4026. case ICK_C_Only_Conversion:
  4027. case ICK_Incompatible_Pointer_Conversion:
  4028. llvm_unreachable("Improper second standard conversion");
  4029. }
  4030. switch (SCS.Third) {
  4031. case ICK_Identity:
  4032. // Nothing to do.
  4033. break;
  4034. case ICK_Function_Conversion:
  4035. // If both sides are functions (or pointers/references to them), there could
  4036. // be incompatible exception declarations.
  4037. if (CheckExceptionSpecCompatibility(From, ToType))
  4038. return ExprError();
  4039. From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
  4040. /*BasePath=*/nullptr, CCK)
  4041. .get();
  4042. break;
  4043. case ICK_Qualification: {
  4044. ExprValueKind VK = From->getValueKind();
  4045. CastKind CK = CK_NoOp;
  4046. if (ToType->isReferenceType() &&
  4047. ToType->getPointeeType().getAddressSpace() !=
  4048. From->getType().getAddressSpace())
  4049. CK = CK_AddressSpaceConversion;
  4050. if (ToType->isPointerType() &&
  4051. ToType->getPointeeType().getAddressSpace() !=
  4052. From->getType()->getPointeeType().getAddressSpace())
  4053. CK = CK_AddressSpaceConversion;
  4054. From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
  4055. /*BasePath=*/nullptr, CCK)
  4056. .get();
  4057. if (SCS.DeprecatedStringLiteralToCharPtr &&
  4058. !getLangOpts().WritableStrings) {
  4059. Diag(From->getBeginLoc(),
  4060. getLangOpts().CPlusPlus11
  4061. ? diag::ext_deprecated_string_literal_conversion
  4062. : diag::warn_deprecated_string_literal_conversion)
  4063. << ToType.getNonReferenceType();
  4064. }
  4065. break;
  4066. }
  4067. default:
  4068. llvm_unreachable("Improper third standard conversion");
  4069. }
  4070. // If this conversion sequence involved a scalar -> atomic conversion, perform
  4071. // that conversion now.
  4072. if (!ToAtomicType.isNull()) {
  4073. assert(Context.hasSameType(
  4074. ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
  4075. From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
  4076. VK_PRValue, nullptr, CCK)
  4077. .get();
  4078. }
  4079. // Materialize a temporary if we're implicitly converting to a reference
  4080. // type. This is not required by the C++ rules but is necessary to maintain
  4081. // AST invariants.
  4082. if (ToType->isReferenceType() && From->isPRValue()) {
  4083. ExprResult Res = TemporaryMaterializationConversion(From);
  4084. if (Res.isInvalid())
  4085. return ExprError();
  4086. From = Res.get();
  4087. }
  4088. // If this conversion sequence succeeded and involved implicitly converting a
  4089. // _Nullable type to a _Nonnull one, complain.
  4090. if (!isCast(CCK))
  4091. diagnoseNullableToNonnullConversion(ToType, InitialFromType,
  4092. From->getBeginLoc());
  4093. return From;
  4094. }
  4095. /// Check the completeness of a type in a unary type trait.
  4096. ///
  4097. /// If the particular type trait requires a complete type, tries to complete
  4098. /// it. If completing the type fails, a diagnostic is emitted and false
  4099. /// returned. If completing the type succeeds or no completion was required,
  4100. /// returns true.
  4101. static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
  4102. SourceLocation Loc,
  4103. QualType ArgTy) {
  4104. // C++0x [meta.unary.prop]p3:
  4105. // For all of the class templates X declared in this Clause, instantiating
  4106. // that template with a template argument that is a class template
  4107. // specialization may result in the implicit instantiation of the template
  4108. // argument if and only if the semantics of X require that the argument
  4109. // must be a complete type.
  4110. // We apply this rule to all the type trait expressions used to implement
  4111. // these class templates. We also try to follow any GCC documented behavior
  4112. // in these expressions to ensure portability of standard libraries.
  4113. switch (UTT) {
  4114. default: llvm_unreachable("not a UTT");
  4115. // is_complete_type somewhat obviously cannot require a complete type.
  4116. case UTT_IsCompleteType:
  4117. // Fall-through
  4118. // These traits are modeled on the type predicates in C++0x
  4119. // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
  4120. // requiring a complete type, as whether or not they return true cannot be
  4121. // impacted by the completeness of the type.
  4122. case UTT_IsVoid:
  4123. case UTT_IsIntegral:
  4124. case UTT_IsFloatingPoint:
  4125. case UTT_IsArray:
  4126. case UTT_IsPointer:
  4127. case UTT_IsLvalueReference:
  4128. case UTT_IsRvalueReference:
  4129. case UTT_IsMemberFunctionPointer:
  4130. case UTT_IsMemberObjectPointer:
  4131. case UTT_IsEnum:
  4132. case UTT_IsUnion:
  4133. case UTT_IsClass:
  4134. case UTT_IsFunction:
  4135. case UTT_IsReference:
  4136. case UTT_IsArithmetic:
  4137. case UTT_IsFundamental:
  4138. case UTT_IsObject:
  4139. case UTT_IsScalar:
  4140. case UTT_IsCompound:
  4141. case UTT_IsMemberPointer:
  4142. // Fall-through
  4143. // These traits are modeled on type predicates in C++0x [meta.unary.prop]
  4144. // which requires some of its traits to have the complete type. However,
  4145. // the completeness of the type cannot impact these traits' semantics, and
  4146. // so they don't require it. This matches the comments on these traits in
  4147. // Table 49.
  4148. case UTT_IsConst:
  4149. case UTT_IsVolatile:
  4150. case UTT_IsSigned:
  4151. case UTT_IsUnsigned:
  4152. // This type trait always returns false, checking the type is moot.
  4153. case UTT_IsInterfaceClass:
  4154. return true;
  4155. // C++14 [meta.unary.prop]:
  4156. // If T is a non-union class type, T shall be a complete type.
  4157. case UTT_IsEmpty:
  4158. case UTT_IsPolymorphic:
  4159. case UTT_IsAbstract:
  4160. if (const auto *RD = ArgTy->getAsCXXRecordDecl())
  4161. if (!RD->isUnion())
  4162. return !S.RequireCompleteType(
  4163. Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
  4164. return true;
  4165. // C++14 [meta.unary.prop]:
  4166. // If T is a class type, T shall be a complete type.
  4167. case UTT_IsFinal:
  4168. case UTT_IsSealed:
  4169. if (ArgTy->getAsCXXRecordDecl())
  4170. return !S.RequireCompleteType(
  4171. Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
  4172. return true;
  4173. // C++1z [meta.unary.prop]:
  4174. // remove_all_extents_t<T> shall be a complete type or cv void.
  4175. case UTT_IsAggregate:
  4176. case UTT_IsTrivial:
  4177. case UTT_IsTriviallyCopyable:
  4178. case UTT_IsStandardLayout:
  4179. case UTT_IsPOD:
  4180. case UTT_IsLiteral:
  4181. // Per the GCC type traits documentation, T shall be a complete type, cv void,
  4182. // or an array of unknown bound. But GCC actually imposes the same constraints
  4183. // as above.
  4184. case UTT_HasNothrowAssign:
  4185. case UTT_HasNothrowMoveAssign:
  4186. case UTT_HasNothrowConstructor:
  4187. case UTT_HasNothrowCopy:
  4188. case UTT_HasTrivialAssign:
  4189. case UTT_HasTrivialMoveAssign:
  4190. case UTT_HasTrivialDefaultConstructor:
  4191. case UTT_HasTrivialMoveConstructor:
  4192. case UTT_HasTrivialCopy:
  4193. case UTT_HasTrivialDestructor:
  4194. case UTT_HasVirtualDestructor:
  4195. ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
  4196. LLVM_FALLTHROUGH;
  4197. // C++1z [meta.unary.prop]:
  4198. // T shall be a complete type, cv void, or an array of unknown bound.
  4199. case UTT_IsDestructible:
  4200. case UTT_IsNothrowDestructible:
  4201. case UTT_IsTriviallyDestructible:
  4202. case UTT_HasUniqueObjectRepresentations:
  4203. if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
  4204. return true;
  4205. return !S.RequireCompleteType(
  4206. Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
  4207. }
  4208. }
  4209. static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
  4210. Sema &Self, SourceLocation KeyLoc, ASTContext &C,
  4211. bool (CXXRecordDecl::*HasTrivial)() const,
  4212. bool (CXXRecordDecl::*HasNonTrivial)() const,
  4213. bool (CXXMethodDecl::*IsDesiredOp)() const)
  4214. {
  4215. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  4216. if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
  4217. return true;
  4218. DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
  4219. DeclarationNameInfo NameInfo(Name, KeyLoc);
  4220. LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
  4221. if (Self.LookupQualifiedName(Res, RD)) {
  4222. bool FoundOperator = false;
  4223. Res.suppressDiagnostics();
  4224. for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
  4225. Op != OpEnd; ++Op) {
  4226. if (isa<FunctionTemplateDecl>(*Op))
  4227. continue;
  4228. CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
  4229. if((Operator->*IsDesiredOp)()) {
  4230. FoundOperator = true;
  4231. auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
  4232. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  4233. if (!CPT || !CPT->isNothrow())
  4234. return false;
  4235. }
  4236. }
  4237. return FoundOperator;
  4238. }
  4239. return false;
  4240. }
  4241. static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
  4242. SourceLocation KeyLoc, QualType T) {
  4243. assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
  4244. ASTContext &C = Self.Context;
  4245. switch(UTT) {
  4246. default: llvm_unreachable("not a UTT");
  4247. // Type trait expressions corresponding to the primary type category
  4248. // predicates in C++0x [meta.unary.cat].
  4249. case UTT_IsVoid:
  4250. return T->isVoidType();
  4251. case UTT_IsIntegral:
  4252. return T->isIntegralType(C);
  4253. case UTT_IsFloatingPoint:
  4254. return T->isFloatingType();
  4255. case UTT_IsArray:
  4256. return T->isArrayType();
  4257. case UTT_IsPointer:
  4258. return T->isAnyPointerType();
  4259. case UTT_IsLvalueReference:
  4260. return T->isLValueReferenceType();
  4261. case UTT_IsRvalueReference:
  4262. return T->isRValueReferenceType();
  4263. case UTT_IsMemberFunctionPointer:
  4264. return T->isMemberFunctionPointerType();
  4265. case UTT_IsMemberObjectPointer:
  4266. return T->isMemberDataPointerType();
  4267. case UTT_IsEnum:
  4268. return T->isEnumeralType();
  4269. case UTT_IsUnion:
  4270. return T->isUnionType();
  4271. case UTT_IsClass:
  4272. return T->isClassType() || T->isStructureType() || T->isInterfaceType();
  4273. case UTT_IsFunction:
  4274. return T->isFunctionType();
  4275. // Type trait expressions which correspond to the convenient composition
  4276. // predicates in C++0x [meta.unary.comp].
  4277. case UTT_IsReference:
  4278. return T->isReferenceType();
  4279. case UTT_IsArithmetic:
  4280. return T->isArithmeticType() && !T->isEnumeralType();
  4281. case UTT_IsFundamental:
  4282. return T->isFundamentalType();
  4283. case UTT_IsObject:
  4284. return T->isObjectType();
  4285. case UTT_IsScalar:
  4286. // Note: semantic analysis depends on Objective-C lifetime types to be
  4287. // considered scalar types. However, such types do not actually behave
  4288. // like scalar types at run time (since they may require retain/release
  4289. // operations), so we report them as non-scalar.
  4290. if (T->isObjCLifetimeType()) {
  4291. switch (T.getObjCLifetime()) {
  4292. case Qualifiers::OCL_None:
  4293. case Qualifiers::OCL_ExplicitNone:
  4294. return true;
  4295. case Qualifiers::OCL_Strong:
  4296. case Qualifiers::OCL_Weak:
  4297. case Qualifiers::OCL_Autoreleasing:
  4298. return false;
  4299. }
  4300. }
  4301. return T->isScalarType();
  4302. case UTT_IsCompound:
  4303. return T->isCompoundType();
  4304. case UTT_IsMemberPointer:
  4305. return T->isMemberPointerType();
  4306. // Type trait expressions which correspond to the type property predicates
  4307. // in C++0x [meta.unary.prop].
  4308. case UTT_IsConst:
  4309. return T.isConstQualified();
  4310. case UTT_IsVolatile:
  4311. return T.isVolatileQualified();
  4312. case UTT_IsTrivial:
  4313. return T.isTrivialType(C);
  4314. case UTT_IsTriviallyCopyable:
  4315. return T.isTriviallyCopyableType(C);
  4316. case UTT_IsStandardLayout:
  4317. return T->isStandardLayoutType();
  4318. case UTT_IsPOD:
  4319. return T.isPODType(C);
  4320. case UTT_IsLiteral:
  4321. return T->isLiteralType(C);
  4322. case UTT_IsEmpty:
  4323. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4324. return !RD->isUnion() && RD->isEmpty();
  4325. return false;
  4326. case UTT_IsPolymorphic:
  4327. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4328. return !RD->isUnion() && RD->isPolymorphic();
  4329. return false;
  4330. case UTT_IsAbstract:
  4331. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4332. return !RD->isUnion() && RD->isAbstract();
  4333. return false;
  4334. case UTT_IsAggregate:
  4335. // Report vector extensions and complex types as aggregates because they
  4336. // support aggregate initialization. GCC mirrors this behavior for vectors
  4337. // but not _Complex.
  4338. return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
  4339. T->isAnyComplexType();
  4340. // __is_interface_class only returns true when CL is invoked in /CLR mode and
  4341. // even then only when it is used with the 'interface struct ...' syntax
  4342. // Clang doesn't support /CLR which makes this type trait moot.
  4343. case UTT_IsInterfaceClass:
  4344. return false;
  4345. case UTT_IsFinal:
  4346. case UTT_IsSealed:
  4347. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4348. return RD->hasAttr<FinalAttr>();
  4349. return false;
  4350. case UTT_IsSigned:
  4351. // Enum types should always return false.
  4352. // Floating points should always return true.
  4353. return T->isFloatingType() ||
  4354. (T->isSignedIntegerType() && !T->isEnumeralType());
  4355. case UTT_IsUnsigned:
  4356. // Enum types should always return false.
  4357. return T->isUnsignedIntegerType() && !T->isEnumeralType();
  4358. // Type trait expressions which query classes regarding their construction,
  4359. // destruction, and copying. Rather than being based directly on the
  4360. // related type predicates in the standard, they are specified by both
  4361. // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
  4362. // specifications.
  4363. //
  4364. // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
  4365. // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
  4366. //
  4367. // Note that these builtins do not behave as documented in g++: if a class
  4368. // has both a trivial and a non-trivial special member of a particular kind,
  4369. // they return false! For now, we emulate this behavior.
  4370. // FIXME: This appears to be a g++ bug: more complex cases reveal that it
  4371. // does not correctly compute triviality in the presence of multiple special
  4372. // members of the same kind. Revisit this once the g++ bug is fixed.
  4373. case UTT_HasTrivialDefaultConstructor:
  4374. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4375. // If __is_pod (type) is true then the trait is true, else if type is
  4376. // a cv class or union type (or array thereof) with a trivial default
  4377. // constructor ([class.ctor]) then the trait is true, else it is false.
  4378. if (T.isPODType(C))
  4379. return true;
  4380. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  4381. return RD->hasTrivialDefaultConstructor() &&
  4382. !RD->hasNonTrivialDefaultConstructor();
  4383. return false;
  4384. case UTT_HasTrivialMoveConstructor:
  4385. // This trait is implemented by MSVC 2012 and needed to parse the
  4386. // standard library headers. Specifically this is used as the logic
  4387. // behind std::is_trivially_move_constructible (20.9.4.3).
  4388. if (T.isPODType(C))
  4389. return true;
  4390. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  4391. return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
  4392. return false;
  4393. case UTT_HasTrivialCopy:
  4394. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4395. // If __is_pod (type) is true or type is a reference type then
  4396. // the trait is true, else if type is a cv class or union type
  4397. // with a trivial copy constructor ([class.copy]) then the trait
  4398. // is true, else it is false.
  4399. if (T.isPODType(C) || T->isReferenceType())
  4400. return true;
  4401. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4402. return RD->hasTrivialCopyConstructor() &&
  4403. !RD->hasNonTrivialCopyConstructor();
  4404. return false;
  4405. case UTT_HasTrivialMoveAssign:
  4406. // This trait is implemented by MSVC 2012 and needed to parse the
  4407. // standard library headers. Specifically it is used as the logic
  4408. // behind std::is_trivially_move_assignable (20.9.4.3)
  4409. if (T.isPODType(C))
  4410. return true;
  4411. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  4412. return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
  4413. return false;
  4414. case UTT_HasTrivialAssign:
  4415. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4416. // If type is const qualified or is a reference type then the
  4417. // trait is false. Otherwise if __is_pod (type) is true then the
  4418. // trait is true, else if type is a cv class or union type with
  4419. // a trivial copy assignment ([class.copy]) then the trait is
  4420. // true, else it is false.
  4421. // Note: the const and reference restrictions are interesting,
  4422. // given that const and reference members don't prevent a class
  4423. // from having a trivial copy assignment operator (but do cause
  4424. // errors if the copy assignment operator is actually used, q.v.
  4425. // [class.copy]p12).
  4426. if (T.isConstQualified())
  4427. return false;
  4428. if (T.isPODType(C))
  4429. return true;
  4430. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4431. return RD->hasTrivialCopyAssignment() &&
  4432. !RD->hasNonTrivialCopyAssignment();
  4433. return false;
  4434. case UTT_IsDestructible:
  4435. case UTT_IsTriviallyDestructible:
  4436. case UTT_IsNothrowDestructible:
  4437. // C++14 [meta.unary.prop]:
  4438. // For reference types, is_destructible<T>::value is true.
  4439. if (T->isReferenceType())
  4440. return true;
  4441. // Objective-C++ ARC: autorelease types don't require destruction.
  4442. if (T->isObjCLifetimeType() &&
  4443. T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
  4444. return true;
  4445. // C++14 [meta.unary.prop]:
  4446. // For incomplete types and function types, is_destructible<T>::value is
  4447. // false.
  4448. if (T->isIncompleteType() || T->isFunctionType())
  4449. return false;
  4450. // A type that requires destruction (via a non-trivial destructor or ARC
  4451. // lifetime semantics) is not trivially-destructible.
  4452. if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
  4453. return false;
  4454. // C++14 [meta.unary.prop]:
  4455. // For object types and given U equal to remove_all_extents_t<T>, if the
  4456. // expression std::declval<U&>().~U() is well-formed when treated as an
  4457. // unevaluated operand (Clause 5), then is_destructible<T>::value is true
  4458. if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
  4459. CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
  4460. if (!Destructor)
  4461. return false;
  4462. // C++14 [dcl.fct.def.delete]p2:
  4463. // A program that refers to a deleted function implicitly or
  4464. // explicitly, other than to declare it, is ill-formed.
  4465. if (Destructor->isDeleted())
  4466. return false;
  4467. if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
  4468. return false;
  4469. if (UTT == UTT_IsNothrowDestructible) {
  4470. auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
  4471. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  4472. if (!CPT || !CPT->isNothrow())
  4473. return false;
  4474. }
  4475. }
  4476. return true;
  4477. case UTT_HasTrivialDestructor:
  4478. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
  4479. // If __is_pod (type) is true or type is a reference type
  4480. // then the trait is true, else if type is a cv class or union
  4481. // type (or array thereof) with a trivial destructor
  4482. // ([class.dtor]) then the trait is true, else it is
  4483. // false.
  4484. if (T.isPODType(C) || T->isReferenceType())
  4485. return true;
  4486. // Objective-C++ ARC: autorelease types don't require destruction.
  4487. if (T->isObjCLifetimeType() &&
  4488. T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
  4489. return true;
  4490. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  4491. return RD->hasTrivialDestructor();
  4492. return false;
  4493. // TODO: Propagate nothrowness for implicitly declared special members.
  4494. case UTT_HasNothrowAssign:
  4495. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4496. // If type is const qualified or is a reference type then the
  4497. // trait is false. Otherwise if __has_trivial_assign (type)
  4498. // is true then the trait is true, else if type is a cv class
  4499. // or union type with copy assignment operators that are known
  4500. // not to throw an exception then the trait is true, else it is
  4501. // false.
  4502. if (C.getBaseElementType(T).isConstQualified())
  4503. return false;
  4504. if (T->isReferenceType())
  4505. return false;
  4506. if (T.isPODType(C) || T->isObjCLifetimeType())
  4507. return true;
  4508. if (const RecordType *RT = T->getAs<RecordType>())
  4509. return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
  4510. &CXXRecordDecl::hasTrivialCopyAssignment,
  4511. &CXXRecordDecl::hasNonTrivialCopyAssignment,
  4512. &CXXMethodDecl::isCopyAssignmentOperator);
  4513. return false;
  4514. case UTT_HasNothrowMoveAssign:
  4515. // This trait is implemented by MSVC 2012 and needed to parse the
  4516. // standard library headers. Specifically this is used as the logic
  4517. // behind std::is_nothrow_move_assignable (20.9.4.3).
  4518. if (T.isPODType(C))
  4519. return true;
  4520. if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
  4521. return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
  4522. &CXXRecordDecl::hasTrivialMoveAssignment,
  4523. &CXXRecordDecl::hasNonTrivialMoveAssignment,
  4524. &CXXMethodDecl::isMoveAssignmentOperator);
  4525. return false;
  4526. case UTT_HasNothrowCopy:
  4527. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4528. // If __has_trivial_copy (type) is true then the trait is true, else
  4529. // if type is a cv class or union type with copy constructors that are
  4530. // known not to throw an exception then the trait is true, else it is
  4531. // false.
  4532. if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
  4533. return true;
  4534. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  4535. if (RD->hasTrivialCopyConstructor() &&
  4536. !RD->hasNonTrivialCopyConstructor())
  4537. return true;
  4538. bool FoundConstructor = false;
  4539. unsigned FoundTQs;
  4540. for (const auto *ND : Self.LookupConstructors(RD)) {
  4541. // A template constructor is never a copy constructor.
  4542. // FIXME: However, it may actually be selected at the actual overload
  4543. // resolution point.
  4544. if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
  4545. continue;
  4546. // UsingDecl itself is not a constructor
  4547. if (isa<UsingDecl>(ND))
  4548. continue;
  4549. auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
  4550. if (Constructor->isCopyConstructor(FoundTQs)) {
  4551. FoundConstructor = true;
  4552. auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
  4553. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  4554. if (!CPT)
  4555. return false;
  4556. // TODO: check whether evaluating default arguments can throw.
  4557. // For now, we'll be conservative and assume that they can throw.
  4558. if (!CPT->isNothrow() || CPT->getNumParams() > 1)
  4559. return false;
  4560. }
  4561. }
  4562. return FoundConstructor;
  4563. }
  4564. return false;
  4565. case UTT_HasNothrowConstructor:
  4566. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
  4567. // If __has_trivial_constructor (type) is true then the trait is
  4568. // true, else if type is a cv class or union type (or array
  4569. // thereof) with a default constructor that is known not to
  4570. // throw an exception then the trait is true, else it is false.
  4571. if (T.isPODType(C) || T->isObjCLifetimeType())
  4572. return true;
  4573. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
  4574. if (RD->hasTrivialDefaultConstructor() &&
  4575. !RD->hasNonTrivialDefaultConstructor())
  4576. return true;
  4577. bool FoundConstructor = false;
  4578. for (const auto *ND : Self.LookupConstructors(RD)) {
  4579. // FIXME: In C++0x, a constructor template can be a default constructor.
  4580. if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
  4581. continue;
  4582. // UsingDecl itself is not a constructor
  4583. if (isa<UsingDecl>(ND))
  4584. continue;
  4585. auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
  4586. if (Constructor->isDefaultConstructor()) {
  4587. FoundConstructor = true;
  4588. auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
  4589. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  4590. if (!CPT)
  4591. return false;
  4592. // FIXME: check whether evaluating default arguments can throw.
  4593. // For now, we'll be conservative and assume that they can throw.
  4594. if (!CPT->isNothrow() || CPT->getNumParams() > 0)
  4595. return false;
  4596. }
  4597. }
  4598. return FoundConstructor;
  4599. }
  4600. return false;
  4601. case UTT_HasVirtualDestructor:
  4602. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4603. // If type is a class type with a virtual destructor ([class.dtor])
  4604. // then the trait is true, else it is false.
  4605. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4606. if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
  4607. return Destructor->isVirtual();
  4608. return false;
  4609. // These type trait expressions are modeled on the specifications for the
  4610. // Embarcadero C++0x type trait functions:
  4611. // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
  4612. case UTT_IsCompleteType:
  4613. // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
  4614. // Returns True if and only if T is a complete type at the point of the
  4615. // function call.
  4616. return !T->isIncompleteType();
  4617. case UTT_HasUniqueObjectRepresentations:
  4618. return C.hasUniqueObjectRepresentations(T);
  4619. }
  4620. }
  4621. static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
  4622. QualType RhsT, SourceLocation KeyLoc);
  4623. static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
  4624. ArrayRef<TypeSourceInfo *> Args,
  4625. SourceLocation RParenLoc) {
  4626. if (Kind <= UTT_Last)
  4627. return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
  4628. // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
  4629. // traits to avoid duplication.
  4630. if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
  4631. return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
  4632. Args[1]->getType(), RParenLoc);
  4633. switch (Kind) {
  4634. case clang::BTT_ReferenceBindsToTemporary:
  4635. case clang::TT_IsConstructible:
  4636. case clang::TT_IsNothrowConstructible:
  4637. case clang::TT_IsTriviallyConstructible: {
  4638. // C++11 [meta.unary.prop]:
  4639. // is_trivially_constructible is defined as:
  4640. //
  4641. // is_constructible<T, Args...>::value is true and the variable
  4642. // definition for is_constructible, as defined below, is known to call
  4643. // no operation that is not trivial.
  4644. //
  4645. // The predicate condition for a template specialization
  4646. // is_constructible<T, Args...> shall be satisfied if and only if the
  4647. // following variable definition would be well-formed for some invented
  4648. // variable t:
  4649. //
  4650. // T t(create<Args>()...);
  4651. assert(!Args.empty());
  4652. // Precondition: T and all types in the parameter pack Args shall be
  4653. // complete types, (possibly cv-qualified) void, or arrays of
  4654. // unknown bound.
  4655. for (const auto *TSI : Args) {
  4656. QualType ArgTy = TSI->getType();
  4657. if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
  4658. continue;
  4659. if (S.RequireCompleteType(KWLoc, ArgTy,
  4660. diag::err_incomplete_type_used_in_type_trait_expr))
  4661. return false;
  4662. }
  4663. // Make sure the first argument is not incomplete nor a function type.
  4664. QualType T = Args[0]->getType();
  4665. if (T->isIncompleteType() || T->isFunctionType())
  4666. return false;
  4667. // Make sure the first argument is not an abstract type.
  4668. CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  4669. if (RD && RD->isAbstract())
  4670. return false;
  4671. llvm::BumpPtrAllocator OpaqueExprAllocator;
  4672. SmallVector<Expr *, 2> ArgExprs;
  4673. ArgExprs.reserve(Args.size() - 1);
  4674. for (unsigned I = 1, N = Args.size(); I != N; ++I) {
  4675. QualType ArgTy = Args[I]->getType();
  4676. if (ArgTy->isObjectType() || ArgTy->isFunctionType())
  4677. ArgTy = S.Context.getRValueReferenceType(ArgTy);
  4678. ArgExprs.push_back(
  4679. new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
  4680. OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
  4681. ArgTy.getNonLValueExprType(S.Context),
  4682. Expr::getValueKindForType(ArgTy)));
  4683. }
  4684. // Perform the initialization in an unevaluated context within a SFINAE
  4685. // trap at translation unit scope.
  4686. EnterExpressionEvaluationContext Unevaluated(
  4687. S, Sema::ExpressionEvaluationContext::Unevaluated);
  4688. Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
  4689. Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
  4690. InitializedEntity To(
  4691. InitializedEntity::InitializeTemporary(S.Context, Args[0]));
  4692. InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
  4693. RParenLoc));
  4694. InitializationSequence Init(S, To, InitKind, ArgExprs);
  4695. if (Init.Failed())
  4696. return false;
  4697. ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
  4698. if (Result.isInvalid() || SFINAE.hasErrorOccurred())
  4699. return false;
  4700. if (Kind == clang::TT_IsConstructible)
  4701. return true;
  4702. if (Kind == clang::BTT_ReferenceBindsToTemporary) {
  4703. if (!T->isReferenceType())
  4704. return false;
  4705. return !Init.isDirectReferenceBinding();
  4706. }
  4707. if (Kind == clang::TT_IsNothrowConstructible)
  4708. return S.canThrow(Result.get()) == CT_Cannot;
  4709. if (Kind == clang::TT_IsTriviallyConstructible) {
  4710. // Under Objective-C ARC and Weak, if the destination has non-trivial
  4711. // Objective-C lifetime, this is a non-trivial construction.
  4712. if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
  4713. return false;
  4714. // The initialization succeeded; now make sure there are no non-trivial
  4715. // calls.
  4716. return !Result.get()->hasNonTrivialCall(S.Context);
  4717. }
  4718. llvm_unreachable("unhandled type trait");
  4719. return false;
  4720. }
  4721. default: llvm_unreachable("not a TT");
  4722. }
  4723. return false;
  4724. }
  4725. ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
  4726. ArrayRef<TypeSourceInfo *> Args,
  4727. SourceLocation RParenLoc) {
  4728. QualType ResultType = Context.getLogicalOperationType();
  4729. if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
  4730. *this, Kind, KWLoc, Args[0]->getType()))
  4731. return ExprError();
  4732. bool Dependent = false;
  4733. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  4734. if (Args[I]->getType()->isDependentType()) {
  4735. Dependent = true;
  4736. break;
  4737. }
  4738. }
  4739. bool Result = false;
  4740. if (!Dependent)
  4741. Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
  4742. return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
  4743. RParenLoc, Result);
  4744. }
  4745. ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
  4746. ArrayRef<ParsedType> Args,
  4747. SourceLocation RParenLoc) {
  4748. SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
  4749. ConvertedArgs.reserve(Args.size());
  4750. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  4751. TypeSourceInfo *TInfo;
  4752. QualType T = GetTypeFromParser(Args[I], &TInfo);
  4753. if (!TInfo)
  4754. TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
  4755. ConvertedArgs.push_back(TInfo);
  4756. }
  4757. return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
  4758. }
  4759. static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
  4760. QualType RhsT, SourceLocation KeyLoc) {
  4761. assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
  4762. "Cannot evaluate traits of dependent types");
  4763. switch(BTT) {
  4764. case BTT_IsBaseOf: {
  4765. // C++0x [meta.rel]p2
  4766. // Base is a base class of Derived without regard to cv-qualifiers or
  4767. // Base and Derived are not unions and name the same class type without
  4768. // regard to cv-qualifiers.
  4769. const RecordType *lhsRecord = LhsT->getAs<RecordType>();
  4770. const RecordType *rhsRecord = RhsT->getAs<RecordType>();
  4771. if (!rhsRecord || !lhsRecord) {
  4772. const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
  4773. const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
  4774. if (!LHSObjTy || !RHSObjTy)
  4775. return false;
  4776. ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
  4777. ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
  4778. if (!BaseInterface || !DerivedInterface)
  4779. return false;
  4780. if (Self.RequireCompleteType(
  4781. KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
  4782. return false;
  4783. return BaseInterface->isSuperClassOf(DerivedInterface);
  4784. }
  4785. assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
  4786. == (lhsRecord == rhsRecord));
  4787. // Unions are never base classes, and never have base classes.
  4788. // It doesn't matter if they are complete or not. See PR#41843
  4789. if (lhsRecord && lhsRecord->getDecl()->isUnion())
  4790. return false;
  4791. if (rhsRecord && rhsRecord->getDecl()->isUnion())
  4792. return false;
  4793. if (lhsRecord == rhsRecord)
  4794. return true;
  4795. // C++0x [meta.rel]p2:
  4796. // If Base and Derived are class types and are different types
  4797. // (ignoring possible cv-qualifiers) then Derived shall be a
  4798. // complete type.
  4799. if (Self.RequireCompleteType(KeyLoc, RhsT,
  4800. diag::err_incomplete_type_used_in_type_trait_expr))
  4801. return false;
  4802. return cast<CXXRecordDecl>(rhsRecord->getDecl())
  4803. ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
  4804. }
  4805. case BTT_IsSame:
  4806. return Self.Context.hasSameType(LhsT, RhsT);
  4807. case BTT_TypeCompatible: {
  4808. // GCC ignores cv-qualifiers on arrays for this builtin.
  4809. Qualifiers LhsQuals, RhsQuals;
  4810. QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
  4811. QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
  4812. return Self.Context.typesAreCompatible(Lhs, Rhs);
  4813. }
  4814. case BTT_IsConvertible:
  4815. case BTT_IsConvertibleTo: {
  4816. // C++0x [meta.rel]p4:
  4817. // Given the following function prototype:
  4818. //
  4819. // template <class T>
  4820. // typename add_rvalue_reference<T>::type create();
  4821. //
  4822. // the predicate condition for a template specialization
  4823. // is_convertible<From, To> shall be satisfied if and only if
  4824. // the return expression in the following code would be
  4825. // well-formed, including any implicit conversions to the return
  4826. // type of the function:
  4827. //
  4828. // To test() {
  4829. // return create<From>();
  4830. // }
  4831. //
  4832. // Access checking is performed as if in a context unrelated to To and
  4833. // From. Only the validity of the immediate context of the expression
  4834. // of the return-statement (including conversions to the return type)
  4835. // is considered.
  4836. //
  4837. // We model the initialization as a copy-initialization of a temporary
  4838. // of the appropriate type, which for this expression is identical to the
  4839. // return statement (since NRVO doesn't apply).
  4840. // Functions aren't allowed to return function or array types.
  4841. if (RhsT->isFunctionType() || RhsT->isArrayType())
  4842. return false;
  4843. // A return statement in a void function must have void type.
  4844. if (RhsT->isVoidType())
  4845. return LhsT->isVoidType();
  4846. // A function definition requires a complete, non-abstract return type.
  4847. if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
  4848. return false;
  4849. // Compute the result of add_rvalue_reference.
  4850. if (LhsT->isObjectType() || LhsT->isFunctionType())
  4851. LhsT = Self.Context.getRValueReferenceType(LhsT);
  4852. // Build a fake source and destination for initialization.
  4853. InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
  4854. OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
  4855. Expr::getValueKindForType(LhsT));
  4856. Expr *FromPtr = &From;
  4857. InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
  4858. SourceLocation()));
  4859. // Perform the initialization in an unevaluated context within a SFINAE
  4860. // trap at translation unit scope.
  4861. EnterExpressionEvaluationContext Unevaluated(
  4862. Self, Sema::ExpressionEvaluationContext::Unevaluated);
  4863. Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
  4864. Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
  4865. InitializationSequence Init(Self, To, Kind, FromPtr);
  4866. if (Init.Failed())
  4867. return false;
  4868. ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
  4869. return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
  4870. }
  4871. case BTT_IsAssignable:
  4872. case BTT_IsNothrowAssignable:
  4873. case BTT_IsTriviallyAssignable: {
  4874. // C++11 [meta.unary.prop]p3:
  4875. // is_trivially_assignable is defined as:
  4876. // is_assignable<T, U>::value is true and the assignment, as defined by
  4877. // is_assignable, is known to call no operation that is not trivial
  4878. //
  4879. // is_assignable is defined as:
  4880. // The expression declval<T>() = declval<U>() is well-formed when
  4881. // treated as an unevaluated operand (Clause 5).
  4882. //
  4883. // For both, T and U shall be complete types, (possibly cv-qualified)
  4884. // void, or arrays of unknown bound.
  4885. if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
  4886. Self.RequireCompleteType(KeyLoc, LhsT,
  4887. diag::err_incomplete_type_used_in_type_trait_expr))
  4888. return false;
  4889. if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
  4890. Self.RequireCompleteType(KeyLoc, RhsT,
  4891. diag::err_incomplete_type_used_in_type_trait_expr))
  4892. return false;
  4893. // cv void is never assignable.
  4894. if (LhsT->isVoidType() || RhsT->isVoidType())
  4895. return false;
  4896. // Build expressions that emulate the effect of declval<T>() and
  4897. // declval<U>().
  4898. if (LhsT->isObjectType() || LhsT->isFunctionType())
  4899. LhsT = Self.Context.getRValueReferenceType(LhsT);
  4900. if (RhsT->isObjectType() || RhsT->isFunctionType())
  4901. RhsT = Self.Context.getRValueReferenceType(RhsT);
  4902. OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
  4903. Expr::getValueKindForType(LhsT));
  4904. OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
  4905. Expr::getValueKindForType(RhsT));
  4906. // Attempt the assignment in an unevaluated context within a SFINAE
  4907. // trap at translation unit scope.
  4908. EnterExpressionEvaluationContext Unevaluated(
  4909. Self, Sema::ExpressionEvaluationContext::Unevaluated);
  4910. Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
  4911. Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
  4912. ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
  4913. &Rhs);
  4914. if (Result.isInvalid())
  4915. return false;
  4916. // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
  4917. Self.CheckUnusedVolatileAssignment(Result.get());
  4918. if (SFINAE.hasErrorOccurred())
  4919. return false;
  4920. if (BTT == BTT_IsAssignable)
  4921. return true;
  4922. if (BTT == BTT_IsNothrowAssignable)
  4923. return Self.canThrow(Result.get()) == CT_Cannot;
  4924. if (BTT == BTT_IsTriviallyAssignable) {
  4925. // Under Objective-C ARC and Weak, if the destination has non-trivial
  4926. // Objective-C lifetime, this is a non-trivial assignment.
  4927. if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
  4928. return false;
  4929. return !Result.get()->hasNonTrivialCall(Self.Context);
  4930. }
  4931. llvm_unreachable("unhandled type trait");
  4932. return false;
  4933. }
  4934. default: llvm_unreachable("not a BTT");
  4935. }
  4936. llvm_unreachable("Unknown type trait or not implemented");
  4937. }
  4938. ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
  4939. SourceLocation KWLoc,
  4940. ParsedType Ty,
  4941. Expr* DimExpr,
  4942. SourceLocation RParen) {
  4943. TypeSourceInfo *TSInfo;
  4944. QualType T = GetTypeFromParser(Ty, &TSInfo);
  4945. if (!TSInfo)
  4946. TSInfo = Context.getTrivialTypeSourceInfo(T);
  4947. return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
  4948. }
  4949. static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
  4950. QualType T, Expr *DimExpr,
  4951. SourceLocation KeyLoc) {
  4952. assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
  4953. switch(ATT) {
  4954. case ATT_ArrayRank:
  4955. if (T->isArrayType()) {
  4956. unsigned Dim = 0;
  4957. while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
  4958. ++Dim;
  4959. T = AT->getElementType();
  4960. }
  4961. return Dim;
  4962. }
  4963. return 0;
  4964. case ATT_ArrayExtent: {
  4965. llvm::APSInt Value;
  4966. uint64_t Dim;
  4967. if (Self.VerifyIntegerConstantExpression(
  4968. DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
  4969. .isInvalid())
  4970. return 0;
  4971. if (Value.isSigned() && Value.isNegative()) {
  4972. Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
  4973. << DimExpr->getSourceRange();
  4974. return 0;
  4975. }
  4976. Dim = Value.getLimitedValue();
  4977. if (T->isArrayType()) {
  4978. unsigned D = 0;
  4979. bool Matched = false;
  4980. while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
  4981. if (Dim == D) {
  4982. Matched = true;
  4983. break;
  4984. }
  4985. ++D;
  4986. T = AT->getElementType();
  4987. }
  4988. if (Matched && T->isArrayType()) {
  4989. if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
  4990. return CAT->getSize().getLimitedValue();
  4991. }
  4992. }
  4993. return 0;
  4994. }
  4995. }
  4996. llvm_unreachable("Unknown type trait or not implemented");
  4997. }
  4998. ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
  4999. SourceLocation KWLoc,
  5000. TypeSourceInfo *TSInfo,
  5001. Expr* DimExpr,
  5002. SourceLocation RParen) {
  5003. QualType T = TSInfo->getType();
  5004. // FIXME: This should likely be tracked as an APInt to remove any host
  5005. // assumptions about the width of size_t on the target.
  5006. uint64_t Value = 0;
  5007. if (!T->isDependentType())
  5008. Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
  5009. // While the specification for these traits from the Embarcadero C++
  5010. // compiler's documentation says the return type is 'unsigned int', Clang
  5011. // returns 'size_t'. On Windows, the primary platform for the Embarcadero
  5012. // compiler, there is no difference. On several other platforms this is an
  5013. // important distinction.
  5014. return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
  5015. RParen, Context.getSizeType());
  5016. }
  5017. ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
  5018. SourceLocation KWLoc,
  5019. Expr *Queried,
  5020. SourceLocation RParen) {
  5021. // If error parsing the expression, ignore.
  5022. if (!Queried)
  5023. return ExprError();
  5024. ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
  5025. return Result;
  5026. }
  5027. static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
  5028. switch (ET) {
  5029. case ET_IsLValueExpr: return E->isLValue();
  5030. case ET_IsRValueExpr:
  5031. return E->isPRValue();
  5032. }
  5033. llvm_unreachable("Expression trait not covered by switch");
  5034. }
  5035. ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
  5036. SourceLocation KWLoc,
  5037. Expr *Queried,
  5038. SourceLocation RParen) {
  5039. if (Queried->isTypeDependent()) {
  5040. // Delay type-checking for type-dependent expressions.
  5041. } else if (Queried->hasPlaceholderType()) {
  5042. ExprResult PE = CheckPlaceholderExpr(Queried);
  5043. if (PE.isInvalid()) return ExprError();
  5044. return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
  5045. }
  5046. bool Value = EvaluateExpressionTrait(ET, Queried);
  5047. return new (Context)
  5048. ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
  5049. }
  5050. QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
  5051. ExprValueKind &VK,
  5052. SourceLocation Loc,
  5053. bool isIndirect) {
  5054. assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
  5055. "placeholders should have been weeded out by now");
  5056. // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
  5057. // temporary materialization conversion otherwise.
  5058. if (isIndirect)
  5059. LHS = DefaultLvalueConversion(LHS.get());
  5060. else if (LHS.get()->isPRValue())
  5061. LHS = TemporaryMaterializationConversion(LHS.get());
  5062. if (LHS.isInvalid())
  5063. return QualType();
  5064. // The RHS always undergoes lvalue conversions.
  5065. RHS = DefaultLvalueConversion(RHS.get());
  5066. if (RHS.isInvalid()) return QualType();
  5067. const char *OpSpelling = isIndirect ? "->*" : ".*";
  5068. // C++ 5.5p2
  5069. // The binary operator .* [p3: ->*] binds its second operand, which shall
  5070. // be of type "pointer to member of T" (where T is a completely-defined
  5071. // class type) [...]
  5072. QualType RHSType = RHS.get()->getType();
  5073. const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
  5074. if (!MemPtr) {
  5075. Diag(Loc, diag::err_bad_memptr_rhs)
  5076. << OpSpelling << RHSType << RHS.get()->getSourceRange();
  5077. return QualType();
  5078. }
  5079. QualType Class(MemPtr->getClass(), 0);
  5080. // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
  5081. // member pointer points must be completely-defined. However, there is no
  5082. // reason for this semantic distinction, and the rule is not enforced by
  5083. // other compilers. Therefore, we do not check this property, as it is
  5084. // likely to be considered a defect.
  5085. // C++ 5.5p2
  5086. // [...] to its first operand, which shall be of class T or of a class of
  5087. // which T is an unambiguous and accessible base class. [p3: a pointer to
  5088. // such a class]
  5089. QualType LHSType = LHS.get()->getType();
  5090. if (isIndirect) {
  5091. if (const PointerType *Ptr = LHSType->getAs<PointerType>())
  5092. LHSType = Ptr->getPointeeType();
  5093. else {
  5094. Diag(Loc, diag::err_bad_memptr_lhs)
  5095. << OpSpelling << 1 << LHSType
  5096. << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
  5097. return QualType();
  5098. }
  5099. }
  5100. if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
  5101. // If we want to check the hierarchy, we need a complete type.
  5102. if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
  5103. OpSpelling, (int)isIndirect)) {
  5104. return QualType();
  5105. }
  5106. if (!IsDerivedFrom(Loc, LHSType, Class)) {
  5107. Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
  5108. << (int)isIndirect << LHS.get()->getType();
  5109. return QualType();
  5110. }
  5111. CXXCastPath BasePath;
  5112. if (CheckDerivedToBaseConversion(
  5113. LHSType, Class, Loc,
  5114. SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
  5115. &BasePath))
  5116. return QualType();
  5117. // Cast LHS to type of use.
  5118. QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
  5119. if (isIndirect)
  5120. UseType = Context.getPointerType(UseType);
  5121. ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
  5122. LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
  5123. &BasePath);
  5124. }
  5125. if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
  5126. // Diagnose use of pointer-to-member type which when used as
  5127. // the functional cast in a pointer-to-member expression.
  5128. Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
  5129. return QualType();
  5130. }
  5131. // C++ 5.5p2
  5132. // The result is an object or a function of the type specified by the
  5133. // second operand.
  5134. // The cv qualifiers are the union of those in the pointer and the left side,
  5135. // in accordance with 5.5p5 and 5.2.5.
  5136. QualType Result = MemPtr->getPointeeType();
  5137. Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
  5138. // C++0x [expr.mptr.oper]p6:
  5139. // In a .* expression whose object expression is an rvalue, the program is
  5140. // ill-formed if the second operand is a pointer to member function with
  5141. // ref-qualifier &. In a ->* expression or in a .* expression whose object
  5142. // expression is an lvalue, the program is ill-formed if the second operand
  5143. // is a pointer to member function with ref-qualifier &&.
  5144. if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
  5145. switch (Proto->getRefQualifier()) {
  5146. case RQ_None:
  5147. // Do nothing
  5148. break;
  5149. case RQ_LValue:
  5150. if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
  5151. // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
  5152. // is (exactly) 'const'.
  5153. if (Proto->isConst() && !Proto->isVolatile())
  5154. Diag(Loc, getLangOpts().CPlusPlus20
  5155. ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
  5156. : diag::ext_pointer_to_const_ref_member_on_rvalue);
  5157. else
  5158. Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
  5159. << RHSType << 1 << LHS.get()->getSourceRange();
  5160. }
  5161. break;
  5162. case RQ_RValue:
  5163. if (isIndirect || !LHS.get()->Classify(Context).isRValue())
  5164. Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
  5165. << RHSType << 0 << LHS.get()->getSourceRange();
  5166. break;
  5167. }
  5168. }
  5169. // C++ [expr.mptr.oper]p6:
  5170. // The result of a .* expression whose second operand is a pointer
  5171. // to a data member is of the same value category as its
  5172. // first operand. The result of a .* expression whose second
  5173. // operand is a pointer to a member function is a prvalue. The
  5174. // result of an ->* expression is an lvalue if its second operand
  5175. // is a pointer to data member and a prvalue otherwise.
  5176. if (Result->isFunctionType()) {
  5177. VK = VK_PRValue;
  5178. return Context.BoundMemberTy;
  5179. } else if (isIndirect) {
  5180. VK = VK_LValue;
  5181. } else {
  5182. VK = LHS.get()->getValueKind();
  5183. }
  5184. return Result;
  5185. }
  5186. /// Try to convert a type to another according to C++11 5.16p3.
  5187. ///
  5188. /// This is part of the parameter validation for the ? operator. If either
  5189. /// value operand is a class type, the two operands are attempted to be
  5190. /// converted to each other. This function does the conversion in one direction.
  5191. /// It returns true if the program is ill-formed and has already been diagnosed
  5192. /// as such.
  5193. static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
  5194. SourceLocation QuestionLoc,
  5195. bool &HaveConversion,
  5196. QualType &ToType) {
  5197. HaveConversion = false;
  5198. ToType = To->getType();
  5199. InitializationKind Kind =
  5200. InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
  5201. // C++11 5.16p3
  5202. // The process for determining whether an operand expression E1 of type T1
  5203. // can be converted to match an operand expression E2 of type T2 is defined
  5204. // as follows:
  5205. // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
  5206. // implicitly converted to type "lvalue reference to T2", subject to the
  5207. // constraint that in the conversion the reference must bind directly to
  5208. // an lvalue.
  5209. // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
  5210. // implicitly converted to the type "rvalue reference to R2", subject to
  5211. // the constraint that the reference must bind directly.
  5212. if (To->isGLValue()) {
  5213. QualType T = Self.Context.getReferenceQualifiedType(To);
  5214. InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
  5215. InitializationSequence InitSeq(Self, Entity, Kind, From);
  5216. if (InitSeq.isDirectReferenceBinding()) {
  5217. ToType = T;
  5218. HaveConversion = true;
  5219. return false;
  5220. }
  5221. if (InitSeq.isAmbiguous())
  5222. return InitSeq.Diagnose(Self, Entity, Kind, From);
  5223. }
  5224. // -- If E2 is an rvalue, or if the conversion above cannot be done:
  5225. // -- if E1 and E2 have class type, and the underlying class types are
  5226. // the same or one is a base class of the other:
  5227. QualType FTy = From->getType();
  5228. QualType TTy = To->getType();
  5229. const RecordType *FRec = FTy->getAs<RecordType>();
  5230. const RecordType *TRec = TTy->getAs<RecordType>();
  5231. bool FDerivedFromT = FRec && TRec && FRec != TRec &&
  5232. Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
  5233. if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
  5234. Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
  5235. // E1 can be converted to match E2 if the class of T2 is the
  5236. // same type as, or a base class of, the class of T1, and
  5237. // [cv2 > cv1].
  5238. if (FRec == TRec || FDerivedFromT) {
  5239. if (TTy.isAtLeastAsQualifiedAs(FTy)) {
  5240. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
  5241. InitializationSequence InitSeq(Self, Entity, Kind, From);
  5242. if (InitSeq) {
  5243. HaveConversion = true;
  5244. return false;
  5245. }
  5246. if (InitSeq.isAmbiguous())
  5247. return InitSeq.Diagnose(Self, Entity, Kind, From);
  5248. }
  5249. }
  5250. return false;
  5251. }
  5252. // -- Otherwise: E1 can be converted to match E2 if E1 can be
  5253. // implicitly converted to the type that expression E2 would have
  5254. // if E2 were converted to an rvalue (or the type it has, if E2 is
  5255. // an rvalue).
  5256. //
  5257. // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
  5258. // to the array-to-pointer or function-to-pointer conversions.
  5259. TTy = TTy.getNonLValueExprType(Self.Context);
  5260. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
  5261. InitializationSequence InitSeq(Self, Entity, Kind, From);
  5262. HaveConversion = !InitSeq.Failed();
  5263. ToType = TTy;
  5264. if (InitSeq.isAmbiguous())
  5265. return InitSeq.Diagnose(Self, Entity, Kind, From);
  5266. return false;
  5267. }
  5268. /// Try to find a common type for two according to C++0x 5.16p5.
  5269. ///
  5270. /// This is part of the parameter validation for the ? operator. If either
  5271. /// value operand is a class type, overload resolution is used to find a
  5272. /// conversion to a common type.
  5273. static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
  5274. SourceLocation QuestionLoc) {
  5275. Expr *Args[2] = { LHS.get(), RHS.get() };
  5276. OverloadCandidateSet CandidateSet(QuestionLoc,
  5277. OverloadCandidateSet::CSK_Operator);
  5278. Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
  5279. CandidateSet);
  5280. OverloadCandidateSet::iterator Best;
  5281. switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
  5282. case OR_Success: {
  5283. // We found a match. Perform the conversions on the arguments and move on.
  5284. ExprResult LHSRes = Self.PerformImplicitConversion(
  5285. LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
  5286. Sema::AA_Converting);
  5287. if (LHSRes.isInvalid())
  5288. break;
  5289. LHS = LHSRes;
  5290. ExprResult RHSRes = Self.PerformImplicitConversion(
  5291. RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
  5292. Sema::AA_Converting);
  5293. if (RHSRes.isInvalid())
  5294. break;
  5295. RHS = RHSRes;
  5296. if (Best->Function)
  5297. Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
  5298. return false;
  5299. }
  5300. case OR_No_Viable_Function:
  5301. // Emit a better diagnostic if one of the expressions is a null pointer
  5302. // constant and the other is a pointer type. In this case, the user most
  5303. // likely forgot to take the address of the other expression.
  5304. if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5305. return true;
  5306. Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5307. << LHS.get()->getType() << RHS.get()->getType()
  5308. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5309. return true;
  5310. case OR_Ambiguous:
  5311. Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
  5312. << LHS.get()->getType() << RHS.get()->getType()
  5313. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5314. // FIXME: Print the possible common types by printing the return types of
  5315. // the viable candidates.
  5316. break;
  5317. case OR_Deleted:
  5318. llvm_unreachable("Conditional operator has only built-in overloads");
  5319. }
  5320. return true;
  5321. }
  5322. /// Perform an "extended" implicit conversion as returned by
  5323. /// TryClassUnification.
  5324. static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
  5325. InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
  5326. InitializationKind Kind =
  5327. InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
  5328. Expr *Arg = E.get();
  5329. InitializationSequence InitSeq(Self, Entity, Kind, Arg);
  5330. ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
  5331. if (Result.isInvalid())
  5332. return true;
  5333. E = Result;
  5334. return false;
  5335. }
  5336. // Check the condition operand of ?: to see if it is valid for the GCC
  5337. // extension.
  5338. static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
  5339. QualType CondTy) {
  5340. if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
  5341. return false;
  5342. const QualType EltTy =
  5343. cast<VectorType>(CondTy.getCanonicalType())->getElementType();
  5344. assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() &&
  5345. "Vectors cant be boolean or enum types");
  5346. return EltTy->isIntegralType(Ctx);
  5347. }
  5348. QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
  5349. ExprResult &RHS,
  5350. SourceLocation QuestionLoc) {
  5351. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  5352. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  5353. QualType CondType = Cond.get()->getType();
  5354. const auto *CondVT = CondType->castAs<VectorType>();
  5355. QualType CondElementTy = CondVT->getElementType();
  5356. unsigned CondElementCount = CondVT->getNumElements();
  5357. QualType LHSType = LHS.get()->getType();
  5358. const auto *LHSVT = LHSType->getAs<VectorType>();
  5359. QualType RHSType = RHS.get()->getType();
  5360. const auto *RHSVT = RHSType->getAs<VectorType>();
  5361. QualType ResultType;
  5362. if (LHSVT && RHSVT) {
  5363. if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
  5364. Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
  5365. << /*isExtVector*/ isa<ExtVectorType>(CondVT);
  5366. return {};
  5367. }
  5368. // If both are vector types, they must be the same type.
  5369. if (!Context.hasSameType(LHSType, RHSType)) {
  5370. Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
  5371. << LHSType << RHSType;
  5372. return {};
  5373. }
  5374. ResultType = LHSType;
  5375. } else if (LHSVT || RHSVT) {
  5376. ResultType = CheckVectorOperands(
  5377. LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
  5378. /*AllowBoolConversions*/ false);
  5379. if (ResultType.isNull())
  5380. return {};
  5381. } else {
  5382. // Both are scalar.
  5383. QualType ResultElementTy;
  5384. LHSType = LHSType.getCanonicalType().getUnqualifiedType();
  5385. RHSType = RHSType.getCanonicalType().getUnqualifiedType();
  5386. if (Context.hasSameType(LHSType, RHSType))
  5387. ResultElementTy = LHSType;
  5388. else
  5389. ResultElementTy =
  5390. UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
  5391. if (ResultElementTy->isEnumeralType()) {
  5392. Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
  5393. << ResultElementTy;
  5394. return {};
  5395. }
  5396. if (CondType->isExtVectorType())
  5397. ResultType =
  5398. Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
  5399. else
  5400. ResultType = Context.getVectorType(
  5401. ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector);
  5402. LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
  5403. RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
  5404. }
  5405. assert(!ResultType.isNull() && ResultType->isVectorType() &&
  5406. (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
  5407. "Result should have been a vector type");
  5408. auto *ResultVectorTy = ResultType->castAs<VectorType>();
  5409. QualType ResultElementTy = ResultVectorTy->getElementType();
  5410. unsigned ResultElementCount = ResultVectorTy->getNumElements();
  5411. if (ResultElementCount != CondElementCount) {
  5412. Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
  5413. << ResultType;
  5414. return {};
  5415. }
  5416. if (Context.getTypeSize(ResultElementTy) !=
  5417. Context.getTypeSize(CondElementTy)) {
  5418. Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
  5419. << ResultType;
  5420. return {};
  5421. }
  5422. return ResultType;
  5423. }
  5424. /// Check the operands of ?: under C++ semantics.
  5425. ///
  5426. /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
  5427. /// extension. In this case, LHS == Cond. (But they're not aliases.)
  5428. ///
  5429. /// This function also implements GCC's vector extension and the
  5430. /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
  5431. /// permit the use of a?b:c where the type of a is that of a integer vector with
  5432. /// the same number of elements and size as the vectors of b and c. If one of
  5433. /// either b or c is a scalar it is implicitly converted to match the type of
  5434. /// the vector. Otherwise the expression is ill-formed. If both b and c are
  5435. /// scalars, then b and c are checked and converted to the type of a if
  5436. /// possible.
  5437. ///
  5438. /// The expressions are evaluated differently for GCC's and OpenCL's extensions.
  5439. /// For the GCC extension, the ?: operator is evaluated as
  5440. /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
  5441. /// For the OpenCL extensions, the ?: operator is evaluated as
  5442. /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
  5443. /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
  5444. QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5445. ExprResult &RHS, ExprValueKind &VK,
  5446. ExprObjectKind &OK,
  5447. SourceLocation QuestionLoc) {
  5448. // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
  5449. // pointers.
  5450. // Assume r-value.
  5451. VK = VK_PRValue;
  5452. OK = OK_Ordinary;
  5453. bool IsVectorConditional =
  5454. isValidVectorForConditionalCondition(Context, Cond.get()->getType());
  5455. // C++11 [expr.cond]p1
  5456. // The first expression is contextually converted to bool.
  5457. if (!Cond.get()->isTypeDependent()) {
  5458. ExprResult CondRes = IsVectorConditional
  5459. ? DefaultFunctionArrayLvalueConversion(Cond.get())
  5460. : CheckCXXBooleanCondition(Cond.get());
  5461. if (CondRes.isInvalid())
  5462. return QualType();
  5463. Cond = CondRes;
  5464. } else {
  5465. // To implement C++, the first expression typically doesn't alter the result
  5466. // type of the conditional, however the GCC compatible vector extension
  5467. // changes the result type to be that of the conditional. Since we cannot
  5468. // know if this is a vector extension here, delay the conversion of the
  5469. // LHS/RHS below until later.
  5470. return Context.DependentTy;
  5471. }
  5472. // Either of the arguments dependent?
  5473. if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
  5474. return Context.DependentTy;
  5475. // C++11 [expr.cond]p2
  5476. // If either the second or the third operand has type (cv) void, ...
  5477. QualType LTy = LHS.get()->getType();
  5478. QualType RTy = RHS.get()->getType();
  5479. bool LVoid = LTy->isVoidType();
  5480. bool RVoid = RTy->isVoidType();
  5481. if (LVoid || RVoid) {
  5482. // ... one of the following shall hold:
  5483. // -- The second or the third operand (but not both) is a (possibly
  5484. // parenthesized) throw-expression; the result is of the type
  5485. // and value category of the other.
  5486. bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
  5487. bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
  5488. // Void expressions aren't legal in the vector-conditional expressions.
  5489. if (IsVectorConditional) {
  5490. SourceRange DiagLoc =
  5491. LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
  5492. bool IsThrow = LVoid ? LThrow : RThrow;
  5493. Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
  5494. << DiagLoc << IsThrow;
  5495. return QualType();
  5496. }
  5497. if (LThrow != RThrow) {
  5498. Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
  5499. VK = NonThrow->getValueKind();
  5500. // DR (no number yet): the result is a bit-field if the
  5501. // non-throw-expression operand is a bit-field.
  5502. OK = NonThrow->getObjectKind();
  5503. return NonThrow->getType();
  5504. }
  5505. // -- Both the second and third operands have type void; the result is of
  5506. // type void and is a prvalue.
  5507. if (LVoid && RVoid)
  5508. return Context.VoidTy;
  5509. // Neither holds, error.
  5510. Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
  5511. << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
  5512. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5513. return QualType();
  5514. }
  5515. // Neither is void.
  5516. if (IsVectorConditional)
  5517. return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
  5518. // C++11 [expr.cond]p3
  5519. // Otherwise, if the second and third operand have different types, and
  5520. // either has (cv) class type [...] an attempt is made to convert each of
  5521. // those operands to the type of the other.
  5522. if (!Context.hasSameType(LTy, RTy) &&
  5523. (LTy->isRecordType() || RTy->isRecordType())) {
  5524. // These return true if a single direction is already ambiguous.
  5525. QualType L2RType, R2LType;
  5526. bool HaveL2R, HaveR2L;
  5527. if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
  5528. return QualType();
  5529. if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
  5530. return QualType();
  5531. // If both can be converted, [...] the program is ill-formed.
  5532. if (HaveL2R && HaveR2L) {
  5533. Diag(QuestionLoc, diag::err_conditional_ambiguous)
  5534. << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5535. return QualType();
  5536. }
  5537. // If exactly one conversion is possible, that conversion is applied to
  5538. // the chosen operand and the converted operands are used in place of the
  5539. // original operands for the remainder of this section.
  5540. if (HaveL2R) {
  5541. if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
  5542. return QualType();
  5543. LTy = LHS.get()->getType();
  5544. } else if (HaveR2L) {
  5545. if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
  5546. return QualType();
  5547. RTy = RHS.get()->getType();
  5548. }
  5549. }
  5550. // C++11 [expr.cond]p3
  5551. // if both are glvalues of the same value category and the same type except
  5552. // for cv-qualification, an attempt is made to convert each of those
  5553. // operands to the type of the other.
  5554. // FIXME:
  5555. // Resolving a defect in P0012R1: we extend this to cover all cases where
  5556. // one of the operands is reference-compatible with the other, in order
  5557. // to support conditionals between functions differing in noexcept. This
  5558. // will similarly cover difference in array bounds after P0388R4.
  5559. // FIXME: If LTy and RTy have a composite pointer type, should we convert to
  5560. // that instead?
  5561. ExprValueKind LVK = LHS.get()->getValueKind();
  5562. ExprValueKind RVK = RHS.get()->getValueKind();
  5563. if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
  5564. // DerivedToBase was already handled by the class-specific case above.
  5565. // FIXME: Should we allow ObjC conversions here?
  5566. const ReferenceConversions AllowedConversions =
  5567. ReferenceConversions::Qualification |
  5568. ReferenceConversions::NestedQualification |
  5569. ReferenceConversions::Function;
  5570. ReferenceConversions RefConv;
  5571. if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
  5572. Ref_Compatible &&
  5573. !(RefConv & ~AllowedConversions) &&
  5574. // [...] subject to the constraint that the reference must bind
  5575. // directly [...]
  5576. !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
  5577. RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
  5578. RTy = RHS.get()->getType();
  5579. } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
  5580. Ref_Compatible &&
  5581. !(RefConv & ~AllowedConversions) &&
  5582. !LHS.get()->refersToBitField() &&
  5583. !LHS.get()->refersToVectorElement()) {
  5584. LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
  5585. LTy = LHS.get()->getType();
  5586. }
  5587. }
  5588. // C++11 [expr.cond]p4
  5589. // If the second and third operands are glvalues of the same value
  5590. // category and have the same type, the result is of that type and
  5591. // value category and it is a bit-field if the second or the third
  5592. // operand is a bit-field, or if both are bit-fields.
  5593. // We only extend this to bitfields, not to the crazy other kinds of
  5594. // l-values.
  5595. bool Same = Context.hasSameType(LTy, RTy);
  5596. if (Same && LVK == RVK && LVK != VK_PRValue &&
  5597. LHS.get()->isOrdinaryOrBitFieldObject() &&
  5598. RHS.get()->isOrdinaryOrBitFieldObject()) {
  5599. VK = LHS.get()->getValueKind();
  5600. if (LHS.get()->getObjectKind() == OK_BitField ||
  5601. RHS.get()->getObjectKind() == OK_BitField)
  5602. OK = OK_BitField;
  5603. // If we have function pointer types, unify them anyway to unify their
  5604. // exception specifications, if any.
  5605. if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
  5606. Qualifiers Qs = LTy.getQualifiers();
  5607. LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
  5608. /*ConvertArgs*/false);
  5609. LTy = Context.getQualifiedType(LTy, Qs);
  5610. assert(!LTy.isNull() && "failed to find composite pointer type for "
  5611. "canonically equivalent function ptr types");
  5612. assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
  5613. }
  5614. return LTy;
  5615. }
  5616. // C++11 [expr.cond]p5
  5617. // Otherwise, the result is a prvalue. If the second and third operands
  5618. // do not have the same type, and either has (cv) class type, ...
  5619. if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
  5620. // ... overload resolution is used to determine the conversions (if any)
  5621. // to be applied to the operands. If the overload resolution fails, the
  5622. // program is ill-formed.
  5623. if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
  5624. return QualType();
  5625. }
  5626. // C++11 [expr.cond]p6
  5627. // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
  5628. // conversions are performed on the second and third operands.
  5629. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  5630. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  5631. if (LHS.isInvalid() || RHS.isInvalid())
  5632. return QualType();
  5633. LTy = LHS.get()->getType();
  5634. RTy = RHS.get()->getType();
  5635. // After those conversions, one of the following shall hold:
  5636. // -- The second and third operands have the same type; the result
  5637. // is of that type. If the operands have class type, the result
  5638. // is a prvalue temporary of the result type, which is
  5639. // copy-initialized from either the second operand or the third
  5640. // operand depending on the value of the first operand.
  5641. if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
  5642. if (LTy->isRecordType()) {
  5643. // The operands have class type. Make a temporary copy.
  5644. InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
  5645. ExprResult LHSCopy = PerformCopyInitialization(Entity,
  5646. SourceLocation(),
  5647. LHS);
  5648. if (LHSCopy.isInvalid())
  5649. return QualType();
  5650. ExprResult RHSCopy = PerformCopyInitialization(Entity,
  5651. SourceLocation(),
  5652. RHS);
  5653. if (RHSCopy.isInvalid())
  5654. return QualType();
  5655. LHS = LHSCopy;
  5656. RHS = RHSCopy;
  5657. }
  5658. // If we have function pointer types, unify them anyway to unify their
  5659. // exception specifications, if any.
  5660. if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
  5661. LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
  5662. assert(!LTy.isNull() && "failed to find composite pointer type for "
  5663. "canonically equivalent function ptr types");
  5664. }
  5665. return LTy;
  5666. }
  5667. // Extension: conditional operator involving vector types.
  5668. if (LTy->isVectorType() || RTy->isVectorType())
  5669. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5670. /*AllowBothBool*/true,
  5671. /*AllowBoolConversions*/false);
  5672. // -- The second and third operands have arithmetic or enumeration type;
  5673. // the usual arithmetic conversions are performed to bring them to a
  5674. // common type, and the result is of that type.
  5675. if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
  5676. QualType ResTy =
  5677. UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
  5678. if (LHS.isInvalid() || RHS.isInvalid())
  5679. return QualType();
  5680. if (ResTy.isNull()) {
  5681. Diag(QuestionLoc,
  5682. diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
  5683. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5684. return QualType();
  5685. }
  5686. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5687. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5688. return ResTy;
  5689. }
  5690. // -- The second and third operands have pointer type, or one has pointer
  5691. // type and the other is a null pointer constant, or both are null
  5692. // pointer constants, at least one of which is non-integral; pointer
  5693. // conversions and qualification conversions are performed to bring them
  5694. // to their composite pointer type. The result is of the composite
  5695. // pointer type.
  5696. // -- The second and third operands have pointer to member type, or one has
  5697. // pointer to member type and the other is a null pointer constant;
  5698. // pointer to member conversions and qualification conversions are
  5699. // performed to bring them to a common type, whose cv-qualification
  5700. // shall match the cv-qualification of either the second or the third
  5701. // operand. The result is of the common type.
  5702. QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
  5703. if (!Composite.isNull())
  5704. return Composite;
  5705. // Similarly, attempt to find composite type of two objective-c pointers.
  5706. Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
  5707. if (LHS.isInvalid() || RHS.isInvalid())
  5708. return QualType();
  5709. if (!Composite.isNull())
  5710. return Composite;
  5711. // Check if we are using a null with a non-pointer type.
  5712. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5713. return QualType();
  5714. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5715. << LHS.get()->getType() << RHS.get()->getType()
  5716. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5717. return QualType();
  5718. }
  5719. static FunctionProtoType::ExceptionSpecInfo
  5720. mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
  5721. FunctionProtoType::ExceptionSpecInfo ESI2,
  5722. SmallVectorImpl<QualType> &ExceptionTypeStorage) {
  5723. ExceptionSpecificationType EST1 = ESI1.Type;
  5724. ExceptionSpecificationType EST2 = ESI2.Type;
  5725. // If either of them can throw anything, that is the result.
  5726. if (EST1 == EST_None) return ESI1;
  5727. if (EST2 == EST_None) return ESI2;
  5728. if (EST1 == EST_MSAny) return ESI1;
  5729. if (EST2 == EST_MSAny) return ESI2;
  5730. if (EST1 == EST_NoexceptFalse) return ESI1;
  5731. if (EST2 == EST_NoexceptFalse) return ESI2;
  5732. // If either of them is non-throwing, the result is the other.
  5733. if (EST1 == EST_NoThrow) return ESI2;
  5734. if (EST2 == EST_NoThrow) return ESI1;
  5735. if (EST1 == EST_DynamicNone) return ESI2;
  5736. if (EST2 == EST_DynamicNone) return ESI1;
  5737. if (EST1 == EST_BasicNoexcept) return ESI2;
  5738. if (EST2 == EST_BasicNoexcept) return ESI1;
  5739. if (EST1 == EST_NoexceptTrue) return ESI2;
  5740. if (EST2 == EST_NoexceptTrue) return ESI1;
  5741. // If we're left with value-dependent computed noexcept expressions, we're
  5742. // stuck. Before C++17, we can just drop the exception specification entirely,
  5743. // since it's not actually part of the canonical type. And this should never
  5744. // happen in C++17, because it would mean we were computing the composite
  5745. // pointer type of dependent types, which should never happen.
  5746. if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
  5747. assert(!S.getLangOpts().CPlusPlus17 &&
  5748. "computing composite pointer type of dependent types");
  5749. return FunctionProtoType::ExceptionSpecInfo();
  5750. }
  5751. // Switch over the possibilities so that people adding new values know to
  5752. // update this function.
  5753. switch (EST1) {
  5754. case EST_None:
  5755. case EST_DynamicNone:
  5756. case EST_MSAny:
  5757. case EST_BasicNoexcept:
  5758. case EST_DependentNoexcept:
  5759. case EST_NoexceptFalse:
  5760. case EST_NoexceptTrue:
  5761. case EST_NoThrow:
  5762. llvm_unreachable("handled above");
  5763. case EST_Dynamic: {
  5764. // This is the fun case: both exception specifications are dynamic. Form
  5765. // the union of the two lists.
  5766. assert(EST2 == EST_Dynamic && "other cases should already be handled");
  5767. llvm::SmallPtrSet<QualType, 8> Found;
  5768. for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
  5769. for (QualType E : Exceptions)
  5770. if (Found.insert(S.Context.getCanonicalType(E)).second)
  5771. ExceptionTypeStorage.push_back(E);
  5772. FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
  5773. Result.Exceptions = ExceptionTypeStorage;
  5774. return Result;
  5775. }
  5776. case EST_Unevaluated:
  5777. case EST_Uninstantiated:
  5778. case EST_Unparsed:
  5779. llvm_unreachable("shouldn't see unresolved exception specifications here");
  5780. }
  5781. llvm_unreachable("invalid ExceptionSpecificationType");
  5782. }
  5783. /// Find a merged pointer type and convert the two expressions to it.
  5784. ///
  5785. /// This finds the composite pointer type for \p E1 and \p E2 according to
  5786. /// C++2a [expr.type]p3. It converts both expressions to this type and returns
  5787. /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
  5788. /// is \c true).
  5789. ///
  5790. /// \param Loc The location of the operator requiring these two expressions to
  5791. /// be converted to the composite pointer type.
  5792. ///
  5793. /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
  5794. QualType Sema::FindCompositePointerType(SourceLocation Loc,
  5795. Expr *&E1, Expr *&E2,
  5796. bool ConvertArgs) {
  5797. assert(getLangOpts().CPlusPlus && "This function assumes C++");
  5798. // C++1z [expr]p14:
  5799. // The composite pointer type of two operands p1 and p2 having types T1
  5800. // and T2
  5801. QualType T1 = E1->getType(), T2 = E2->getType();
  5802. // where at least one is a pointer or pointer to member type or
  5803. // std::nullptr_t is:
  5804. bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
  5805. T1->isNullPtrType();
  5806. bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
  5807. T2->isNullPtrType();
  5808. if (!T1IsPointerLike && !T2IsPointerLike)
  5809. return QualType();
  5810. // - if both p1 and p2 are null pointer constants, std::nullptr_t;
  5811. // This can't actually happen, following the standard, but we also use this
  5812. // to implement the end of [expr.conv], which hits this case.
  5813. //
  5814. // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
  5815. if (T1IsPointerLike &&
  5816. E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  5817. if (ConvertArgs)
  5818. E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
  5819. ? CK_NullToMemberPointer
  5820. : CK_NullToPointer).get();
  5821. return T1;
  5822. }
  5823. if (T2IsPointerLike &&
  5824. E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  5825. if (ConvertArgs)
  5826. E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
  5827. ? CK_NullToMemberPointer
  5828. : CK_NullToPointer).get();
  5829. return T2;
  5830. }
  5831. // Now both have to be pointers or member pointers.
  5832. if (!T1IsPointerLike || !T2IsPointerLike)
  5833. return QualType();
  5834. assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
  5835. "nullptr_t should be a null pointer constant");
  5836. struct Step {
  5837. enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
  5838. // Qualifiers to apply under the step kind.
  5839. Qualifiers Quals;
  5840. /// The class for a pointer-to-member; a constant array type with a bound
  5841. /// (if any) for an array.
  5842. const Type *ClassOrBound;
  5843. Step(Kind K, const Type *ClassOrBound = nullptr)
  5844. : K(K), ClassOrBound(ClassOrBound) {}
  5845. QualType rebuild(ASTContext &Ctx, QualType T) const {
  5846. T = Ctx.getQualifiedType(T, Quals);
  5847. switch (K) {
  5848. case Pointer:
  5849. return Ctx.getPointerType(T);
  5850. case MemberPointer:
  5851. return Ctx.getMemberPointerType(T, ClassOrBound);
  5852. case ObjCPointer:
  5853. return Ctx.getObjCObjectPointerType(T);
  5854. case Array:
  5855. if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
  5856. return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
  5857. ArrayType::Normal, 0);
  5858. else
  5859. return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
  5860. }
  5861. llvm_unreachable("unknown step kind");
  5862. }
  5863. };
  5864. SmallVector<Step, 8> Steps;
  5865. // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
  5866. // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
  5867. // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
  5868. // respectively;
  5869. // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
  5870. // to member of C2 of type cv2 U2" for some non-function type U, where
  5871. // C1 is reference-related to C2 or C2 is reference-related to C1, the
  5872. // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
  5873. // respectively;
  5874. // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
  5875. // T2;
  5876. //
  5877. // Dismantle T1 and T2 to simultaneously determine whether they are similar
  5878. // and to prepare to form the cv-combined type if so.
  5879. QualType Composite1 = T1;
  5880. QualType Composite2 = T2;
  5881. unsigned NeedConstBefore = 0;
  5882. while (true) {
  5883. assert(!Composite1.isNull() && !Composite2.isNull());
  5884. Qualifiers Q1, Q2;
  5885. Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
  5886. Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
  5887. // Top-level qualifiers are ignored. Merge at all lower levels.
  5888. if (!Steps.empty()) {
  5889. // Find the qualifier union: (approximately) the unique minimal set of
  5890. // qualifiers that is compatible with both types.
  5891. Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
  5892. Q2.getCVRUQualifiers());
  5893. // Under one level of pointer or pointer-to-member, we can change to an
  5894. // unambiguous compatible address space.
  5895. if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
  5896. Quals.setAddressSpace(Q1.getAddressSpace());
  5897. } else if (Steps.size() == 1) {
  5898. bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
  5899. bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
  5900. if (MaybeQ1 == MaybeQ2) {
  5901. // Exception for ptr size address spaces. Should be able to choose
  5902. // either address space during comparison.
  5903. if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||
  5904. isPtrSizeAddressSpace(Q2.getAddressSpace()))
  5905. MaybeQ1 = true;
  5906. else
  5907. return QualType(); // No unique best address space.
  5908. }
  5909. Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
  5910. : Q2.getAddressSpace());
  5911. } else {
  5912. return QualType();
  5913. }
  5914. // FIXME: In C, we merge __strong and none to __strong at the top level.
  5915. if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
  5916. Quals.setObjCGCAttr(Q1.getObjCGCAttr());
  5917. else if (T1->isVoidPointerType() || T2->isVoidPointerType())
  5918. assert(Steps.size() == 1);
  5919. else
  5920. return QualType();
  5921. // Mismatched lifetime qualifiers never compatibly include each other.
  5922. if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
  5923. Quals.setObjCLifetime(Q1.getObjCLifetime());
  5924. else if (T1->isVoidPointerType() || T2->isVoidPointerType())
  5925. assert(Steps.size() == 1);
  5926. else
  5927. return QualType();
  5928. Steps.back().Quals = Quals;
  5929. if (Q1 != Quals || Q2 != Quals)
  5930. NeedConstBefore = Steps.size() - 1;
  5931. }
  5932. // FIXME: Can we unify the following with UnwrapSimilarTypes?
  5933. const ArrayType *Arr1, *Arr2;
  5934. if ((Arr1 = Context.getAsArrayType(Composite1)) &&
  5935. (Arr2 = Context.getAsArrayType(Composite2))) {
  5936. auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
  5937. auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
  5938. if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
  5939. Composite1 = Arr1->getElementType();
  5940. Composite2 = Arr2->getElementType();
  5941. Steps.emplace_back(Step::Array, CAT1);
  5942. continue;
  5943. }
  5944. bool IAT1 = isa<IncompleteArrayType>(Arr1);
  5945. bool IAT2 = isa<IncompleteArrayType>(Arr2);
  5946. if ((IAT1 && IAT2) ||
  5947. (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
  5948. ((bool)CAT1 != (bool)CAT2) &&
  5949. (Steps.empty() || Steps.back().K != Step::Array))) {
  5950. // In C++20 onwards, we can unify an array of N T with an array of
  5951. // a different or unknown bound. But we can't form an array whose
  5952. // element type is an array of unknown bound by doing so.
  5953. Composite1 = Arr1->getElementType();
  5954. Composite2 = Arr2->getElementType();
  5955. Steps.emplace_back(Step::Array);
  5956. if (CAT1 || CAT2)
  5957. NeedConstBefore = Steps.size();
  5958. continue;
  5959. }
  5960. }
  5961. const PointerType *Ptr1, *Ptr2;
  5962. if ((Ptr1 = Composite1->getAs<PointerType>()) &&
  5963. (Ptr2 = Composite2->getAs<PointerType>())) {
  5964. Composite1 = Ptr1->getPointeeType();
  5965. Composite2 = Ptr2->getPointeeType();
  5966. Steps.emplace_back(Step::Pointer);
  5967. continue;
  5968. }
  5969. const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
  5970. if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
  5971. (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
  5972. Composite1 = ObjPtr1->getPointeeType();
  5973. Composite2 = ObjPtr2->getPointeeType();
  5974. Steps.emplace_back(Step::ObjCPointer);
  5975. continue;
  5976. }
  5977. const MemberPointerType *MemPtr1, *MemPtr2;
  5978. if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
  5979. (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
  5980. Composite1 = MemPtr1->getPointeeType();
  5981. Composite2 = MemPtr2->getPointeeType();
  5982. // At the top level, we can perform a base-to-derived pointer-to-member
  5983. // conversion:
  5984. //
  5985. // - [...] where C1 is reference-related to C2 or C2 is
  5986. // reference-related to C1
  5987. //
  5988. // (Note that the only kinds of reference-relatedness in scope here are
  5989. // "same type or derived from".) At any other level, the class must
  5990. // exactly match.
  5991. const Type *Class = nullptr;
  5992. QualType Cls1(MemPtr1->getClass(), 0);
  5993. QualType Cls2(MemPtr2->getClass(), 0);
  5994. if (Context.hasSameType(Cls1, Cls2))
  5995. Class = MemPtr1->getClass();
  5996. else if (Steps.empty())
  5997. Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
  5998. IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
  5999. if (!Class)
  6000. return QualType();
  6001. Steps.emplace_back(Step::MemberPointer, Class);
  6002. continue;
  6003. }
  6004. // Special case: at the top level, we can decompose an Objective-C pointer
  6005. // and a 'cv void *'. Unify the qualifiers.
  6006. if (Steps.empty() && ((Composite1->isVoidPointerType() &&
  6007. Composite2->isObjCObjectPointerType()) ||
  6008. (Composite1->isObjCObjectPointerType() &&
  6009. Composite2->isVoidPointerType()))) {
  6010. Composite1 = Composite1->getPointeeType();
  6011. Composite2 = Composite2->getPointeeType();
  6012. Steps.emplace_back(Step::Pointer);
  6013. continue;
  6014. }
  6015. // FIXME: block pointer types?
  6016. // Cannot unwrap any more types.
  6017. break;
  6018. }
  6019. // - if T1 or T2 is "pointer to noexcept function" and the other type is
  6020. // "pointer to function", where the function types are otherwise the same,
  6021. // "pointer to function";
  6022. // - if T1 or T2 is "pointer to member of C1 of type function", the other
  6023. // type is "pointer to member of C2 of type noexcept function", and C1
  6024. // is reference-related to C2 or C2 is reference-related to C1, where
  6025. // the function types are otherwise the same, "pointer to member of C2 of
  6026. // type function" or "pointer to member of C1 of type function",
  6027. // respectively;
  6028. //
  6029. // We also support 'noreturn' here, so as a Clang extension we generalize the
  6030. // above to:
  6031. //
  6032. // - [Clang] If T1 and T2 are both of type "pointer to function" or
  6033. // "pointer to member function" and the pointee types can be unified
  6034. // by a function pointer conversion, that conversion is applied
  6035. // before checking the following rules.
  6036. //
  6037. // We've already unwrapped down to the function types, and we want to merge
  6038. // rather than just convert, so do this ourselves rather than calling
  6039. // IsFunctionConversion.
  6040. //
  6041. // FIXME: In order to match the standard wording as closely as possible, we
  6042. // currently only do this under a single level of pointers. Ideally, we would
  6043. // allow this in general, and set NeedConstBefore to the relevant depth on
  6044. // the side(s) where we changed anything. If we permit that, we should also
  6045. // consider this conversion when determining type similarity and model it as
  6046. // a qualification conversion.
  6047. if (Steps.size() == 1) {
  6048. if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
  6049. if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
  6050. FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
  6051. FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
  6052. // The result is noreturn if both operands are.
  6053. bool Noreturn =
  6054. EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
  6055. EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
  6056. EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
  6057. // The result is nothrow if both operands are.
  6058. SmallVector<QualType, 8> ExceptionTypeStorage;
  6059. EPI1.ExceptionSpec = EPI2.ExceptionSpec =
  6060. mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
  6061. ExceptionTypeStorage);
  6062. Composite1 = Context.getFunctionType(FPT1->getReturnType(),
  6063. FPT1->getParamTypes(), EPI1);
  6064. Composite2 = Context.getFunctionType(FPT2->getReturnType(),
  6065. FPT2->getParamTypes(), EPI2);
  6066. }
  6067. }
  6068. }
  6069. // There are some more conversions we can perform under exactly one pointer.
  6070. if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
  6071. !Context.hasSameType(Composite1, Composite2)) {
  6072. // - if T1 or T2 is "pointer to cv1 void" and the other type is
  6073. // "pointer to cv2 T", where T is an object type or void,
  6074. // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
  6075. if (Composite1->isVoidType() && Composite2->isObjectType())
  6076. Composite2 = Composite1;
  6077. else if (Composite2->isVoidType() && Composite1->isObjectType())
  6078. Composite1 = Composite2;
  6079. // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
  6080. // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
  6081. // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
  6082. // T1, respectively;
  6083. //
  6084. // The "similar type" handling covers all of this except for the "T1 is a
  6085. // base class of T2" case in the definition of reference-related.
  6086. else if (IsDerivedFrom(Loc, Composite1, Composite2))
  6087. Composite1 = Composite2;
  6088. else if (IsDerivedFrom(Loc, Composite2, Composite1))
  6089. Composite2 = Composite1;
  6090. }
  6091. // At this point, either the inner types are the same or we have failed to
  6092. // find a composite pointer type.
  6093. if (!Context.hasSameType(Composite1, Composite2))
  6094. return QualType();
  6095. // Per C++ [conv.qual]p3, add 'const' to every level before the last
  6096. // differing qualifier.
  6097. for (unsigned I = 0; I != NeedConstBefore; ++I)
  6098. Steps[I].Quals.addConst();
  6099. // Rebuild the composite type.
  6100. QualType Composite = Composite1;
  6101. for (auto &S : llvm::reverse(Steps))
  6102. Composite = S.rebuild(Context, Composite);
  6103. if (ConvertArgs) {
  6104. // Convert the expressions to the composite pointer type.
  6105. InitializedEntity Entity =
  6106. InitializedEntity::InitializeTemporary(Composite);
  6107. InitializationKind Kind =
  6108. InitializationKind::CreateCopy(Loc, SourceLocation());
  6109. InitializationSequence E1ToC(*this, Entity, Kind, E1);
  6110. if (!E1ToC)
  6111. return QualType();
  6112. InitializationSequence E2ToC(*this, Entity, Kind, E2);
  6113. if (!E2ToC)
  6114. return QualType();
  6115. // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
  6116. ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
  6117. if (E1Result.isInvalid())
  6118. return QualType();
  6119. E1 = E1Result.get();
  6120. ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
  6121. if (E2Result.isInvalid())
  6122. return QualType();
  6123. E2 = E2Result.get();
  6124. }
  6125. return Composite;
  6126. }
  6127. ExprResult Sema::MaybeBindToTemporary(Expr *E) {
  6128. if (!E)
  6129. return ExprError();
  6130. assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
  6131. // If the result is a glvalue, we shouldn't bind it.
  6132. if (E->isGLValue())
  6133. return E;
  6134. // In ARC, calls that return a retainable type can return retained,
  6135. // in which case we have to insert a consuming cast.
  6136. if (getLangOpts().ObjCAutoRefCount &&
  6137. E->getType()->isObjCRetainableType()) {
  6138. bool ReturnsRetained;
  6139. // For actual calls, we compute this by examining the type of the
  6140. // called value.
  6141. if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
  6142. Expr *Callee = Call->getCallee()->IgnoreParens();
  6143. QualType T = Callee->getType();
  6144. if (T == Context.BoundMemberTy) {
  6145. // Handle pointer-to-members.
  6146. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
  6147. T = BinOp->getRHS()->getType();
  6148. else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
  6149. T = Mem->getMemberDecl()->getType();
  6150. }
  6151. if (const PointerType *Ptr = T->getAs<PointerType>())
  6152. T = Ptr->getPointeeType();
  6153. else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
  6154. T = Ptr->getPointeeType();
  6155. else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
  6156. T = MemPtr->getPointeeType();
  6157. auto *FTy = T->castAs<FunctionType>();
  6158. ReturnsRetained = FTy->getExtInfo().getProducesResult();
  6159. // ActOnStmtExpr arranges things so that StmtExprs of retainable
  6160. // type always produce a +1 object.
  6161. } else if (isa<StmtExpr>(E)) {
  6162. ReturnsRetained = true;
  6163. // We hit this case with the lambda conversion-to-block optimization;
  6164. // we don't want any extra casts here.
  6165. } else if (isa<CastExpr>(E) &&
  6166. isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
  6167. return E;
  6168. // For message sends and property references, we try to find an
  6169. // actual method. FIXME: we should infer retention by selector in
  6170. // cases where we don't have an actual method.
  6171. } else {
  6172. ObjCMethodDecl *D = nullptr;
  6173. if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
  6174. D = Send->getMethodDecl();
  6175. } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
  6176. D = BoxedExpr->getBoxingMethod();
  6177. } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
  6178. // Don't do reclaims if we're using the zero-element array
  6179. // constant.
  6180. if (ArrayLit->getNumElements() == 0 &&
  6181. Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
  6182. return E;
  6183. D = ArrayLit->getArrayWithObjectsMethod();
  6184. } else if (ObjCDictionaryLiteral *DictLit
  6185. = dyn_cast<ObjCDictionaryLiteral>(E)) {
  6186. // Don't do reclaims if we're using the zero-element dictionary
  6187. // constant.
  6188. if (DictLit->getNumElements() == 0 &&
  6189. Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
  6190. return E;
  6191. D = DictLit->getDictWithObjectsMethod();
  6192. }
  6193. ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
  6194. // Don't do reclaims on performSelector calls; despite their
  6195. // return type, the invoked method doesn't necessarily actually
  6196. // return an object.
  6197. if (!ReturnsRetained &&
  6198. D && D->getMethodFamily() == OMF_performSelector)
  6199. return E;
  6200. }
  6201. // Don't reclaim an object of Class type.
  6202. if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
  6203. return E;
  6204. Cleanup.setExprNeedsCleanups(true);
  6205. CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
  6206. : CK_ARCReclaimReturnedObject);
  6207. return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
  6208. VK_PRValue, FPOptionsOverride());
  6209. }
  6210. if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  6211. Cleanup.setExprNeedsCleanups(true);
  6212. if (!getLangOpts().CPlusPlus)
  6213. return E;
  6214. // Search for the base element type (cf. ASTContext::getBaseElementType) with
  6215. // a fast path for the common case that the type is directly a RecordType.
  6216. const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
  6217. const RecordType *RT = nullptr;
  6218. while (!RT) {
  6219. switch (T->getTypeClass()) {
  6220. case Type::Record:
  6221. RT = cast<RecordType>(T);
  6222. break;
  6223. case Type::ConstantArray:
  6224. case Type::IncompleteArray:
  6225. case Type::VariableArray:
  6226. case Type::DependentSizedArray:
  6227. T = cast<ArrayType>(T)->getElementType().getTypePtr();
  6228. break;
  6229. default:
  6230. return E;
  6231. }
  6232. }
  6233. // That should be enough to guarantee that this type is complete, if we're
  6234. // not processing a decltype expression.
  6235. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  6236. if (RD->isInvalidDecl() || RD->isDependentContext())
  6237. return E;
  6238. bool IsDecltype = ExprEvalContexts.back().ExprContext ==
  6239. ExpressionEvaluationContextRecord::EK_Decltype;
  6240. CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
  6241. if (Destructor) {
  6242. MarkFunctionReferenced(E->getExprLoc(), Destructor);
  6243. CheckDestructorAccess(E->getExprLoc(), Destructor,
  6244. PDiag(diag::err_access_dtor_temp)
  6245. << E->getType());
  6246. if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
  6247. return ExprError();
  6248. // If destructor is trivial, we can avoid the extra copy.
  6249. if (Destructor->isTrivial())
  6250. return E;
  6251. // We need a cleanup, but we don't need to remember the temporary.
  6252. Cleanup.setExprNeedsCleanups(true);
  6253. }
  6254. CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
  6255. CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
  6256. if (IsDecltype)
  6257. ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
  6258. return Bind;
  6259. }
  6260. ExprResult
  6261. Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
  6262. if (SubExpr.isInvalid())
  6263. return ExprError();
  6264. return MaybeCreateExprWithCleanups(SubExpr.get());
  6265. }
  6266. Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
  6267. assert(SubExpr && "subexpression can't be null!");
  6268. CleanupVarDeclMarking();
  6269. unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
  6270. assert(ExprCleanupObjects.size() >= FirstCleanup);
  6271. assert(Cleanup.exprNeedsCleanups() ||
  6272. ExprCleanupObjects.size() == FirstCleanup);
  6273. if (!Cleanup.exprNeedsCleanups())
  6274. return SubExpr;
  6275. auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
  6276. ExprCleanupObjects.size() - FirstCleanup);
  6277. auto *E = ExprWithCleanups::Create(
  6278. Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
  6279. DiscardCleanupsInEvaluationContext();
  6280. return E;
  6281. }
  6282. Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
  6283. assert(SubStmt && "sub-statement can't be null!");
  6284. CleanupVarDeclMarking();
  6285. if (!Cleanup.exprNeedsCleanups())
  6286. return SubStmt;
  6287. // FIXME: In order to attach the temporaries, wrap the statement into
  6288. // a StmtExpr; currently this is only used for asm statements.
  6289. // This is hacky, either create a new CXXStmtWithTemporaries statement or
  6290. // a new AsmStmtWithTemporaries.
  6291. CompoundStmt *CompStmt = CompoundStmt::Create(
  6292. Context, SubStmt, SourceLocation(), SourceLocation());
  6293. Expr *E = new (Context)
  6294. StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
  6295. /*FIXME TemplateDepth=*/0);
  6296. return MaybeCreateExprWithCleanups(E);
  6297. }
  6298. /// Process the expression contained within a decltype. For such expressions,
  6299. /// certain semantic checks on temporaries are delayed until this point, and
  6300. /// are omitted for the 'topmost' call in the decltype expression. If the
  6301. /// topmost call bound a temporary, strip that temporary off the expression.
  6302. ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
  6303. assert(ExprEvalContexts.back().ExprContext ==
  6304. ExpressionEvaluationContextRecord::EK_Decltype &&
  6305. "not in a decltype expression");
  6306. ExprResult Result = CheckPlaceholderExpr(E);
  6307. if (Result.isInvalid())
  6308. return ExprError();
  6309. E = Result.get();
  6310. // C++11 [expr.call]p11:
  6311. // If a function call is a prvalue of object type,
  6312. // -- if the function call is either
  6313. // -- the operand of a decltype-specifier, or
  6314. // -- the right operand of a comma operator that is the operand of a
  6315. // decltype-specifier,
  6316. // a temporary object is not introduced for the prvalue.
  6317. // Recursively rebuild ParenExprs and comma expressions to strip out the
  6318. // outermost CXXBindTemporaryExpr, if any.
  6319. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  6320. ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
  6321. if (SubExpr.isInvalid())
  6322. return ExprError();
  6323. if (SubExpr.get() == PE->getSubExpr())
  6324. return E;
  6325. return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
  6326. }
  6327. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6328. if (BO->getOpcode() == BO_Comma) {
  6329. ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
  6330. if (RHS.isInvalid())
  6331. return ExprError();
  6332. if (RHS.get() == BO->getRHS())
  6333. return E;
  6334. return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
  6335. BO->getType(), BO->getValueKind(),
  6336. BO->getObjectKind(), BO->getOperatorLoc(),
  6337. BO->getFPFeatures(getLangOpts()));
  6338. }
  6339. }
  6340. CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
  6341. CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
  6342. : nullptr;
  6343. if (TopCall)
  6344. E = TopCall;
  6345. else
  6346. TopBind = nullptr;
  6347. // Disable the special decltype handling now.
  6348. ExprEvalContexts.back().ExprContext =
  6349. ExpressionEvaluationContextRecord::EK_Other;
  6350. Result = CheckUnevaluatedOperand(E);
  6351. if (Result.isInvalid())
  6352. return ExprError();
  6353. E = Result.get();
  6354. // In MS mode, don't perform any extra checking of call return types within a
  6355. // decltype expression.
  6356. if (getLangOpts().MSVCCompat)
  6357. return E;
  6358. // Perform the semantic checks we delayed until this point.
  6359. for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
  6360. I != N; ++I) {
  6361. CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
  6362. if (Call == TopCall)
  6363. continue;
  6364. if (CheckCallReturnType(Call->getCallReturnType(Context),
  6365. Call->getBeginLoc(), Call, Call->getDirectCallee()))
  6366. return ExprError();
  6367. }
  6368. // Now all relevant types are complete, check the destructors are accessible
  6369. // and non-deleted, and annotate them on the temporaries.
  6370. for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
  6371. I != N; ++I) {
  6372. CXXBindTemporaryExpr *Bind =
  6373. ExprEvalContexts.back().DelayedDecltypeBinds[I];
  6374. if (Bind == TopBind)
  6375. continue;
  6376. CXXTemporary *Temp = Bind->getTemporary();
  6377. CXXRecordDecl *RD =
  6378. Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  6379. CXXDestructorDecl *Destructor = LookupDestructor(RD);
  6380. Temp->setDestructor(Destructor);
  6381. MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
  6382. CheckDestructorAccess(Bind->getExprLoc(), Destructor,
  6383. PDiag(diag::err_access_dtor_temp)
  6384. << Bind->getType());
  6385. if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
  6386. return ExprError();
  6387. // We need a cleanup, but we don't need to remember the temporary.
  6388. Cleanup.setExprNeedsCleanups(true);
  6389. }
  6390. // Possibly strip off the top CXXBindTemporaryExpr.
  6391. return E;
  6392. }
  6393. /// Note a set of 'operator->' functions that were used for a member access.
  6394. static void noteOperatorArrows(Sema &S,
  6395. ArrayRef<FunctionDecl *> OperatorArrows) {
  6396. unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
  6397. // FIXME: Make this configurable?
  6398. unsigned Limit = 9;
  6399. if (OperatorArrows.size() > Limit) {
  6400. // Produce Limit-1 normal notes and one 'skipping' note.
  6401. SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
  6402. SkipCount = OperatorArrows.size() - (Limit - 1);
  6403. }
  6404. for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
  6405. if (I == SkipStart) {
  6406. S.Diag(OperatorArrows[I]->getLocation(),
  6407. diag::note_operator_arrows_suppressed)
  6408. << SkipCount;
  6409. I += SkipCount;
  6410. } else {
  6411. S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
  6412. << OperatorArrows[I]->getCallResultType();
  6413. ++I;
  6414. }
  6415. }
  6416. }
  6417. ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
  6418. SourceLocation OpLoc,
  6419. tok::TokenKind OpKind,
  6420. ParsedType &ObjectType,
  6421. bool &MayBePseudoDestructor) {
  6422. // Since this might be a postfix expression, get rid of ParenListExprs.
  6423. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
  6424. if (Result.isInvalid()) return ExprError();
  6425. Base = Result.get();
  6426. Result = CheckPlaceholderExpr(Base);
  6427. if (Result.isInvalid()) return ExprError();
  6428. Base = Result.get();
  6429. QualType BaseType = Base->getType();
  6430. MayBePseudoDestructor = false;
  6431. if (BaseType->isDependentType()) {
  6432. // If we have a pointer to a dependent type and are using the -> operator,
  6433. // the object type is the type that the pointer points to. We might still
  6434. // have enough information about that type to do something useful.
  6435. if (OpKind == tok::arrow)
  6436. if (const PointerType *Ptr = BaseType->getAs<PointerType>())
  6437. BaseType = Ptr->getPointeeType();
  6438. ObjectType = ParsedType::make(BaseType);
  6439. MayBePseudoDestructor = true;
  6440. return Base;
  6441. }
  6442. // C++ [over.match.oper]p8:
  6443. // [...] When operator->returns, the operator-> is applied to the value
  6444. // returned, with the original second operand.
  6445. if (OpKind == tok::arrow) {
  6446. QualType StartingType = BaseType;
  6447. bool NoArrowOperatorFound = false;
  6448. bool FirstIteration = true;
  6449. FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
  6450. // The set of types we've considered so far.
  6451. llvm::SmallPtrSet<CanQualType,8> CTypes;
  6452. SmallVector<FunctionDecl*, 8> OperatorArrows;
  6453. CTypes.insert(Context.getCanonicalType(BaseType));
  6454. while (BaseType->isRecordType()) {
  6455. if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
  6456. Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
  6457. << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
  6458. noteOperatorArrows(*this, OperatorArrows);
  6459. Diag(OpLoc, diag::note_operator_arrow_depth)
  6460. << getLangOpts().ArrowDepth;
  6461. return ExprError();
  6462. }
  6463. Result = BuildOverloadedArrowExpr(
  6464. S, Base, OpLoc,
  6465. // When in a template specialization and on the first loop iteration,
  6466. // potentially give the default diagnostic (with the fixit in a
  6467. // separate note) instead of having the error reported back to here
  6468. // and giving a diagnostic with a fixit attached to the error itself.
  6469. (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
  6470. ? nullptr
  6471. : &NoArrowOperatorFound);
  6472. if (Result.isInvalid()) {
  6473. if (NoArrowOperatorFound) {
  6474. if (FirstIteration) {
  6475. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  6476. << BaseType << 1 << Base->getSourceRange()
  6477. << FixItHint::CreateReplacement(OpLoc, ".");
  6478. OpKind = tok::period;
  6479. break;
  6480. }
  6481. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  6482. << BaseType << Base->getSourceRange();
  6483. CallExpr *CE = dyn_cast<CallExpr>(Base);
  6484. if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
  6485. Diag(CD->getBeginLoc(),
  6486. diag::note_member_reference_arrow_from_operator_arrow);
  6487. }
  6488. }
  6489. return ExprError();
  6490. }
  6491. Base = Result.get();
  6492. if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
  6493. OperatorArrows.push_back(OpCall->getDirectCallee());
  6494. BaseType = Base->getType();
  6495. CanQualType CBaseType = Context.getCanonicalType(BaseType);
  6496. if (!CTypes.insert(CBaseType).second) {
  6497. Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
  6498. noteOperatorArrows(*this, OperatorArrows);
  6499. return ExprError();
  6500. }
  6501. FirstIteration = false;
  6502. }
  6503. if (OpKind == tok::arrow) {
  6504. if (BaseType->isPointerType())
  6505. BaseType = BaseType->getPointeeType();
  6506. else if (auto *AT = Context.getAsArrayType(BaseType))
  6507. BaseType = AT->getElementType();
  6508. }
  6509. }
  6510. // Objective-C properties allow "." access on Objective-C pointer types,
  6511. // so adjust the base type to the object type itself.
  6512. if (BaseType->isObjCObjectPointerType())
  6513. BaseType = BaseType->getPointeeType();
  6514. // C++ [basic.lookup.classref]p2:
  6515. // [...] If the type of the object expression is of pointer to scalar
  6516. // type, the unqualified-id is looked up in the context of the complete
  6517. // postfix-expression.
  6518. //
  6519. // This also indicates that we could be parsing a pseudo-destructor-name.
  6520. // Note that Objective-C class and object types can be pseudo-destructor
  6521. // expressions or normal member (ivar or property) access expressions, and
  6522. // it's legal for the type to be incomplete if this is a pseudo-destructor
  6523. // call. We'll do more incomplete-type checks later in the lookup process,
  6524. // so just skip this check for ObjC types.
  6525. if (!BaseType->isRecordType()) {
  6526. ObjectType = ParsedType::make(BaseType);
  6527. MayBePseudoDestructor = true;
  6528. return Base;
  6529. }
  6530. // The object type must be complete (or dependent), or
  6531. // C++11 [expr.prim.general]p3:
  6532. // Unlike the object expression in other contexts, *this is not required to
  6533. // be of complete type for purposes of class member access (5.2.5) outside
  6534. // the member function body.
  6535. if (!BaseType->isDependentType() &&
  6536. !isThisOutsideMemberFunctionBody(BaseType) &&
  6537. RequireCompleteType(OpLoc, BaseType,
  6538. diag::err_incomplete_member_access)) {
  6539. return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
  6540. }
  6541. // C++ [basic.lookup.classref]p2:
  6542. // If the id-expression in a class member access (5.2.5) is an
  6543. // unqualified-id, and the type of the object expression is of a class
  6544. // type C (or of pointer to a class type C), the unqualified-id is looked
  6545. // up in the scope of class C. [...]
  6546. ObjectType = ParsedType::make(BaseType);
  6547. return Base;
  6548. }
  6549. static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
  6550. tok::TokenKind &OpKind, SourceLocation OpLoc) {
  6551. if (Base->hasPlaceholderType()) {
  6552. ExprResult result = S.CheckPlaceholderExpr(Base);
  6553. if (result.isInvalid()) return true;
  6554. Base = result.get();
  6555. }
  6556. ObjectType = Base->getType();
  6557. // C++ [expr.pseudo]p2:
  6558. // The left-hand side of the dot operator shall be of scalar type. The
  6559. // left-hand side of the arrow operator shall be of pointer to scalar type.
  6560. // This scalar type is the object type.
  6561. // Note that this is rather different from the normal handling for the
  6562. // arrow operator.
  6563. if (OpKind == tok::arrow) {
  6564. // The operator requires a prvalue, so perform lvalue conversions.
  6565. // Only do this if we might plausibly end with a pointer, as otherwise
  6566. // this was likely to be intended to be a '.'.
  6567. if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
  6568. ObjectType->isFunctionType()) {
  6569. ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);
  6570. if (BaseResult.isInvalid())
  6571. return true;
  6572. Base = BaseResult.get();
  6573. ObjectType = Base->getType();
  6574. }
  6575. if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
  6576. ObjectType = Ptr->getPointeeType();
  6577. } else if (!Base->isTypeDependent()) {
  6578. // The user wrote "p->" when they probably meant "p."; fix it.
  6579. S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  6580. << ObjectType << true
  6581. << FixItHint::CreateReplacement(OpLoc, ".");
  6582. if (S.isSFINAEContext())
  6583. return true;
  6584. OpKind = tok::period;
  6585. }
  6586. }
  6587. return false;
  6588. }
  6589. /// Check if it's ok to try and recover dot pseudo destructor calls on
  6590. /// pointer objects.
  6591. static bool
  6592. canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
  6593. QualType DestructedType) {
  6594. // If this is a record type, check if its destructor is callable.
  6595. if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
  6596. if (RD->hasDefinition())
  6597. if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
  6598. return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
  6599. return false;
  6600. }
  6601. // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
  6602. return DestructedType->isDependentType() || DestructedType->isScalarType() ||
  6603. DestructedType->isVectorType();
  6604. }
  6605. ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
  6606. SourceLocation OpLoc,
  6607. tok::TokenKind OpKind,
  6608. const CXXScopeSpec &SS,
  6609. TypeSourceInfo *ScopeTypeInfo,
  6610. SourceLocation CCLoc,
  6611. SourceLocation TildeLoc,
  6612. PseudoDestructorTypeStorage Destructed) {
  6613. TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
  6614. QualType ObjectType;
  6615. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  6616. return ExprError();
  6617. if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
  6618. !ObjectType->isVectorType()) {
  6619. if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
  6620. Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
  6621. else {
  6622. Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
  6623. << ObjectType << Base->getSourceRange();
  6624. return ExprError();
  6625. }
  6626. }
  6627. // C++ [expr.pseudo]p2:
  6628. // [...] The cv-unqualified versions of the object type and of the type
  6629. // designated by the pseudo-destructor-name shall be the same type.
  6630. if (DestructedTypeInfo) {
  6631. QualType DestructedType = DestructedTypeInfo->getType();
  6632. SourceLocation DestructedTypeStart
  6633. = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
  6634. if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
  6635. if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
  6636. // Detect dot pseudo destructor calls on pointer objects, e.g.:
  6637. // Foo *foo;
  6638. // foo.~Foo();
  6639. if (OpKind == tok::period && ObjectType->isPointerType() &&
  6640. Context.hasSameUnqualifiedType(DestructedType,
  6641. ObjectType->getPointeeType())) {
  6642. auto Diagnostic =
  6643. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  6644. << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
  6645. // Issue a fixit only when the destructor is valid.
  6646. if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
  6647. *this, DestructedType))
  6648. Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
  6649. // Recover by setting the object type to the destructed type and the
  6650. // operator to '->'.
  6651. ObjectType = DestructedType;
  6652. OpKind = tok::arrow;
  6653. } else {
  6654. Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
  6655. << ObjectType << DestructedType << Base->getSourceRange()
  6656. << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
  6657. // Recover by setting the destructed type to the object type.
  6658. DestructedType = ObjectType;
  6659. DestructedTypeInfo =
  6660. Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
  6661. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  6662. }
  6663. } else if (DestructedType.getObjCLifetime() !=
  6664. ObjectType.getObjCLifetime()) {
  6665. if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
  6666. // Okay: just pretend that the user provided the correctly-qualified
  6667. // type.
  6668. } else {
  6669. Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
  6670. << ObjectType << DestructedType << Base->getSourceRange()
  6671. << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
  6672. }
  6673. // Recover by setting the destructed type to the object type.
  6674. DestructedType = ObjectType;
  6675. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
  6676. DestructedTypeStart);
  6677. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  6678. }
  6679. }
  6680. }
  6681. // C++ [expr.pseudo]p2:
  6682. // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
  6683. // form
  6684. //
  6685. // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
  6686. //
  6687. // shall designate the same scalar type.
  6688. if (ScopeTypeInfo) {
  6689. QualType ScopeType = ScopeTypeInfo->getType();
  6690. if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
  6691. !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
  6692. Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
  6693. diag::err_pseudo_dtor_type_mismatch)
  6694. << ObjectType << ScopeType << Base->getSourceRange()
  6695. << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
  6696. ScopeType = QualType();
  6697. ScopeTypeInfo = nullptr;
  6698. }
  6699. }
  6700. Expr *Result
  6701. = new (Context) CXXPseudoDestructorExpr(Context, Base,
  6702. OpKind == tok::arrow, OpLoc,
  6703. SS.getWithLocInContext(Context),
  6704. ScopeTypeInfo,
  6705. CCLoc,
  6706. TildeLoc,
  6707. Destructed);
  6708. return Result;
  6709. }
  6710. ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
  6711. SourceLocation OpLoc,
  6712. tok::TokenKind OpKind,
  6713. CXXScopeSpec &SS,
  6714. UnqualifiedId &FirstTypeName,
  6715. SourceLocation CCLoc,
  6716. SourceLocation TildeLoc,
  6717. UnqualifiedId &SecondTypeName) {
  6718. assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
  6719. FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
  6720. "Invalid first type name in pseudo-destructor");
  6721. assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
  6722. SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
  6723. "Invalid second type name in pseudo-destructor");
  6724. QualType ObjectType;
  6725. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  6726. return ExprError();
  6727. // Compute the object type that we should use for name lookup purposes. Only
  6728. // record types and dependent types matter.
  6729. ParsedType ObjectTypePtrForLookup;
  6730. if (!SS.isSet()) {
  6731. if (ObjectType->isRecordType())
  6732. ObjectTypePtrForLookup = ParsedType::make(ObjectType);
  6733. else if (ObjectType->isDependentType())
  6734. ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
  6735. }
  6736. // Convert the name of the type being destructed (following the ~) into a
  6737. // type (with source-location information).
  6738. QualType DestructedType;
  6739. TypeSourceInfo *DestructedTypeInfo = nullptr;
  6740. PseudoDestructorTypeStorage Destructed;
  6741. if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
  6742. ParsedType T = getTypeName(*SecondTypeName.Identifier,
  6743. SecondTypeName.StartLocation,
  6744. S, &SS, true, false, ObjectTypePtrForLookup,
  6745. /*IsCtorOrDtorName*/true);
  6746. if (!T &&
  6747. ((SS.isSet() && !computeDeclContext(SS, false)) ||
  6748. (!SS.isSet() && ObjectType->isDependentType()))) {
  6749. // The name of the type being destroyed is a dependent name, and we
  6750. // couldn't find anything useful in scope. Just store the identifier and
  6751. // it's location, and we'll perform (qualified) name lookup again at
  6752. // template instantiation time.
  6753. Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
  6754. SecondTypeName.StartLocation);
  6755. } else if (!T) {
  6756. Diag(SecondTypeName.StartLocation,
  6757. diag::err_pseudo_dtor_destructor_non_type)
  6758. << SecondTypeName.Identifier << ObjectType;
  6759. if (isSFINAEContext())
  6760. return ExprError();
  6761. // Recover by assuming we had the right type all along.
  6762. DestructedType = ObjectType;
  6763. } else
  6764. DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
  6765. } else {
  6766. // Resolve the template-id to a type.
  6767. TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
  6768. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6769. TemplateId->NumArgs);
  6770. TypeResult T = ActOnTemplateIdType(S,
  6771. SS,
  6772. TemplateId->TemplateKWLoc,
  6773. TemplateId->Template,
  6774. TemplateId->Name,
  6775. TemplateId->TemplateNameLoc,
  6776. TemplateId->LAngleLoc,
  6777. TemplateArgsPtr,
  6778. TemplateId->RAngleLoc,
  6779. /*IsCtorOrDtorName*/true);
  6780. if (T.isInvalid() || !T.get()) {
  6781. // Recover by assuming we had the right type all along.
  6782. DestructedType = ObjectType;
  6783. } else
  6784. DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
  6785. }
  6786. // If we've performed some kind of recovery, (re-)build the type source
  6787. // information.
  6788. if (!DestructedType.isNull()) {
  6789. if (!DestructedTypeInfo)
  6790. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
  6791. SecondTypeName.StartLocation);
  6792. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  6793. }
  6794. // Convert the name of the scope type (the type prior to '::') into a type.
  6795. TypeSourceInfo *ScopeTypeInfo = nullptr;
  6796. QualType ScopeType;
  6797. if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
  6798. FirstTypeName.Identifier) {
  6799. if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
  6800. ParsedType T = getTypeName(*FirstTypeName.Identifier,
  6801. FirstTypeName.StartLocation,
  6802. S, &SS, true, false, ObjectTypePtrForLookup,
  6803. /*IsCtorOrDtorName*/true);
  6804. if (!T) {
  6805. Diag(FirstTypeName.StartLocation,
  6806. diag::err_pseudo_dtor_destructor_non_type)
  6807. << FirstTypeName.Identifier << ObjectType;
  6808. if (isSFINAEContext())
  6809. return ExprError();
  6810. // Just drop this type. It's unnecessary anyway.
  6811. ScopeType = QualType();
  6812. } else
  6813. ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
  6814. } else {
  6815. // Resolve the template-id to a type.
  6816. TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
  6817. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6818. TemplateId->NumArgs);
  6819. TypeResult T = ActOnTemplateIdType(S,
  6820. SS,
  6821. TemplateId->TemplateKWLoc,
  6822. TemplateId->Template,
  6823. TemplateId->Name,
  6824. TemplateId->TemplateNameLoc,
  6825. TemplateId->LAngleLoc,
  6826. TemplateArgsPtr,
  6827. TemplateId->RAngleLoc,
  6828. /*IsCtorOrDtorName*/true);
  6829. if (T.isInvalid() || !T.get()) {
  6830. // Recover by dropping this type.
  6831. ScopeType = QualType();
  6832. } else
  6833. ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
  6834. }
  6835. }
  6836. if (!ScopeType.isNull() && !ScopeTypeInfo)
  6837. ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
  6838. FirstTypeName.StartLocation);
  6839. return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
  6840. ScopeTypeInfo, CCLoc, TildeLoc,
  6841. Destructed);
  6842. }
  6843. ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
  6844. SourceLocation OpLoc,
  6845. tok::TokenKind OpKind,
  6846. SourceLocation TildeLoc,
  6847. const DeclSpec& DS) {
  6848. QualType ObjectType;
  6849. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  6850. return ExprError();
  6851. if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
  6852. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  6853. return true;
  6854. }
  6855. QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
  6856. TypeLocBuilder TLB;
  6857. DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
  6858. DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
  6859. DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
  6860. TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
  6861. PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
  6862. return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
  6863. nullptr, SourceLocation(), TildeLoc,
  6864. Destructed);
  6865. }
  6866. ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
  6867. CXXConversionDecl *Method,
  6868. bool HadMultipleCandidates) {
  6869. // Convert the expression to match the conversion function's implicit object
  6870. // parameter.
  6871. ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
  6872. FoundDecl, Method);
  6873. if (Exp.isInvalid())
  6874. return true;
  6875. if (Method->getParent()->isLambda() &&
  6876. Method->getConversionType()->isBlockPointerType()) {
  6877. // This is a lambda conversion to block pointer; check if the argument
  6878. // was a LambdaExpr.
  6879. Expr *SubE = E;
  6880. CastExpr *CE = dyn_cast<CastExpr>(SubE);
  6881. if (CE && CE->getCastKind() == CK_NoOp)
  6882. SubE = CE->getSubExpr();
  6883. SubE = SubE->IgnoreParens();
  6884. if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
  6885. SubE = BE->getSubExpr();
  6886. if (isa<LambdaExpr>(SubE)) {
  6887. // For the conversion to block pointer on a lambda expression, we
  6888. // construct a special BlockLiteral instead; this doesn't really make
  6889. // a difference in ARC, but outside of ARC the resulting block literal
  6890. // follows the normal lifetime rules for block literals instead of being
  6891. // autoreleased.
  6892. PushExpressionEvaluationContext(
  6893. ExpressionEvaluationContext::PotentiallyEvaluated);
  6894. ExprResult BlockExp = BuildBlockForLambdaConversion(
  6895. Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
  6896. PopExpressionEvaluationContext();
  6897. // FIXME: This note should be produced by a CodeSynthesisContext.
  6898. if (BlockExp.isInvalid())
  6899. Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
  6900. return BlockExp;
  6901. }
  6902. }
  6903. MemberExpr *ME =
  6904. BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
  6905. NestedNameSpecifierLoc(), SourceLocation(), Method,
  6906. DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
  6907. HadMultipleCandidates, DeclarationNameInfo(),
  6908. Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
  6909. QualType ResultType = Method->getReturnType();
  6910. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  6911. ResultType = ResultType.getNonLValueExprType(Context);
  6912. CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
  6913. Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(),
  6914. CurFPFeatureOverrides());
  6915. if (CheckFunctionCall(Method, CE,
  6916. Method->getType()->castAs<FunctionProtoType>()))
  6917. return ExprError();
  6918. return CheckForImmediateInvocation(CE, CE->getMethodDecl());
  6919. }
  6920. ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
  6921. SourceLocation RParen) {
  6922. // If the operand is an unresolved lookup expression, the expression is ill-
  6923. // formed per [over.over]p1, because overloaded function names cannot be used
  6924. // without arguments except in explicit contexts.
  6925. ExprResult R = CheckPlaceholderExpr(Operand);
  6926. if (R.isInvalid())
  6927. return R;
  6928. R = CheckUnevaluatedOperand(R.get());
  6929. if (R.isInvalid())
  6930. return ExprError();
  6931. Operand = R.get();
  6932. if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
  6933. Operand->HasSideEffects(Context, false)) {
  6934. // The expression operand for noexcept is in an unevaluated expression
  6935. // context, so side effects could result in unintended consequences.
  6936. Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  6937. }
  6938. CanThrowResult CanThrow = canThrow(Operand);
  6939. return new (Context)
  6940. CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
  6941. }
  6942. ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
  6943. Expr *Operand, SourceLocation RParen) {
  6944. return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
  6945. }
  6946. static void MaybeDecrementCount(
  6947. Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
  6948. DeclRefExpr *LHS = nullptr;
  6949. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6950. if (BO->getLHS()->getType()->isDependentType() ||
  6951. BO->getRHS()->getType()->isDependentType()) {
  6952. if (BO->getOpcode() != BO_Assign)
  6953. return;
  6954. } else if (!BO->isAssignmentOp())
  6955. return;
  6956. LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
  6957. } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
  6958. if (COCE->getOperator() != OO_Equal)
  6959. return;
  6960. LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
  6961. }
  6962. if (!LHS)
  6963. return;
  6964. VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
  6965. if (!VD)
  6966. return;
  6967. auto iter = RefsMinusAssignments.find(VD);
  6968. if (iter == RefsMinusAssignments.end())
  6969. return;
  6970. iter->getSecond()--;
  6971. }
  6972. /// Perform the conversions required for an expression used in a
  6973. /// context that ignores the result.
  6974. ExprResult Sema::IgnoredValueConversions(Expr *E) {
  6975. MaybeDecrementCount(E, RefsMinusAssignments);
  6976. if (E->hasPlaceholderType()) {
  6977. ExprResult result = CheckPlaceholderExpr(E);
  6978. if (result.isInvalid()) return E;
  6979. E = result.get();
  6980. }
  6981. // C99 6.3.2.1:
  6982. // [Except in specific positions,] an lvalue that does not have
  6983. // array type is converted to the value stored in the
  6984. // designated object (and is no longer an lvalue).
  6985. if (E->isPRValue()) {
  6986. // In C, function designators (i.e. expressions of function type)
  6987. // are r-values, but we still want to do function-to-pointer decay
  6988. // on them. This is both technically correct and convenient for
  6989. // some clients.
  6990. if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
  6991. return DefaultFunctionArrayConversion(E);
  6992. return E;
  6993. }
  6994. if (getLangOpts().CPlusPlus) {
  6995. // The C++11 standard defines the notion of a discarded-value expression;
  6996. // normally, we don't need to do anything to handle it, but if it is a
  6997. // volatile lvalue with a special form, we perform an lvalue-to-rvalue
  6998. // conversion.
  6999. if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
  7000. ExprResult Res = DefaultLvalueConversion(E);
  7001. if (Res.isInvalid())
  7002. return E;
  7003. E = Res.get();
  7004. } else {
  7005. // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
  7006. // it occurs as a discarded-value expression.
  7007. CheckUnusedVolatileAssignment(E);
  7008. }
  7009. // C++1z:
  7010. // If the expression is a prvalue after this optional conversion, the
  7011. // temporary materialization conversion is applied.
  7012. //
  7013. // We skip this step: IR generation is able to synthesize the storage for
  7014. // itself in the aggregate case, and adding the extra node to the AST is
  7015. // just clutter.
  7016. // FIXME: We don't emit lifetime markers for the temporaries due to this.
  7017. // FIXME: Do any other AST consumers care about this?
  7018. return E;
  7019. }
  7020. // GCC seems to also exclude expressions of incomplete enum type.
  7021. if (const EnumType *T = E->getType()->getAs<EnumType>()) {
  7022. if (!T->getDecl()->isComplete()) {
  7023. // FIXME: stupid workaround for a codegen bug!
  7024. E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
  7025. return E;
  7026. }
  7027. }
  7028. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  7029. if (Res.isInvalid())
  7030. return E;
  7031. E = Res.get();
  7032. if (!E->getType()->isVoidType())
  7033. RequireCompleteType(E->getExprLoc(), E->getType(),
  7034. diag::err_incomplete_type);
  7035. return E;
  7036. }
  7037. ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
  7038. // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
  7039. // it occurs as an unevaluated operand.
  7040. CheckUnusedVolatileAssignment(E);
  7041. return E;
  7042. }
  7043. // If we can unambiguously determine whether Var can never be used
  7044. // in a constant expression, return true.
  7045. // - if the variable and its initializer are non-dependent, then
  7046. // we can unambiguously check if the variable is a constant expression.
  7047. // - if the initializer is not value dependent - we can determine whether
  7048. // it can be used to initialize a constant expression. If Init can not
  7049. // be used to initialize a constant expression we conclude that Var can
  7050. // never be a constant expression.
  7051. // - FXIME: if the initializer is dependent, we can still do some analysis and
  7052. // identify certain cases unambiguously as non-const by using a Visitor:
  7053. // - such as those that involve odr-use of a ParmVarDecl, involve a new
  7054. // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
  7055. static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
  7056. ASTContext &Context) {
  7057. if (isa<ParmVarDecl>(Var)) return true;
  7058. const VarDecl *DefVD = nullptr;
  7059. // If there is no initializer - this can not be a constant expression.
  7060. if (!Var->getAnyInitializer(DefVD)) return true;
  7061. assert(DefVD);
  7062. if (DefVD->isWeak()) return false;
  7063. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  7064. Expr *Init = cast<Expr>(Eval->Value);
  7065. if (Var->getType()->isDependentType() || Init->isValueDependent()) {
  7066. // FIXME: Teach the constant evaluator to deal with the non-dependent parts
  7067. // of value-dependent expressions, and use it here to determine whether the
  7068. // initializer is a potential constant expression.
  7069. return false;
  7070. }
  7071. return !Var->isUsableInConstantExpressions(Context);
  7072. }
  7073. /// Check if the current lambda has any potential captures
  7074. /// that must be captured by any of its enclosing lambdas that are ready to
  7075. /// capture. If there is a lambda that can capture a nested
  7076. /// potential-capture, go ahead and do so. Also, check to see if any
  7077. /// variables are uncaptureable or do not involve an odr-use so do not
  7078. /// need to be captured.
  7079. static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
  7080. Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
  7081. assert(!S.isUnevaluatedContext());
  7082. assert(S.CurContext->isDependentContext());
  7083. #ifndef NDEBUG
  7084. DeclContext *DC = S.CurContext;
  7085. while (DC && isa<CapturedDecl>(DC))
  7086. DC = DC->getParent();
  7087. assert(
  7088. CurrentLSI->CallOperator == DC &&
  7089. "The current call operator must be synchronized with Sema's CurContext");
  7090. #endif // NDEBUG
  7091. const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
  7092. // All the potentially captureable variables in the current nested
  7093. // lambda (within a generic outer lambda), must be captured by an
  7094. // outer lambda that is enclosed within a non-dependent context.
  7095. CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
  7096. // If the variable is clearly identified as non-odr-used and the full
  7097. // expression is not instantiation dependent, only then do we not
  7098. // need to check enclosing lambda's for speculative captures.
  7099. // For e.g.:
  7100. // Even though 'x' is not odr-used, it should be captured.
  7101. // int test() {
  7102. // const int x = 10;
  7103. // auto L = [=](auto a) {
  7104. // (void) +x + a;
  7105. // };
  7106. // }
  7107. if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
  7108. !IsFullExprInstantiationDependent)
  7109. return;
  7110. // If we have a capture-capable lambda for the variable, go ahead and
  7111. // capture the variable in that lambda (and all its enclosing lambdas).
  7112. if (const Optional<unsigned> Index =
  7113. getStackIndexOfNearestEnclosingCaptureCapableLambda(
  7114. S.FunctionScopes, Var, S))
  7115. S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
  7116. Index.getValue());
  7117. const bool IsVarNeverAConstantExpression =
  7118. VariableCanNeverBeAConstantExpression(Var, S.Context);
  7119. if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
  7120. // This full expression is not instantiation dependent or the variable
  7121. // can not be used in a constant expression - which means
  7122. // this variable must be odr-used here, so diagnose a
  7123. // capture violation early, if the variable is un-captureable.
  7124. // This is purely for diagnosing errors early. Otherwise, this
  7125. // error would get diagnosed when the lambda becomes capture ready.
  7126. QualType CaptureType, DeclRefType;
  7127. SourceLocation ExprLoc = VarExpr->getExprLoc();
  7128. if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
  7129. /*EllipsisLoc*/ SourceLocation(),
  7130. /*BuildAndDiagnose*/false, CaptureType,
  7131. DeclRefType, nullptr)) {
  7132. // We will never be able to capture this variable, and we need
  7133. // to be able to in any and all instantiations, so diagnose it.
  7134. S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
  7135. /*EllipsisLoc*/ SourceLocation(),
  7136. /*BuildAndDiagnose*/true, CaptureType,
  7137. DeclRefType, nullptr);
  7138. }
  7139. }
  7140. });
  7141. // Check if 'this' needs to be captured.
  7142. if (CurrentLSI->hasPotentialThisCapture()) {
  7143. // If we have a capture-capable lambda for 'this', go ahead and capture
  7144. // 'this' in that lambda (and all its enclosing lambdas).
  7145. if (const Optional<unsigned> Index =
  7146. getStackIndexOfNearestEnclosingCaptureCapableLambda(
  7147. S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
  7148. const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
  7149. S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
  7150. /*Explicit*/ false, /*BuildAndDiagnose*/ true,
  7151. &FunctionScopeIndexOfCapturableLambda);
  7152. }
  7153. }
  7154. // Reset all the potential captures at the end of each full-expression.
  7155. CurrentLSI->clearPotentialCaptures();
  7156. }
  7157. static ExprResult attemptRecovery(Sema &SemaRef,
  7158. const TypoCorrectionConsumer &Consumer,
  7159. const TypoCorrection &TC) {
  7160. LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
  7161. Consumer.getLookupResult().getLookupKind());
  7162. const CXXScopeSpec *SS = Consumer.getSS();
  7163. CXXScopeSpec NewSS;
  7164. // Use an approprate CXXScopeSpec for building the expr.
  7165. if (auto *NNS = TC.getCorrectionSpecifier())
  7166. NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
  7167. else if (SS && !TC.WillReplaceSpecifier())
  7168. NewSS = *SS;
  7169. if (auto *ND = TC.getFoundDecl()) {
  7170. R.setLookupName(ND->getDeclName());
  7171. R.addDecl(ND);
  7172. if (ND->isCXXClassMember()) {
  7173. // Figure out the correct naming class to add to the LookupResult.
  7174. CXXRecordDecl *Record = nullptr;
  7175. if (auto *NNS = TC.getCorrectionSpecifier())
  7176. Record = NNS->getAsType()->getAsCXXRecordDecl();
  7177. if (!Record)
  7178. Record =
  7179. dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
  7180. if (Record)
  7181. R.setNamingClass(Record);
  7182. // Detect and handle the case where the decl might be an implicit
  7183. // member.
  7184. bool MightBeImplicitMember;
  7185. if (!Consumer.isAddressOfOperand())
  7186. MightBeImplicitMember = true;
  7187. else if (!NewSS.isEmpty())
  7188. MightBeImplicitMember = false;
  7189. else if (R.isOverloadedResult())
  7190. MightBeImplicitMember = false;
  7191. else if (R.isUnresolvableResult())
  7192. MightBeImplicitMember = true;
  7193. else
  7194. MightBeImplicitMember = isa<FieldDecl>(ND) ||
  7195. isa<IndirectFieldDecl>(ND) ||
  7196. isa<MSPropertyDecl>(ND);
  7197. if (MightBeImplicitMember)
  7198. return SemaRef.BuildPossibleImplicitMemberExpr(
  7199. NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
  7200. /*TemplateArgs*/ nullptr, /*S*/ nullptr);
  7201. } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
  7202. return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
  7203. Ivar->getIdentifier());
  7204. }
  7205. }
  7206. return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
  7207. /*AcceptInvalidDecl*/ true);
  7208. }
  7209. namespace {
  7210. class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
  7211. llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
  7212. public:
  7213. explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
  7214. : TypoExprs(TypoExprs) {}
  7215. bool VisitTypoExpr(TypoExpr *TE) {
  7216. TypoExprs.insert(TE);
  7217. return true;
  7218. }
  7219. };
  7220. class TransformTypos : public TreeTransform<TransformTypos> {
  7221. typedef TreeTransform<TransformTypos> BaseTransform;
  7222. VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
  7223. // process of being initialized.
  7224. llvm::function_ref<ExprResult(Expr *)> ExprFilter;
  7225. llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
  7226. llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
  7227. llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
  7228. /// Emit diagnostics for all of the TypoExprs encountered.
  7229. ///
  7230. /// If the TypoExprs were successfully corrected, then the diagnostics should
  7231. /// suggest the corrections. Otherwise the diagnostics will not suggest
  7232. /// anything (having been passed an empty TypoCorrection).
  7233. ///
  7234. /// If we've failed to correct due to ambiguous corrections, we need to
  7235. /// be sure to pass empty corrections and replacements. Otherwise it's
  7236. /// possible that the Consumer has a TypoCorrection that failed to ambiguity
  7237. /// and we don't want to report those diagnostics.
  7238. void EmitAllDiagnostics(bool IsAmbiguous) {
  7239. for (TypoExpr *TE : TypoExprs) {
  7240. auto &State = SemaRef.getTypoExprState(TE);
  7241. if (State.DiagHandler) {
  7242. TypoCorrection TC = IsAmbiguous
  7243. ? TypoCorrection() : State.Consumer->getCurrentCorrection();
  7244. ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
  7245. // Extract the NamedDecl from the transformed TypoExpr and add it to the
  7246. // TypoCorrection, replacing the existing decls. This ensures the right
  7247. // NamedDecl is used in diagnostics e.g. in the case where overload
  7248. // resolution was used to select one from several possible decls that
  7249. // had been stored in the TypoCorrection.
  7250. if (auto *ND = getDeclFromExpr(
  7251. Replacement.isInvalid() ? nullptr : Replacement.get()))
  7252. TC.setCorrectionDecl(ND);
  7253. State.DiagHandler(TC);
  7254. }
  7255. SemaRef.clearDelayedTypo(TE);
  7256. }
  7257. }
  7258. /// Try to advance the typo correction state of the first unfinished TypoExpr.
  7259. /// We allow advancement of the correction stream by removing it from the
  7260. /// TransformCache which allows `TransformTypoExpr` to advance during the
  7261. /// next transformation attempt.
  7262. ///
  7263. /// Any substitution attempts for the previous TypoExprs (which must have been
  7264. /// finished) will need to be retried since it's possible that they will now
  7265. /// be invalid given the latest advancement.
  7266. ///
  7267. /// We need to be sure that we're making progress - it's possible that the
  7268. /// tree is so malformed that the transform never makes it to the
  7269. /// `TransformTypoExpr`.
  7270. ///
  7271. /// Returns true if there are any untried correction combinations.
  7272. bool CheckAndAdvanceTypoExprCorrectionStreams() {
  7273. for (auto TE : TypoExprs) {
  7274. auto &State = SemaRef.getTypoExprState(TE);
  7275. TransformCache.erase(TE);
  7276. if (!State.Consumer->hasMadeAnyCorrectionProgress())
  7277. return false;
  7278. if (!State.Consumer->finished())
  7279. return true;
  7280. State.Consumer->resetCorrectionStream();
  7281. }
  7282. return false;
  7283. }
  7284. NamedDecl *getDeclFromExpr(Expr *E) {
  7285. if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
  7286. E = OverloadResolution[OE];
  7287. if (!E)
  7288. return nullptr;
  7289. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  7290. return DRE->getFoundDecl();
  7291. if (auto *ME = dyn_cast<MemberExpr>(E))
  7292. return ME->getFoundDecl();
  7293. // FIXME: Add any other expr types that could be be seen by the delayed typo
  7294. // correction TreeTransform for which the corresponding TypoCorrection could
  7295. // contain multiple decls.
  7296. return nullptr;
  7297. }
  7298. ExprResult TryTransform(Expr *E) {
  7299. Sema::SFINAETrap Trap(SemaRef);
  7300. ExprResult Res = TransformExpr(E);
  7301. if (Trap.hasErrorOccurred() || Res.isInvalid())
  7302. return ExprError();
  7303. return ExprFilter(Res.get());
  7304. }
  7305. // Since correcting typos may intoduce new TypoExprs, this function
  7306. // checks for new TypoExprs and recurses if it finds any. Note that it will
  7307. // only succeed if it is able to correct all typos in the given expression.
  7308. ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
  7309. if (Res.isInvalid()) {
  7310. return Res;
  7311. }
  7312. // Check to see if any new TypoExprs were created. If so, we need to recurse
  7313. // to check their validity.
  7314. Expr *FixedExpr = Res.get();
  7315. auto SavedTypoExprs = std::move(TypoExprs);
  7316. auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
  7317. TypoExprs.clear();
  7318. AmbiguousTypoExprs.clear();
  7319. FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
  7320. if (!TypoExprs.empty()) {
  7321. // Recurse to handle newly created TypoExprs. If we're not able to
  7322. // handle them, discard these TypoExprs.
  7323. ExprResult RecurResult =
  7324. RecursiveTransformLoop(FixedExpr, IsAmbiguous);
  7325. if (RecurResult.isInvalid()) {
  7326. Res = ExprError();
  7327. // Recursive corrections didn't work, wipe them away and don't add
  7328. // them to the TypoExprs set. Remove them from Sema's TypoExpr list
  7329. // since we don't want to clear them twice. Note: it's possible the
  7330. // TypoExprs were created recursively and thus won't be in our
  7331. // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
  7332. auto &SemaTypoExprs = SemaRef.TypoExprs;
  7333. for (auto TE : TypoExprs) {
  7334. TransformCache.erase(TE);
  7335. SemaRef.clearDelayedTypo(TE);
  7336. auto SI = find(SemaTypoExprs, TE);
  7337. if (SI != SemaTypoExprs.end()) {
  7338. SemaTypoExprs.erase(SI);
  7339. }
  7340. }
  7341. } else {
  7342. // TypoExpr is valid: add newly created TypoExprs since we were
  7343. // able to correct them.
  7344. Res = RecurResult;
  7345. SavedTypoExprs.set_union(TypoExprs);
  7346. }
  7347. }
  7348. TypoExprs = std::move(SavedTypoExprs);
  7349. AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
  7350. return Res;
  7351. }
  7352. // Try to transform the given expression, looping through the correction
  7353. // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
  7354. //
  7355. // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
  7356. // true and this method immediately will return an `ExprError`.
  7357. ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
  7358. ExprResult Res;
  7359. auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
  7360. SemaRef.TypoExprs.clear();
  7361. while (true) {
  7362. Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
  7363. // Recursion encountered an ambiguous correction. This means that our
  7364. // correction itself is ambiguous, so stop now.
  7365. if (IsAmbiguous)
  7366. break;
  7367. // If the transform is still valid after checking for any new typos,
  7368. // it's good to go.
  7369. if (!Res.isInvalid())
  7370. break;
  7371. // The transform was invalid, see if we have any TypoExprs with untried
  7372. // correction candidates.
  7373. if (!CheckAndAdvanceTypoExprCorrectionStreams())
  7374. break;
  7375. }
  7376. // If we found a valid result, double check to make sure it's not ambiguous.
  7377. if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
  7378. auto SavedTransformCache =
  7379. llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
  7380. // Ensure none of the TypoExprs have multiple typo correction candidates
  7381. // with the same edit length that pass all the checks and filters.
  7382. while (!AmbiguousTypoExprs.empty()) {
  7383. auto TE = AmbiguousTypoExprs.back();
  7384. // TryTransform itself can create new Typos, adding them to the TypoExpr map
  7385. // and invalidating our TypoExprState, so always fetch it instead of storing.
  7386. SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
  7387. TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
  7388. TypoCorrection Next;
  7389. do {
  7390. // Fetch the next correction by erasing the typo from the cache and calling
  7391. // `TryTransform` which will iterate through corrections in
  7392. // `TransformTypoExpr`.
  7393. TransformCache.erase(TE);
  7394. ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
  7395. if (!AmbigRes.isInvalid() || IsAmbiguous) {
  7396. SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
  7397. SavedTransformCache.erase(TE);
  7398. Res = ExprError();
  7399. IsAmbiguous = true;
  7400. break;
  7401. }
  7402. } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
  7403. Next.getEditDistance(false) == TC.getEditDistance(false));
  7404. if (IsAmbiguous)
  7405. break;
  7406. AmbiguousTypoExprs.remove(TE);
  7407. SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
  7408. TransformCache[TE] = SavedTransformCache[TE];
  7409. }
  7410. TransformCache = std::move(SavedTransformCache);
  7411. }
  7412. // Wipe away any newly created TypoExprs that we don't know about. Since we
  7413. // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
  7414. // possible if a `TypoExpr` is created during a transformation but then
  7415. // fails before we can discover it.
  7416. auto &SemaTypoExprs = SemaRef.TypoExprs;
  7417. for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
  7418. auto TE = *Iterator;
  7419. auto FI = find(TypoExprs, TE);
  7420. if (FI != TypoExprs.end()) {
  7421. Iterator++;
  7422. continue;
  7423. }
  7424. SemaRef.clearDelayedTypo(TE);
  7425. Iterator = SemaTypoExprs.erase(Iterator);
  7426. }
  7427. SemaRef.TypoExprs = std::move(SavedTypoExprs);
  7428. return Res;
  7429. }
  7430. public:
  7431. TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
  7432. : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
  7433. ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
  7434. MultiExprArg Args,
  7435. SourceLocation RParenLoc,
  7436. Expr *ExecConfig = nullptr) {
  7437. auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
  7438. RParenLoc, ExecConfig);
  7439. if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
  7440. if (Result.isUsable()) {
  7441. Expr *ResultCall = Result.get();
  7442. if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
  7443. ResultCall = BE->getSubExpr();
  7444. if (auto *CE = dyn_cast<CallExpr>(ResultCall))
  7445. OverloadResolution[OE] = CE->getCallee();
  7446. }
  7447. }
  7448. return Result;
  7449. }
  7450. ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
  7451. ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
  7452. ExprResult Transform(Expr *E) {
  7453. bool IsAmbiguous = false;
  7454. ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
  7455. if (!Res.isUsable())
  7456. FindTypoExprs(TypoExprs).TraverseStmt(E);
  7457. EmitAllDiagnostics(IsAmbiguous);
  7458. return Res;
  7459. }
  7460. ExprResult TransformTypoExpr(TypoExpr *E) {
  7461. // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
  7462. // cached transformation result if there is one and the TypoExpr isn't the
  7463. // first one that was encountered.
  7464. auto &CacheEntry = TransformCache[E];
  7465. if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
  7466. return CacheEntry;
  7467. }
  7468. auto &State = SemaRef.getTypoExprState(E);
  7469. assert(State.Consumer && "Cannot transform a cleared TypoExpr");
  7470. // For the first TypoExpr and an uncached TypoExpr, find the next likely
  7471. // typo correction and return it.
  7472. while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
  7473. if (InitDecl && TC.getFoundDecl() == InitDecl)
  7474. continue;
  7475. // FIXME: If we would typo-correct to an invalid declaration, it's
  7476. // probably best to just suppress all errors from this typo correction.
  7477. ExprResult NE = State.RecoveryHandler ?
  7478. State.RecoveryHandler(SemaRef, E, TC) :
  7479. attemptRecovery(SemaRef, *State.Consumer, TC);
  7480. if (!NE.isInvalid()) {
  7481. // Check whether there may be a second viable correction with the same
  7482. // edit distance; if so, remember this TypoExpr may have an ambiguous
  7483. // correction so it can be more thoroughly vetted later.
  7484. TypoCorrection Next;
  7485. if ((Next = State.Consumer->peekNextCorrection()) &&
  7486. Next.getEditDistance(false) == TC.getEditDistance(false)) {
  7487. AmbiguousTypoExprs.insert(E);
  7488. } else {
  7489. AmbiguousTypoExprs.remove(E);
  7490. }
  7491. assert(!NE.isUnset() &&
  7492. "Typo was transformed into a valid-but-null ExprResult");
  7493. return CacheEntry = NE;
  7494. }
  7495. }
  7496. return CacheEntry = ExprError();
  7497. }
  7498. };
  7499. }
  7500. ExprResult
  7501. Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
  7502. bool RecoverUncorrectedTypos,
  7503. llvm::function_ref<ExprResult(Expr *)> Filter) {
  7504. // If the current evaluation context indicates there are uncorrected typos
  7505. // and the current expression isn't guaranteed to not have typos, try to
  7506. // resolve any TypoExpr nodes that might be in the expression.
  7507. if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
  7508. (E->isTypeDependent() || E->isValueDependent() ||
  7509. E->isInstantiationDependent())) {
  7510. auto TyposResolved = DelayedTypos.size();
  7511. auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
  7512. TyposResolved -= DelayedTypos.size();
  7513. if (Result.isInvalid() || Result.get() != E) {
  7514. ExprEvalContexts.back().NumTypos -= TyposResolved;
  7515. if (Result.isInvalid() && RecoverUncorrectedTypos) {
  7516. struct TyposReplace : TreeTransform<TyposReplace> {
  7517. TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
  7518. ExprResult TransformTypoExpr(clang::TypoExpr *E) {
  7519. return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
  7520. E->getEndLoc(), {});
  7521. }
  7522. } TT(*this);
  7523. return TT.TransformExpr(E);
  7524. }
  7525. return Result;
  7526. }
  7527. assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
  7528. }
  7529. return E;
  7530. }
  7531. ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
  7532. bool DiscardedValue,
  7533. bool IsConstexpr) {
  7534. ExprResult FullExpr = FE;
  7535. if (!FullExpr.get())
  7536. return ExprError();
  7537. if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
  7538. return ExprError();
  7539. if (DiscardedValue) {
  7540. // Top-level expressions default to 'id' when we're in a debugger.
  7541. if (getLangOpts().DebuggerCastResultToId &&
  7542. FullExpr.get()->getType() == Context.UnknownAnyTy) {
  7543. FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
  7544. if (FullExpr.isInvalid())
  7545. return ExprError();
  7546. }
  7547. FullExpr = CheckPlaceholderExpr(FullExpr.get());
  7548. if (FullExpr.isInvalid())
  7549. return ExprError();
  7550. FullExpr = IgnoredValueConversions(FullExpr.get());
  7551. if (FullExpr.isInvalid())
  7552. return ExprError();
  7553. DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
  7554. }
  7555. FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
  7556. /*RecoverUncorrectedTypos=*/true);
  7557. if (FullExpr.isInvalid())
  7558. return ExprError();
  7559. CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
  7560. // At the end of this full expression (which could be a deeply nested
  7561. // lambda), if there is a potential capture within the nested lambda,
  7562. // have the outer capture-able lambda try and capture it.
  7563. // Consider the following code:
  7564. // void f(int, int);
  7565. // void f(const int&, double);
  7566. // void foo() {
  7567. // const int x = 10, y = 20;
  7568. // auto L = [=](auto a) {
  7569. // auto M = [=](auto b) {
  7570. // f(x, b); <-- requires x to be captured by L and M
  7571. // f(y, a); <-- requires y to be captured by L, but not all Ms
  7572. // };
  7573. // };
  7574. // }
  7575. // FIXME: Also consider what happens for something like this that involves
  7576. // the gnu-extension statement-expressions or even lambda-init-captures:
  7577. // void f() {
  7578. // const int n = 0;
  7579. // auto L = [&](auto a) {
  7580. // +n + ({ 0; a; });
  7581. // };
  7582. // }
  7583. //
  7584. // Here, we see +n, and then the full-expression 0; ends, so we don't
  7585. // capture n (and instead remove it from our list of potential captures),
  7586. // and then the full-expression +n + ({ 0; }); ends, but it's too late
  7587. // for us to see that we need to capture n after all.
  7588. LambdaScopeInfo *const CurrentLSI =
  7589. getCurLambda(/*IgnoreCapturedRegions=*/true);
  7590. // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
  7591. // even if CurContext is not a lambda call operator. Refer to that Bug Report
  7592. // for an example of the code that might cause this asynchrony.
  7593. // By ensuring we are in the context of a lambda's call operator
  7594. // we can fix the bug (we only need to check whether we need to capture
  7595. // if we are within a lambda's body); but per the comments in that
  7596. // PR, a proper fix would entail :
  7597. // "Alternative suggestion:
  7598. // - Add to Sema an integer holding the smallest (outermost) scope
  7599. // index that we are *lexically* within, and save/restore/set to
  7600. // FunctionScopes.size() in InstantiatingTemplate's
  7601. // constructor/destructor.
  7602. // - Teach the handful of places that iterate over FunctionScopes to
  7603. // stop at the outermost enclosing lexical scope."
  7604. DeclContext *DC = CurContext;
  7605. while (DC && isa<CapturedDecl>(DC))
  7606. DC = DC->getParent();
  7607. const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
  7608. if (IsInLambdaDeclContext && CurrentLSI &&
  7609. CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
  7610. CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
  7611. *this);
  7612. return MaybeCreateExprWithCleanups(FullExpr);
  7613. }
  7614. StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
  7615. if (!FullStmt) return StmtError();
  7616. return MaybeCreateStmtWithCleanups(FullStmt);
  7617. }
  7618. Sema::IfExistsResult
  7619. Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
  7620. CXXScopeSpec &SS,
  7621. const DeclarationNameInfo &TargetNameInfo) {
  7622. DeclarationName TargetName = TargetNameInfo.getName();
  7623. if (!TargetName)
  7624. return IER_DoesNotExist;
  7625. // If the name itself is dependent, then the result is dependent.
  7626. if (TargetName.isDependentName())
  7627. return IER_Dependent;
  7628. // Do the redeclaration lookup in the current scope.
  7629. LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
  7630. Sema::NotForRedeclaration);
  7631. LookupParsedName(R, S, &SS);
  7632. R.suppressDiagnostics();
  7633. switch (R.getResultKind()) {
  7634. case LookupResult::Found:
  7635. case LookupResult::FoundOverloaded:
  7636. case LookupResult::FoundUnresolvedValue:
  7637. case LookupResult::Ambiguous:
  7638. return IER_Exists;
  7639. case LookupResult::NotFound:
  7640. return IER_DoesNotExist;
  7641. case LookupResult::NotFoundInCurrentInstantiation:
  7642. return IER_Dependent;
  7643. }
  7644. llvm_unreachable("Invalid LookupResult Kind!");
  7645. }
  7646. Sema::IfExistsResult
  7647. Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
  7648. bool IsIfExists, CXXScopeSpec &SS,
  7649. UnqualifiedId &Name) {
  7650. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  7651. // Check for an unexpanded parameter pack.
  7652. auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
  7653. if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
  7654. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
  7655. return IER_Error;
  7656. return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
  7657. }
  7658. concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
  7659. return BuildExprRequirement(E, /*IsSimple=*/true,
  7660. /*NoexceptLoc=*/SourceLocation(),
  7661. /*ReturnTypeRequirement=*/{});
  7662. }
  7663. concepts::Requirement *
  7664. Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
  7665. SourceLocation NameLoc, IdentifierInfo *TypeName,
  7666. TemplateIdAnnotation *TemplateId) {
  7667. assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
  7668. "Exactly one of TypeName and TemplateId must be specified.");
  7669. TypeSourceInfo *TSI = nullptr;
  7670. if (TypeName) {
  7671. QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
  7672. SS.getWithLocInContext(Context), *TypeName,
  7673. NameLoc, &TSI, /*DeducedTSTContext=*/false);
  7674. if (T.isNull())
  7675. return nullptr;
  7676. } else {
  7677. ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
  7678. TemplateId->NumArgs);
  7679. TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
  7680. TemplateId->TemplateKWLoc,
  7681. TemplateId->Template, TemplateId->Name,
  7682. TemplateId->TemplateNameLoc,
  7683. TemplateId->LAngleLoc, ArgsPtr,
  7684. TemplateId->RAngleLoc);
  7685. if (T.isInvalid())
  7686. return nullptr;
  7687. if (GetTypeFromParser(T.get(), &TSI).isNull())
  7688. return nullptr;
  7689. }
  7690. return BuildTypeRequirement(TSI);
  7691. }
  7692. concepts::Requirement *
  7693. Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
  7694. return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
  7695. /*ReturnTypeRequirement=*/{});
  7696. }
  7697. concepts::Requirement *
  7698. Sema::ActOnCompoundRequirement(
  7699. Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
  7700. TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
  7701. // C++2a [expr.prim.req.compound] p1.3.3
  7702. // [..] the expression is deduced against an invented function template
  7703. // F [...] F is a void function template with a single type template
  7704. // parameter T declared with the constrained-parameter. Form a new
  7705. // cv-qualifier-seq cv by taking the union of const and volatile specifiers
  7706. // around the constrained-parameter. F has a single parameter whose
  7707. // type-specifier is cv T followed by the abstract-declarator. [...]
  7708. //
  7709. // The cv part is done in the calling function - we get the concept with
  7710. // arguments and the abstract declarator with the correct CV qualification and
  7711. // have to synthesize T and the single parameter of F.
  7712. auto &II = Context.Idents.get("expr-type");
  7713. auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
  7714. SourceLocation(),
  7715. SourceLocation(), Depth,
  7716. /*Index=*/0, &II,
  7717. /*Typename=*/true,
  7718. /*ParameterPack=*/false,
  7719. /*HasTypeConstraint=*/true);
  7720. if (BuildTypeConstraint(SS, TypeConstraint, TParam,
  7721. /*EllipsisLoc=*/SourceLocation(),
  7722. /*AllowUnexpandedPack=*/true))
  7723. // Just produce a requirement with no type requirements.
  7724. return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
  7725. auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
  7726. SourceLocation(),
  7727. ArrayRef<NamedDecl *>(TParam),
  7728. SourceLocation(),
  7729. /*RequiresClause=*/nullptr);
  7730. return BuildExprRequirement(
  7731. E, /*IsSimple=*/false, NoexceptLoc,
  7732. concepts::ExprRequirement::ReturnTypeRequirement(TPL));
  7733. }
  7734. concepts::ExprRequirement *
  7735. Sema::BuildExprRequirement(
  7736. Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
  7737. concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
  7738. auto Status = concepts::ExprRequirement::SS_Satisfied;
  7739. ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
  7740. if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
  7741. Status = concepts::ExprRequirement::SS_Dependent;
  7742. else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
  7743. Status = concepts::ExprRequirement::SS_NoexceptNotMet;
  7744. else if (ReturnTypeRequirement.isSubstitutionFailure())
  7745. Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
  7746. else if (ReturnTypeRequirement.isTypeConstraint()) {
  7747. // C++2a [expr.prim.req]p1.3.3
  7748. // The immediately-declared constraint ([temp]) of decltype((E)) shall
  7749. // be satisfied.
  7750. TemplateParameterList *TPL =
  7751. ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
  7752. QualType MatchedType =
  7753. Context.getReferenceQualifiedType(E).getCanonicalType();
  7754. llvm::SmallVector<TemplateArgument, 1> Args;
  7755. Args.push_back(TemplateArgument(MatchedType));
  7756. TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
  7757. MultiLevelTemplateArgumentList MLTAL(TAL);
  7758. for (unsigned I = 0; I < TPL->getDepth(); ++I)
  7759. MLTAL.addOuterRetainedLevel();
  7760. Expr *IDC =
  7761. cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint()
  7762. ->getImmediatelyDeclaredConstraint();
  7763. ExprResult Constraint = SubstExpr(IDC, MLTAL);
  7764. assert(!Constraint.isInvalid() &&
  7765. "Substitution cannot fail as it is simply putting a type template "
  7766. "argument into a concept specialization expression's parameter.");
  7767. SubstitutedConstraintExpr =
  7768. cast<ConceptSpecializationExpr>(Constraint.get());
  7769. if (!SubstitutedConstraintExpr->isSatisfied())
  7770. Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
  7771. }
  7772. return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
  7773. ReturnTypeRequirement, Status,
  7774. SubstitutedConstraintExpr);
  7775. }
  7776. concepts::ExprRequirement *
  7777. Sema::BuildExprRequirement(
  7778. concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
  7779. bool IsSimple, SourceLocation NoexceptLoc,
  7780. concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
  7781. return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
  7782. IsSimple, NoexceptLoc,
  7783. ReturnTypeRequirement);
  7784. }
  7785. concepts::TypeRequirement *
  7786. Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
  7787. return new (Context) concepts::TypeRequirement(Type);
  7788. }
  7789. concepts::TypeRequirement *
  7790. Sema::BuildTypeRequirement(
  7791. concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
  7792. return new (Context) concepts::TypeRequirement(SubstDiag);
  7793. }
  7794. concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
  7795. return BuildNestedRequirement(Constraint);
  7796. }
  7797. concepts::NestedRequirement *
  7798. Sema::BuildNestedRequirement(Expr *Constraint) {
  7799. ConstraintSatisfaction Satisfaction;
  7800. if (!Constraint->isInstantiationDependent() &&
  7801. CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
  7802. Constraint->getSourceRange(), Satisfaction))
  7803. return nullptr;
  7804. return new (Context) concepts::NestedRequirement(Context, Constraint,
  7805. Satisfaction);
  7806. }
  7807. concepts::NestedRequirement *
  7808. Sema::BuildNestedRequirement(
  7809. concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
  7810. return new (Context) concepts::NestedRequirement(SubstDiag);
  7811. }
  7812. RequiresExprBodyDecl *
  7813. Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
  7814. ArrayRef<ParmVarDecl *> LocalParameters,
  7815. Scope *BodyScope) {
  7816. assert(BodyScope);
  7817. RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
  7818. RequiresKWLoc);
  7819. PushDeclContext(BodyScope, Body);
  7820. for (ParmVarDecl *Param : LocalParameters) {
  7821. if (Param->hasDefaultArg())
  7822. // C++2a [expr.prim.req] p4
  7823. // [...] A local parameter of a requires-expression shall not have a
  7824. // default argument. [...]
  7825. Diag(Param->getDefaultArgRange().getBegin(),
  7826. diag::err_requires_expr_local_parameter_default_argument);
  7827. // Ignore default argument and move on
  7828. Param->setDeclContext(Body);
  7829. // If this has an identifier, add it to the scope stack.
  7830. if (Param->getIdentifier()) {
  7831. CheckShadow(BodyScope, Param);
  7832. PushOnScopeChains(Param, BodyScope);
  7833. }
  7834. }
  7835. return Body;
  7836. }
  7837. void Sema::ActOnFinishRequiresExpr() {
  7838. assert(CurContext && "DeclContext imbalance!");
  7839. CurContext = CurContext->getLexicalParent();
  7840. assert(CurContext && "Popped translation unit!");
  7841. }
  7842. ExprResult
  7843. Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
  7844. RequiresExprBodyDecl *Body,
  7845. ArrayRef<ParmVarDecl *> LocalParameters,
  7846. ArrayRef<concepts::Requirement *> Requirements,
  7847. SourceLocation ClosingBraceLoc) {
  7848. auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
  7849. Requirements, ClosingBraceLoc);
  7850. if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
  7851. return ExprError();
  7852. return RE;
  7853. }