SemaExprCXX.cpp 269 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825
  1. //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief Implements semantic analysis for C++ expressions.
  12. ///
  13. //===----------------------------------------------------------------------===//
  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/PartialDiagnostic.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/Lex/Preprocessor.h"
  29. #include "clang/Sema/DeclSpec.h"
  30. #include "clang/Sema/Initialization.h"
  31. #include "clang/Sema/Lookup.h"
  32. #include "clang/Sema/ParsedTemplate.h"
  33. #include "clang/Sema/Scope.h"
  34. #include "clang/Sema/ScopeInfo.h"
  35. #include "clang/Sema/SemaLambda.h"
  36. #include "clang/Sema/TemplateDeduction.h"
  37. #include "llvm/ADT/APInt.h"
  38. #include "llvm/ADT/STLExtras.h"
  39. #include "llvm/Support/ErrorHandling.h"
  40. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  41. using namespace clang;
  42. using namespace sema;
  43. /// \brief 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::getDestructorName(SourceLocation TildeLoc,
  77. IdentifierInfo &II,
  78. SourceLocation NameLoc,
  79. Scope *S, CXXScopeSpec &SS,
  80. ParsedType ObjectTypePtr,
  81. bool EnteringContext) {
  82. // Determine where to perform name lookup.
  83. // FIXME: This area of the standard is very messy, and the current
  84. // wording is rather unclear about which scopes we search for the
  85. // destructor name; see core issues 399 and 555. Issue 399 in
  86. // particular shows where the current description of destructor name
  87. // lookup is completely out of line with existing practice, e.g.,
  88. // this appears to be ill-formed:
  89. //
  90. // namespace N {
  91. // template <typename T> struct S {
  92. // ~S();
  93. // };
  94. // }
  95. //
  96. // void f(N::S<int>* s) {
  97. // s->N::S<int>::~S();
  98. // }
  99. //
  100. // See also PR6358 and PR6359.
  101. // For this reason, we're currently only doing the C++03 version of this
  102. // code; the C++0x version has to wait until we get a proper spec.
  103. QualType SearchType;
  104. DeclContext *LookupCtx = nullptr;
  105. bool isDependent = false;
  106. bool LookInScope = false;
  107. if (SS.isInvalid())
  108. return ParsedType();
  109. // If we have an object type, it's because we are in a
  110. // pseudo-destructor-expression or a member access expression, and
  111. // we know what type we're looking for.
  112. if (ObjectTypePtr)
  113. SearchType = GetTypeFromParser(ObjectTypePtr);
  114. if (SS.isSet()) {
  115. NestedNameSpecifier *NNS = SS.getScopeRep();
  116. bool AlreadySearched = false;
  117. bool LookAtPrefix = true;
  118. // C++11 [basic.lookup.qual]p6:
  119. // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
  120. // the type-names are looked up as types in the scope designated by the
  121. // nested-name-specifier. Similarly, in a qualified-id of the form:
  122. //
  123. // nested-name-specifier[opt] class-name :: ~ class-name
  124. //
  125. // the second class-name is looked up in the same scope as the first.
  126. //
  127. // Here, we determine whether the code below is permitted to look at the
  128. // prefix of the nested-name-specifier.
  129. DeclContext *DC = computeDeclContext(SS, EnteringContext);
  130. if (DC && DC->isFileContext()) {
  131. AlreadySearched = true;
  132. LookupCtx = DC;
  133. isDependent = false;
  134. } else if (DC && isa<CXXRecordDecl>(DC)) {
  135. LookAtPrefix = false;
  136. LookInScope = true;
  137. }
  138. // The second case from the C++03 rules quoted further above.
  139. NestedNameSpecifier *Prefix = nullptr;
  140. if (AlreadySearched) {
  141. // Nothing left to do.
  142. } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
  143. CXXScopeSpec PrefixSS;
  144. PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
  145. LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
  146. isDependent = isDependentScopeSpecifier(PrefixSS);
  147. } else if (ObjectTypePtr) {
  148. LookupCtx = computeDeclContext(SearchType);
  149. isDependent = SearchType->isDependentType();
  150. } else {
  151. LookupCtx = computeDeclContext(SS, EnteringContext);
  152. isDependent = LookupCtx && LookupCtx->isDependentContext();
  153. }
  154. } else if (ObjectTypePtr) {
  155. // C++ [basic.lookup.classref]p3:
  156. // If the unqualified-id is ~type-name, the type-name is looked up
  157. // in the context of the entire postfix-expression. If the type T
  158. // of the object expression is of a class type C, the type-name is
  159. // also looked up in the scope of class C. At least one of the
  160. // lookups shall find a name that refers to (possibly
  161. // cv-qualified) T.
  162. LookupCtx = computeDeclContext(SearchType);
  163. isDependent = SearchType->isDependentType();
  164. assert((isDependent || !SearchType->isIncompleteType()) &&
  165. "Caller should have completed object type");
  166. LookInScope = true;
  167. } else {
  168. // Perform lookup into the current scope (only).
  169. LookInScope = true;
  170. }
  171. TypeDecl *NonMatchingTypeDecl = nullptr;
  172. LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
  173. for (unsigned Step = 0; Step != 2; ++Step) {
  174. // Look for the name first in the computed lookup context (if we
  175. // have one) and, if that fails to find a match, in the scope (if
  176. // we're allowed to look there).
  177. Found.clear();
  178. if (Step == 0 && LookupCtx)
  179. LookupQualifiedName(Found, LookupCtx);
  180. else if (Step == 1 && LookInScope && S)
  181. LookupName(Found, S);
  182. else
  183. continue;
  184. // FIXME: Should we be suppressing ambiguities here?
  185. if (Found.isAmbiguous())
  186. return ParsedType();
  187. if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
  188. QualType T = Context.getTypeDeclType(Type);
  189. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  190. if (SearchType.isNull() || SearchType->isDependentType() ||
  191. Context.hasSameUnqualifiedType(T, SearchType)) {
  192. // We found our type!
  193. return CreateParsedType(T,
  194. Context.getTrivialTypeSourceInfo(T, NameLoc));
  195. }
  196. if (!SearchType.isNull())
  197. NonMatchingTypeDecl = Type;
  198. }
  199. // If the name that we found is a class template name, and it is
  200. // the same name as the template name in the last part of the
  201. // nested-name-specifier (if present) or the object type, then
  202. // this is the destructor for that class.
  203. // FIXME: This is a workaround until we get real drafting for core
  204. // issue 399, for which there isn't even an obvious direction.
  205. if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
  206. QualType MemberOfType;
  207. if (SS.isSet()) {
  208. if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
  209. // Figure out the type of the context, if it has one.
  210. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
  211. MemberOfType = Context.getTypeDeclType(Record);
  212. }
  213. }
  214. if (MemberOfType.isNull())
  215. MemberOfType = SearchType;
  216. if (MemberOfType.isNull())
  217. continue;
  218. // We're referring into a class template specialization. If the
  219. // class template we found is the same as the template being
  220. // specialized, we found what we are looking for.
  221. if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
  222. if (ClassTemplateSpecializationDecl *Spec
  223. = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
  224. if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
  225. Template->getCanonicalDecl())
  226. return CreateParsedType(
  227. MemberOfType,
  228. Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
  229. }
  230. continue;
  231. }
  232. // We're referring to an unresolved class template
  233. // specialization. Determine whether we class template we found
  234. // is the same as the template being specialized or, if we don't
  235. // know which template is being specialized, that it at least
  236. // has the same name.
  237. if (const TemplateSpecializationType *SpecType
  238. = MemberOfType->getAs<TemplateSpecializationType>()) {
  239. TemplateName SpecName = SpecType->getTemplateName();
  240. // The class template we found is the same template being
  241. // specialized.
  242. if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
  243. if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
  244. return CreateParsedType(
  245. MemberOfType,
  246. Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
  247. continue;
  248. }
  249. // The class template we found has the same name as the
  250. // (dependent) template name being specialized.
  251. if (DependentTemplateName *DepTemplate
  252. = SpecName.getAsDependentTemplateName()) {
  253. if (DepTemplate->isIdentifier() &&
  254. DepTemplate->getIdentifier() == Template->getIdentifier())
  255. return CreateParsedType(
  256. MemberOfType,
  257. Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
  258. continue;
  259. }
  260. }
  261. }
  262. }
  263. if (isDependent) {
  264. // We didn't find our type, but that's okay: it's dependent
  265. // anyway.
  266. // FIXME: What if we have no nested-name-specifier?
  267. QualType T = CheckTypenameType(ETK_None, SourceLocation(),
  268. SS.getWithLocInContext(Context),
  269. II, NameLoc);
  270. return ParsedType::make(T);
  271. }
  272. if (NonMatchingTypeDecl) {
  273. QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
  274. Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
  275. << T << SearchType;
  276. Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
  277. << T;
  278. } else if (ObjectTypePtr)
  279. Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
  280. << &II;
  281. else {
  282. SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
  283. diag::err_destructor_class_name);
  284. if (S) {
  285. const DeclContext *Ctx = S->getEntity();
  286. if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
  287. DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
  288. Class->getNameAsString());
  289. }
  290. }
  291. return ParsedType();
  292. }
  293. ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
  294. if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
  295. return ParsedType();
  296. assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
  297. && "only get destructor types from declspecs");
  298. QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  299. QualType SearchType = GetTypeFromParser(ObjectType);
  300. if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
  301. return ParsedType::make(T);
  302. }
  303. Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
  304. << T << SearchType;
  305. return ParsedType();
  306. }
  307. bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
  308. const UnqualifiedId &Name) {
  309. assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
  310. if (!SS.isValid())
  311. return false;
  312. switch (SS.getScopeRep()->getKind()) {
  313. case NestedNameSpecifier::Identifier:
  314. case NestedNameSpecifier::TypeSpec:
  315. case NestedNameSpecifier::TypeSpecWithTemplate:
  316. // Per C++11 [over.literal]p2, literal operators can only be declared at
  317. // namespace scope. Therefore, this unqualified-id cannot name anything.
  318. // Reject it early, because we have no AST representation for this in the
  319. // case where the scope is dependent.
  320. Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
  321. << SS.getScopeRep();
  322. return true;
  323. case NestedNameSpecifier::Global:
  324. case NestedNameSpecifier::Super:
  325. case NestedNameSpecifier::Namespace:
  326. case NestedNameSpecifier::NamespaceAlias:
  327. return false;
  328. }
  329. llvm_unreachable("unknown nested name specifier kind");
  330. }
  331. /// \brief Build a C++ typeid expression with a type operand.
  332. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
  333. SourceLocation TypeidLoc,
  334. TypeSourceInfo *Operand,
  335. SourceLocation RParenLoc) {
  336. // C++ [expr.typeid]p4:
  337. // The top-level cv-qualifiers of the lvalue expression or the type-id
  338. // that is the operand of typeid are always ignored.
  339. // If the type of the type-id is a class type or a reference to a class
  340. // type, the class shall be completely-defined.
  341. Qualifiers Quals;
  342. QualType T
  343. = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
  344. Quals);
  345. if (T->getAs<RecordType>() &&
  346. RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
  347. return ExprError();
  348. if (T->isVariablyModifiedType())
  349. return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
  350. return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
  351. SourceRange(TypeidLoc, RParenLoc));
  352. }
  353. /// \brief Build a C++ typeid expression with an expression operand.
  354. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
  355. SourceLocation TypeidLoc,
  356. Expr *E,
  357. SourceLocation RParenLoc) {
  358. bool WasEvaluated = false;
  359. if (E && !E->isTypeDependent()) {
  360. if (E->getType()->isPlaceholderType()) {
  361. ExprResult result = CheckPlaceholderExpr(E);
  362. if (result.isInvalid()) return ExprError();
  363. E = result.get();
  364. }
  365. QualType T = E->getType();
  366. if (const RecordType *RecordT = T->getAs<RecordType>()) {
  367. CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
  368. // C++ [expr.typeid]p3:
  369. // [...] If the type of the expression is a class type, the class
  370. // shall be completely-defined.
  371. if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
  372. return ExprError();
  373. // C++ [expr.typeid]p3:
  374. // When typeid is applied to an expression other than an glvalue of a
  375. // polymorphic class type [...] [the] expression is an unevaluated
  376. // operand. [...]
  377. if (RecordD->isPolymorphic() && E->isGLValue()) {
  378. // The subexpression is potentially evaluated; switch the context
  379. // and recheck the subexpression.
  380. ExprResult Result = TransformToPotentiallyEvaluated(E);
  381. if (Result.isInvalid()) return ExprError();
  382. E = Result.get();
  383. // We require a vtable to query the type at run time.
  384. MarkVTableUsed(TypeidLoc, RecordD);
  385. WasEvaluated = true;
  386. }
  387. }
  388. // C++ [expr.typeid]p4:
  389. // [...] If the type of the type-id is a reference to a possibly
  390. // cv-qualified type, the result of the typeid expression refers to a
  391. // std::type_info object representing the cv-unqualified referenced
  392. // type.
  393. Qualifiers Quals;
  394. QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
  395. if (!Context.hasSameType(T, UnqualT)) {
  396. T = UnqualT;
  397. E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
  398. }
  399. }
  400. if (E->getType()->isVariablyModifiedType())
  401. return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
  402. << E->getType());
  403. else if (ActiveTemplateInstantiations.empty() &&
  404. E->HasSideEffects(Context, WasEvaluated)) {
  405. // The expression operand for typeid is in an unevaluated expression
  406. // context, so side effects could result in unintended consequences.
  407. Diag(E->getExprLoc(), WasEvaluated
  408. ? diag::warn_side_effects_typeid
  409. : diag::warn_side_effects_unevaluated_context);
  410. }
  411. return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
  412. SourceRange(TypeidLoc, RParenLoc));
  413. }
  414. /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
  415. ExprResult
  416. Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
  417. bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
  418. // Find the std::type_info type.
  419. if (!getStdNamespace())
  420. return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
  421. if (!CXXTypeInfoDecl) {
  422. IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
  423. LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
  424. LookupQualifiedName(R, getStdNamespace());
  425. CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
  426. // Microsoft's typeinfo doesn't have type_info in std but in the global
  427. // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
  428. if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
  429. LookupQualifiedName(R, Context.getTranslationUnitDecl());
  430. CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
  431. }
  432. if (!CXXTypeInfoDecl)
  433. return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
  434. }
  435. if (!getLangOpts().RTTI) {
  436. return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
  437. }
  438. QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
  439. if (isType) {
  440. // The operand is a type; handle it as such.
  441. TypeSourceInfo *TInfo = nullptr;
  442. QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
  443. &TInfo);
  444. if (T.isNull())
  445. return ExprError();
  446. if (!TInfo)
  447. TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
  448. return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
  449. }
  450. // The operand is an expression.
  451. return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
  452. }
  453. /// \brief Build a Microsoft __uuidof expression with a type operand.
  454. ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
  455. SourceLocation TypeidLoc,
  456. TypeSourceInfo *Operand,
  457. SourceLocation RParenLoc) {
  458. if (!Operand->getType()->isDependentType()) {
  459. bool HasMultipleGUIDs = false;
  460. if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
  461. &HasMultipleGUIDs)) {
  462. if (HasMultipleGUIDs)
  463. return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
  464. else
  465. return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
  466. }
  467. }
  468. return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand,
  469. SourceRange(TypeidLoc, RParenLoc));
  470. }
  471. /// \brief Build a Microsoft __uuidof expression with an expression operand.
  472. ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
  473. SourceLocation TypeidLoc,
  474. Expr *E,
  475. SourceLocation RParenLoc) {
  476. if (!E->getType()->isDependentType()) {
  477. bool HasMultipleGUIDs = false;
  478. if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
  479. !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  480. if (HasMultipleGUIDs)
  481. return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
  482. else
  483. return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
  484. }
  485. }
  486. return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E,
  487. SourceRange(TypeidLoc, RParenLoc));
  488. }
  489. /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
  490. ExprResult
  491. Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
  492. bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
  493. // If MSVCGuidDecl has not been cached, do the lookup.
  494. if (!MSVCGuidDecl) {
  495. IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
  496. LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
  497. LookupQualifiedName(R, Context.getTranslationUnitDecl());
  498. MSVCGuidDecl = R.getAsSingle<RecordDecl>();
  499. if (!MSVCGuidDecl)
  500. return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
  501. }
  502. QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
  503. if (isType) {
  504. // The operand is a type; handle it as such.
  505. TypeSourceInfo *TInfo = nullptr;
  506. QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
  507. &TInfo);
  508. if (T.isNull())
  509. return ExprError();
  510. if (!TInfo)
  511. TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
  512. return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
  513. }
  514. // The operand is an expression.
  515. return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
  516. }
  517. /// ActOnCXXBoolLiteral - Parse {true,false} literals.
  518. ExprResult
  519. Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  520. assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
  521. "Unknown C++ Boolean value!");
  522. return new (Context)
  523. CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
  524. }
  525. /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
  526. ExprResult
  527. Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
  528. return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
  529. }
  530. /// ActOnCXXThrow - Parse throw expressions.
  531. ExprResult
  532. Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
  533. bool IsThrownVarInScope = false;
  534. if (Ex) {
  535. // C++0x [class.copymove]p31:
  536. // When certain criteria are met, an implementation is allowed to omit the
  537. // copy/move construction of a class object [...]
  538. //
  539. // - in a throw-expression, when the operand is the name of a
  540. // non-volatile automatic object (other than a function or catch-
  541. // clause parameter) whose scope does not extend beyond the end of the
  542. // innermost enclosing try-block (if there is one), the copy/move
  543. // operation from the operand to the exception object (15.1) can be
  544. // omitted by constructing the automatic object directly into the
  545. // exception object
  546. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
  547. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  548. if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
  549. for( ; S; S = S->getParent()) {
  550. if (S->isDeclScope(Var)) {
  551. IsThrownVarInScope = true;
  552. break;
  553. }
  554. if (S->getFlags() &
  555. (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
  556. Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
  557. Scope::TryScope))
  558. break;
  559. }
  560. }
  561. }
  562. }
  563. return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
  564. }
  565. ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
  566. bool IsThrownVarInScope) {
  567. // Don't report an error if 'throw' is used in system headers.
  568. if (!getLangOpts().CXXExceptions &&
  569. !getSourceManager().isInSystemHeader(OpLoc))
  570. Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
  571. if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
  572. Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
  573. if (Ex && !Ex->isTypeDependent()) {
  574. QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
  575. if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
  576. return ExprError();
  577. // Initialize the exception result. This implicitly weeds out
  578. // abstract types or types with inaccessible copy constructors.
  579. // C++0x [class.copymove]p31:
  580. // When certain criteria are met, an implementation is allowed to omit the
  581. // copy/move construction of a class object [...]
  582. //
  583. // - in a throw-expression, when the operand is the name of a
  584. // non-volatile automatic object (other than a function or
  585. // catch-clause
  586. // parameter) whose scope does not extend beyond the end of the
  587. // innermost enclosing try-block (if there is one), the copy/move
  588. // operation from the operand to the exception object (15.1) can be
  589. // omitted by constructing the automatic object directly into the
  590. // exception object
  591. const VarDecl *NRVOVariable = nullptr;
  592. if (IsThrownVarInScope)
  593. NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
  594. InitializedEntity Entity = InitializedEntity::InitializeException(
  595. OpLoc, ExceptionObjectTy,
  596. /*NRVO=*/NRVOVariable != nullptr);
  597. ExprResult Res = PerformMoveOrCopyInitialization(
  598. Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
  599. if (Res.isInvalid())
  600. return ExprError();
  601. Ex = Res.get();
  602. }
  603. return new (Context)
  604. CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
  605. }
  606. static void
  607. collectPublicBases(CXXRecordDecl *RD,
  608. llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
  609. llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
  610. llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
  611. bool ParentIsPublic) {
  612. for (const CXXBaseSpecifier &BS : RD->bases()) {
  613. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  614. bool NewSubobject;
  615. // Virtual bases constitute the same subobject. Non-virtual bases are
  616. // always distinct subobjects.
  617. if (BS.isVirtual())
  618. NewSubobject = VBases.insert(BaseDecl).second;
  619. else
  620. NewSubobject = true;
  621. if (NewSubobject)
  622. ++SubobjectsSeen[BaseDecl];
  623. // Only add subobjects which have public access throughout the entire chain.
  624. bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
  625. if (PublicPath)
  626. PublicSubobjectsSeen.insert(BaseDecl);
  627. // Recurse on to each base subobject.
  628. collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
  629. PublicPath);
  630. }
  631. }
  632. static void getUnambiguousPublicSubobjects(
  633. CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
  634. llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
  635. llvm::SmallSet<CXXRecordDecl *, 2> VBases;
  636. llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
  637. SubobjectsSeen[RD] = 1;
  638. PublicSubobjectsSeen.insert(RD);
  639. collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
  640. /*ParentIsPublic=*/true);
  641. for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
  642. // Skip ambiguous objects.
  643. if (SubobjectsSeen[PublicSubobject] > 1)
  644. continue;
  645. Objects.push_back(PublicSubobject);
  646. }
  647. }
  648. /// CheckCXXThrowOperand - Validate the operand of a throw.
  649. bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
  650. QualType ExceptionObjectTy, Expr *E) {
  651. // If the type of the exception would be an incomplete type or a pointer
  652. // to an incomplete type other than (cv) void the program is ill-formed.
  653. QualType Ty = ExceptionObjectTy;
  654. bool isPointer = false;
  655. if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
  656. Ty = Ptr->getPointeeType();
  657. isPointer = true;
  658. }
  659. if (!isPointer || !Ty->isVoidType()) {
  660. if (RequireCompleteType(ThrowLoc, Ty,
  661. isPointer ? diag::err_throw_incomplete_ptr
  662. : diag::err_throw_incomplete,
  663. E->getSourceRange()))
  664. return true;
  665. if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
  666. diag::err_throw_abstract_type, E))
  667. return true;
  668. }
  669. // If the exception has class type, we need additional handling.
  670. CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  671. if (!RD)
  672. return false;
  673. // If we are throwing a polymorphic class type or pointer thereof,
  674. // exception handling will make use of the vtable.
  675. MarkVTableUsed(ThrowLoc, RD);
  676. // If a pointer is thrown, the referenced object will not be destroyed.
  677. if (isPointer)
  678. return false;
  679. // If the class has a destructor, we must be able to call it.
  680. if (!RD->hasIrrelevantDestructor()) {
  681. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  682. MarkFunctionReferenced(E->getExprLoc(), Destructor);
  683. CheckDestructorAccess(E->getExprLoc(), Destructor,
  684. PDiag(diag::err_access_dtor_exception) << Ty);
  685. if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
  686. return true;
  687. }
  688. }
  689. // The MSVC ABI creates a list of all types which can catch the exception
  690. // object. This list also references the appropriate copy constructor to call
  691. // if the object is caught by value and has a non-trivial copy constructor.
  692. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  693. // We are only interested in the public, unambiguous bases contained within
  694. // the exception object. Bases which are ambiguous or otherwise
  695. // inaccessible are not catchable types.
  696. llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
  697. getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
  698. for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
  699. // Attempt to lookup the copy constructor. Various pieces of machinery
  700. // will spring into action, like template instantiation, which means this
  701. // cannot be a simple walk of the class's decls. Instead, we must perform
  702. // lookup and overload resolution.
  703. CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
  704. if (!CD)
  705. continue;
  706. // Mark the constructor referenced as it is used by this throw expression.
  707. MarkFunctionReferenced(E->getExprLoc(), CD);
  708. // Skip this copy constructor if it is trivial, we don't need to record it
  709. // in the catchable type data.
  710. if (CD->isTrivial())
  711. continue;
  712. // The copy constructor is non-trivial, create a mapping from this class
  713. // type to this constructor.
  714. // N.B. The selection of copy constructor is not sensitive to this
  715. // particular throw-site. Lookup will be performed at the catch-site to
  716. // ensure that the copy constructor is, in fact, accessible (via
  717. // friendship or any other means).
  718. Context.addCopyConstructorForExceptionObject(Subobject, CD);
  719. // We don't keep the instantiated default argument expressions around so
  720. // we must rebuild them here.
  721. for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
  722. // Skip any default arguments that we've already instantiated.
  723. if (Context.getDefaultArgExprForConstructor(CD, I))
  724. continue;
  725. Expr *DefaultArg =
  726. BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get();
  727. Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
  728. }
  729. }
  730. }
  731. return false;
  732. }
  733. QualType Sema::getCurrentThisType() {
  734. DeclContext *DC = getFunctionLevelDeclContext();
  735. QualType ThisTy = CXXThisTypeOverride;
  736. if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
  737. if (method && method->isInstance())
  738. ThisTy = method->getThisType(Context);
  739. }
  740. if (ThisTy.isNull()) {
  741. if (isGenericLambdaCallOperatorSpecialization(CurContext) &&
  742. CurContext->getParent()->getParent()->isRecord()) {
  743. // This is a generic lambda call operator that is being instantiated
  744. // within a default initializer - so use the enclosing class as 'this'.
  745. // There is no enclosing member function to retrieve the 'this' pointer
  746. // from.
  747. QualType ClassTy = Context.getTypeDeclType(
  748. cast<CXXRecordDecl>(CurContext->getParent()->getParent()));
  749. // There are no cv-qualifiers for 'this' within default initializers,
  750. // per [expr.prim.general]p4.
  751. return Context.getPointerType(ClassTy);
  752. }
  753. }
  754. return ThisTy;
  755. }
  756. Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
  757. Decl *ContextDecl,
  758. unsigned CXXThisTypeQuals,
  759. bool Enabled)
  760. : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
  761. {
  762. if (!Enabled || !ContextDecl)
  763. return;
  764. CXXRecordDecl *Record = nullptr;
  765. if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
  766. Record = Template->getTemplatedDecl();
  767. else
  768. Record = cast<CXXRecordDecl>(ContextDecl);
  769. S.CXXThisTypeOverride
  770. = S.Context.getPointerType(
  771. S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
  772. this->Enabled = true;
  773. }
  774. Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
  775. if (Enabled) {
  776. S.CXXThisTypeOverride = OldCXXThisTypeOverride;
  777. }
  778. }
  779. static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
  780. QualType ThisTy, SourceLocation Loc) {
  781. FieldDecl *Field
  782. = FieldDecl::Create(Context, RD, Loc, Loc, nullptr, ThisTy,
  783. Context.getTrivialTypeSourceInfo(ThisTy, Loc),
  784. nullptr, false, ICIS_NoInit);
  785. Field->setImplicit(true);
  786. Field->setAccess(AS_private);
  787. RD->addDecl(Field);
  788. return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
  789. }
  790. bool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit,
  791. bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
  792. // We don't need to capture this in an unevaluated context.
  793. if (isUnevaluatedContext() && !Explicit)
  794. return true;
  795. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
  796. *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  797. // Otherwise, check that we can capture 'this'.
  798. unsigned NumClosures = 0;
  799. for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
  800. if (CapturingScopeInfo *CSI =
  801. dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
  802. if (CSI->CXXThisCaptureIndex != 0) {
  803. // 'this' is already being captured; there isn't anything more to do.
  804. break;
  805. }
  806. LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
  807. if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
  808. // This context can't implicitly capture 'this'; fail out.
  809. if (BuildAndDiagnose)
  810. Diag(Loc, diag::err_this_capture) << Explicit;
  811. return true;
  812. }
  813. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
  814. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
  815. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
  816. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
  817. Explicit) {
  818. // This closure can capture 'this'; continue looking upwards.
  819. NumClosures++;
  820. Explicit = false;
  821. continue;
  822. }
  823. // This context can't implicitly capture 'this'; fail out.
  824. if (BuildAndDiagnose)
  825. Diag(Loc, diag::err_this_capture) << Explicit;
  826. return true;
  827. }
  828. break;
  829. }
  830. if (!BuildAndDiagnose) return false;
  831. // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
  832. // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
  833. // contexts.
  834. for (unsigned idx = MaxFunctionScopesIndex; NumClosures;
  835. --idx, --NumClosures) {
  836. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
  837. Expr *ThisExpr = nullptr;
  838. QualType ThisTy = getCurrentThisType();
  839. if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  840. // For lambda expressions, build a field and an initializing expression.
  841. ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
  842. else if (CapturedRegionScopeInfo *RSI
  843. = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
  844. ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
  845. bool isNested = NumClosures > 1;
  846. CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
  847. }
  848. return false;
  849. }
  850. ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
  851. /// C++ 9.3.2: In the body of a non-static member function, the keyword this
  852. /// is a non-lvalue expression whose value is the address of the object for
  853. /// which the function is called.
  854. QualType ThisTy = getCurrentThisType();
  855. if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
  856. CheckCXXThisCapture(Loc);
  857. // HLSL Change Starts - adjust this from T* to T&-like
  858. if (getLangOpts().HLSL && ThisTy.getTypePtr()->isPointerType()) {
  859. // Expressions cannot be of reference type - instead, they yield
  860. // an lvalue on the underlying type.
  861. CXXThisExpr* ResultExpr = new (Context)CXXThisExpr(
  862. Loc, ThisTy.getTypePtr()->getPointeeType(), /*isImplicit=*/false);
  863. ResultExpr->setValueKind(ExprValueKind::VK_LValue);
  864. return ResultExpr;
  865. }
  866. // HLSL Change Ends
  867. return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
  868. }
  869. bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
  870. // If we're outside the body of a member function, then we'll have a specified
  871. // type for 'this'.
  872. if (CXXThisTypeOverride.isNull())
  873. return false;
  874. // Determine whether we're looking into a class that's currently being
  875. // defined.
  876. CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
  877. return Class && Class->isBeingDefined();
  878. }
  879. ExprResult
  880. Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
  881. SourceLocation LParenLoc,
  882. MultiExprArg exprs,
  883. SourceLocation RParenLoc) {
  884. if (!TypeRep)
  885. return ExprError();
  886. TypeSourceInfo *TInfo;
  887. QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
  888. if (!TInfo)
  889. TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
  890. // HLSL Change Begin - Check embedded typos for CXXUnresolvedConstructExpr.
  891. ExprResult Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
  892. if (!Result.isInvalid() && isa<CXXUnresolvedConstructExpr>(Result.get()))
  893. Result = CorrectDelayedTyposInExpr(Result.get());
  894. return Result;
  895. // HLSL Change End.
  896. }
  897. /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
  898. /// Can be interpreted either as function-style casting ("int(x)")
  899. /// or class type construction ("ClassType(x,y,z)")
  900. /// or creation of a value-initialized type ("int()").
  901. ExprResult
  902. Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
  903. SourceLocation LParenLoc,
  904. MultiExprArg Exprs,
  905. SourceLocation RParenLoc) {
  906. QualType Ty = TInfo->getType();
  907. SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
  908. if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
  909. return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
  910. RParenLoc);
  911. }
  912. bool ListInitialization = LParenLoc.isInvalid();
  913. assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
  914. && "List initialization must have initializer list as expression.");
  915. SourceRange FullRange = SourceRange(TyBeginLoc,
  916. ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
  917. // C++ [expr.type.conv]p1:
  918. // If the expression list is a single expression, the type conversion
  919. // expression is equivalent (in definedness, and if defined in meaning) to the
  920. // corresponding cast expression.
  921. if (Exprs.size() == 1 && !ListInitialization) {
  922. Expr *Arg = Exprs[0];
  923. return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
  924. }
  925. QualType ElemTy = Ty;
  926. if (Ty->isArrayType()) {
  927. if (!ListInitialization)
  928. return ExprError(Diag(TyBeginLoc,
  929. diag::err_value_init_for_array_type) << FullRange);
  930. ElemTy = Context.getBaseElementType(Ty);
  931. }
  932. if (!Ty->isVoidType() &&
  933. RequireCompleteType(TyBeginLoc, ElemTy,
  934. diag::err_invalid_incomplete_type_use, FullRange))
  935. return ExprError();
  936. if (RequireNonAbstractType(TyBeginLoc, Ty,
  937. diag::err_allocation_of_abstract_type))
  938. return ExprError();
  939. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
  940. InitializationKind Kind =
  941. Exprs.size() ? ListInitialization
  942. ? InitializationKind::CreateDirectList(TyBeginLoc)
  943. : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
  944. : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
  945. InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
  946. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
  947. // HLSL Change: ListInitialization may be false here, but we may produce an expression
  948. // of that type for vector constructors
  949. bool HLSLException = getLangOpts().HLSL && !Result.isInvalid() && isa<InitListExpr>(Result.get());
  950. if (Result.isInvalid() || (!ListInitialization && !HLSLException))
  951. return Result;
  952. Expr *Inner = Result.get();
  953. if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
  954. Inner = BTE->getSubExpr();
  955. if (!isa<CXXTemporaryObjectExpr>(Inner)) {
  956. // If we created a CXXTemporaryObjectExpr, that node also represents the
  957. // functional cast. Otherwise, create an explicit cast to represent
  958. // the syntactic form of a functional-style cast that was used here.
  959. //
  960. // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
  961. // would give a more consistent AST representation than using a
  962. // CXXTemporaryObjectExpr. It's also weird that the functional cast
  963. // is sometimes handled by initialization and sometimes not.
  964. QualType ResultType = Result.get()->getType();
  965. Result = CXXFunctionalCastExpr::Create(
  966. Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
  967. CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
  968. }
  969. return Result;
  970. }
  971. /// doesUsualArrayDeleteWantSize - Answers whether the usual
  972. /// operator delete[] for the given type has a size_t parameter.
  973. static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
  974. QualType allocType) {
  975. const RecordType *record =
  976. allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
  977. if (!record) return false;
  978. // Try to find an operator delete[] in class scope.
  979. DeclarationName deleteName =
  980. S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
  981. LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
  982. S.LookupQualifiedName(ops, record->getDecl());
  983. // We're just doing this for information.
  984. ops.suppressDiagnostics();
  985. // Very likely: there's no operator delete[].
  986. if (ops.empty()) return false;
  987. // If it's ambiguous, it should be illegal to call operator delete[]
  988. // on this thing, so it doesn't matter if we allocate extra space or not.
  989. if (ops.isAmbiguous()) return false;
  990. LookupResult::Filter filter = ops.makeFilter();
  991. while (filter.hasNext()) {
  992. NamedDecl *del = filter.next()->getUnderlyingDecl();
  993. // C++0x [basic.stc.dynamic.deallocation]p2:
  994. // A template instance is never a usual deallocation function,
  995. // regardless of its signature.
  996. if (isa<FunctionTemplateDecl>(del)) {
  997. filter.erase();
  998. continue;
  999. }
  1000. // C++0x [basic.stc.dynamic.deallocation]p2:
  1001. // If class T does not declare [an operator delete[] with one
  1002. // parameter] but does declare a member deallocation function
  1003. // named operator delete[] with exactly two parameters, the
  1004. // second of which has type std::size_t, then this function
  1005. // is a usual deallocation function.
  1006. if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
  1007. filter.erase();
  1008. continue;
  1009. }
  1010. }
  1011. filter.done();
  1012. if (!ops.isSingleResult()) return false;
  1013. const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
  1014. return (del->getNumParams() == 2);
  1015. }
  1016. /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
  1017. ///
  1018. /// E.g.:
  1019. /// @code new (memory) int[size][4] @endcode
  1020. /// or
  1021. /// @code ::new Foo(23, "hello") @endcode
  1022. ///
  1023. /// \param StartLoc The first location of the expression.
  1024. /// \param UseGlobal True if 'new' was prefixed with '::'.
  1025. /// \param PlacementLParen Opening paren of the placement arguments.
  1026. /// \param PlacementArgs Placement new arguments.
  1027. /// \param PlacementRParen Closing paren of the placement arguments.
  1028. /// \param TypeIdParens If the type is in parens, the source range.
  1029. /// \param D The type to be allocated, as well as array dimensions.
  1030. /// \param Initializer The initializing expression or initializer-list, or null
  1031. /// if there is none.
  1032. ExprResult
  1033. Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
  1034. SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
  1035. SourceLocation PlacementRParen, SourceRange TypeIdParens,
  1036. Declarator &D, Expr *Initializer) {
  1037. bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
  1038. Expr *ArraySize = nullptr;
  1039. // If the specified type is an array, unwrap it and save the expression.
  1040. if (D.getNumTypeObjects() > 0 &&
  1041. D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
  1042. DeclaratorChunk &Chunk = D.getTypeObject(0);
  1043. if (TypeContainsAuto)
  1044. return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
  1045. << D.getSourceRange());
  1046. if (Chunk.Arr.hasStatic)
  1047. return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
  1048. << D.getSourceRange());
  1049. if (!Chunk.Arr.NumElts)
  1050. return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
  1051. << D.getSourceRange());
  1052. ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
  1053. D.DropFirstTypeObject();
  1054. }
  1055. // Every dimension shall be of constant size.
  1056. if (ArraySize) {
  1057. for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
  1058. if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
  1059. break;
  1060. DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
  1061. if (Expr *NumElts = (Expr *)Array.NumElts) {
  1062. if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
  1063. if (getLangOpts().CPlusPlus14) {
  1064. // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
  1065. // shall be a converted constant expression (5.19) of type std::size_t
  1066. // and shall evaluate to a strictly positive value.
  1067. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  1068. assert(IntWidth && "Builtin type of size 0?");
  1069. llvm::APSInt Value(IntWidth);
  1070. Array.NumElts
  1071. = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
  1072. CCEK_NewExpr)
  1073. .get();
  1074. } else {
  1075. Array.NumElts
  1076. = VerifyIntegerConstantExpression(NumElts, nullptr,
  1077. diag::err_new_array_nonconst)
  1078. .get();
  1079. }
  1080. if (!Array.NumElts)
  1081. return ExprError();
  1082. }
  1083. }
  1084. }
  1085. }
  1086. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
  1087. QualType AllocType = TInfo->getType();
  1088. if (D.isInvalidType())
  1089. return ExprError();
  1090. SourceRange DirectInitRange;
  1091. if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
  1092. DirectInitRange = List->getSourceRange();
  1093. return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
  1094. PlacementLParen,
  1095. PlacementArgs,
  1096. PlacementRParen,
  1097. TypeIdParens,
  1098. AllocType,
  1099. TInfo,
  1100. ArraySize,
  1101. DirectInitRange,
  1102. Initializer,
  1103. TypeContainsAuto);
  1104. }
  1105. static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
  1106. Expr *Init) {
  1107. if (!Init)
  1108. return true;
  1109. if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
  1110. return PLE->getNumExprs() == 0;
  1111. if (isa<ImplicitValueInitExpr>(Init))
  1112. return true;
  1113. else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
  1114. return !CCE->isListInitialization() &&
  1115. CCE->getConstructor()->isDefaultConstructor();
  1116. else if (Style == CXXNewExpr::ListInit) {
  1117. assert(isa<InitListExpr>(Init) &&
  1118. "Shouldn't create list CXXConstructExprs for arrays.");
  1119. return true;
  1120. }
  1121. return false;
  1122. }
  1123. ExprResult
  1124. Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
  1125. SourceLocation PlacementLParen,
  1126. MultiExprArg PlacementArgs,
  1127. SourceLocation PlacementRParen,
  1128. SourceRange TypeIdParens,
  1129. QualType AllocType,
  1130. TypeSourceInfo *AllocTypeInfo,
  1131. Expr *ArraySize,
  1132. SourceRange DirectInitRange,
  1133. Expr *Initializer,
  1134. bool TypeMayContainAuto) {
  1135. SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
  1136. SourceLocation StartLoc = Range.getBegin();
  1137. CXXNewExpr::InitializationStyle initStyle;
  1138. if (DirectInitRange.isValid()) {
  1139. assert(Initializer && "Have parens but no initializer.");
  1140. initStyle = CXXNewExpr::CallInit;
  1141. } else if (Initializer && isa<InitListExpr>(Initializer))
  1142. initStyle = CXXNewExpr::ListInit;
  1143. else {
  1144. assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
  1145. isa<CXXConstructExpr>(Initializer)) &&
  1146. "Initializer expression that cannot have been implicitly created.");
  1147. initStyle = CXXNewExpr::NoInit;
  1148. }
  1149. Expr **Inits = &Initializer;
  1150. unsigned NumInits = Initializer ? 1 : 0;
  1151. if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
  1152. assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
  1153. Inits = List->getExprs();
  1154. NumInits = List->getNumExprs();
  1155. }
  1156. // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  1157. if (TypeMayContainAuto && AllocType->isUndeducedType()) {
  1158. if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
  1159. return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
  1160. << AllocType << TypeRange);
  1161. if (initStyle == CXXNewExpr::ListInit ||
  1162. (NumInits == 1 && isa<InitListExpr>(Inits[0])))
  1163. return ExprError(Diag(Inits[0]->getLocStart(),
  1164. diag::err_auto_new_list_init)
  1165. << AllocType << TypeRange);
  1166. if (NumInits > 1) {
  1167. Expr *FirstBad = Inits[1];
  1168. return ExprError(Diag(FirstBad->getLocStart(),
  1169. diag::err_auto_new_ctor_multiple_expressions)
  1170. << AllocType << TypeRange);
  1171. }
  1172. Expr *Deduce = Inits[0];
  1173. QualType DeducedType;
  1174. if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
  1175. return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
  1176. << AllocType << Deduce->getType()
  1177. << TypeRange << Deduce->getSourceRange());
  1178. if (DeducedType.isNull())
  1179. return ExprError();
  1180. AllocType = DeducedType;
  1181. }
  1182. // Per C++0x [expr.new]p5, the type being constructed may be a
  1183. // typedef of an array type.
  1184. if (!ArraySize) {
  1185. if (const ConstantArrayType *Array
  1186. = Context.getAsConstantArrayType(AllocType)) {
  1187. ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
  1188. Context.getSizeType(),
  1189. TypeRange.getEnd());
  1190. AllocType = Array->getElementType();
  1191. }
  1192. }
  1193. if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
  1194. return ExprError();
  1195. if (initStyle == CXXNewExpr::ListInit &&
  1196. isStdInitializerList(AllocType, nullptr)) {
  1197. Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
  1198. diag::warn_dangling_std_initializer_list)
  1199. << /*at end of FE*/0 << Inits[0]->getSourceRange();
  1200. }
  1201. // In ARC, infer 'retaining' for the allocated
  1202. if (getLangOpts().ObjCAutoRefCount &&
  1203. AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
  1204. AllocType->isObjCLifetimeType()) {
  1205. AllocType = Context.getLifetimeQualifiedType(AllocType,
  1206. AllocType->getObjCARCImplicitLifetime());
  1207. }
  1208. QualType ResultType = Context.getPointerType(AllocType);
  1209. if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
  1210. ExprResult result = CheckPlaceholderExpr(ArraySize);
  1211. if (result.isInvalid()) return ExprError();
  1212. ArraySize = result.get();
  1213. }
  1214. // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
  1215. // integral or enumeration type with a non-negative value."
  1216. // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
  1217. // enumeration type, or a class type for which a single non-explicit
  1218. // conversion function to integral or unscoped enumeration type exists.
  1219. // C++1y [expr.new]p6: The expression [...] is implicitly converted to
  1220. // std::size_t.
  1221. if (ArraySize && !ArraySize->isTypeDependent()) {
  1222. ExprResult ConvertedSize;
  1223. if (getLangOpts().CPlusPlus14) {
  1224. assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
  1225. ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
  1226. AA_Converting);
  1227. if (!ConvertedSize.isInvalid() &&
  1228. ArraySize->getType()->getAs<RecordType>())
  1229. // Diagnose the compatibility of this conversion.
  1230. Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
  1231. << ArraySize->getType() << 0 << "'size_t'";
  1232. } else {
  1233. class SizeConvertDiagnoser : public ICEConvertDiagnoser {
  1234. protected:
  1235. Expr *ArraySize;
  1236. public:
  1237. SizeConvertDiagnoser(Expr *ArraySize)
  1238. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
  1239. ArraySize(ArraySize) {}
  1240. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  1241. QualType T) override {
  1242. return S.Diag(Loc, diag::err_array_size_not_integral)
  1243. << S.getLangOpts().CPlusPlus11 << T;
  1244. }
  1245. SemaDiagnosticBuilder diagnoseIncomplete(
  1246. Sema &S, SourceLocation Loc, QualType T) override {
  1247. return S.Diag(Loc, diag::err_array_size_incomplete_type)
  1248. << T << ArraySize->getSourceRange();
  1249. }
  1250. SemaDiagnosticBuilder diagnoseExplicitConv(
  1251. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  1252. return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
  1253. }
  1254. SemaDiagnosticBuilder noteExplicitConv(
  1255. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  1256. return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
  1257. << ConvTy->isEnumeralType() << ConvTy;
  1258. }
  1259. SemaDiagnosticBuilder diagnoseAmbiguous(
  1260. Sema &S, SourceLocation Loc, QualType T) override {
  1261. return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
  1262. }
  1263. SemaDiagnosticBuilder noteAmbiguous(
  1264. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  1265. return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
  1266. << ConvTy->isEnumeralType() << ConvTy;
  1267. }
  1268. SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
  1269. QualType T,
  1270. QualType ConvTy) override {
  1271. return S.Diag(Loc,
  1272. S.getLangOpts().CPlusPlus11
  1273. ? diag::warn_cxx98_compat_array_size_conversion
  1274. : diag::ext_array_size_conversion)
  1275. << T << ConvTy->isEnumeralType() << ConvTy;
  1276. }
  1277. } SizeDiagnoser(ArraySize);
  1278. ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
  1279. SizeDiagnoser);
  1280. }
  1281. if (ConvertedSize.isInvalid())
  1282. return ExprError();
  1283. ArraySize = ConvertedSize.get();
  1284. QualType SizeType = ArraySize->getType();
  1285. if (!SizeType->isIntegralOrUnscopedEnumerationType())
  1286. return ExprError();
  1287. // C++98 [expr.new]p7:
  1288. // The expression in a direct-new-declarator shall have integral type
  1289. // with a non-negative value.
  1290. //
  1291. // Let's see if this is a constant < 0. If so, we reject it out of
  1292. // hand. Otherwise, if it's not a constant, we must have an unparenthesized
  1293. // array type.
  1294. //
  1295. // Note: such a construct has well-defined semantics in C++11: it throws
  1296. // std::bad_array_new_length.
  1297. if (!ArraySize->isValueDependent()) {
  1298. llvm::APSInt Value;
  1299. // We've already performed any required implicit conversion to integer or
  1300. // unscoped enumeration type.
  1301. if (ArraySize->isIntegerConstantExpr(Value, Context)) {
  1302. if (Value < llvm::APSInt(
  1303. llvm::APInt::getNullValue(Value.getBitWidth()),
  1304. Value.isUnsigned())) {
  1305. if (getLangOpts().CPlusPlus11)
  1306. Diag(ArraySize->getLocStart(),
  1307. diag::warn_typecheck_negative_array_new_size)
  1308. << ArraySize->getSourceRange();
  1309. else
  1310. return ExprError(Diag(ArraySize->getLocStart(),
  1311. diag::err_typecheck_negative_array_size)
  1312. << ArraySize->getSourceRange());
  1313. } else if (!AllocType->isDependentType()) {
  1314. unsigned ActiveSizeBits =
  1315. ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
  1316. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  1317. if (getLangOpts().CPlusPlus11)
  1318. Diag(ArraySize->getLocStart(),
  1319. diag::warn_array_new_too_large)
  1320. << Value.toString(10)
  1321. << ArraySize->getSourceRange();
  1322. else
  1323. return ExprError(Diag(ArraySize->getLocStart(),
  1324. diag::err_array_too_large)
  1325. << Value.toString(10)
  1326. << ArraySize->getSourceRange());
  1327. }
  1328. }
  1329. } else if (TypeIdParens.isValid()) {
  1330. // Can't have dynamic array size when the type-id is in parentheses.
  1331. Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
  1332. << ArraySize->getSourceRange()
  1333. << FixItHint::CreateRemoval(TypeIdParens.getBegin())
  1334. << FixItHint::CreateRemoval(TypeIdParens.getEnd());
  1335. TypeIdParens = SourceRange();
  1336. }
  1337. }
  1338. // Note that we do *not* convert the argument in any way. It can
  1339. // be signed, larger than size_t, whatever.
  1340. }
  1341. FunctionDecl *OperatorNew = nullptr;
  1342. FunctionDecl *OperatorDelete = nullptr;
  1343. if (!AllocType->isDependentType() &&
  1344. !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
  1345. FindAllocationFunctions(StartLoc,
  1346. SourceRange(PlacementLParen, PlacementRParen),
  1347. UseGlobal, AllocType, ArraySize, PlacementArgs,
  1348. OperatorNew, OperatorDelete))
  1349. return ExprError();
  1350. // If this is an array allocation, compute whether the usual array
  1351. // deallocation function for the type has a size_t parameter.
  1352. bool UsualArrayDeleteWantsSize = false;
  1353. if (ArraySize && !AllocType->isDependentType())
  1354. UsualArrayDeleteWantsSize
  1355. = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
  1356. SmallVector<Expr *, 8> AllPlaceArgs;
  1357. if (OperatorNew) {
  1358. const FunctionProtoType *Proto =
  1359. OperatorNew->getType()->getAs<FunctionProtoType>();
  1360. VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
  1361. : VariadicDoesNotApply;
  1362. // We've already converted the placement args, just fill in any default
  1363. // arguments. Skip the first parameter because we don't have a corresponding
  1364. // argument.
  1365. if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
  1366. PlacementArgs, AllPlaceArgs, CallType))
  1367. return ExprError();
  1368. if (!AllPlaceArgs.empty())
  1369. PlacementArgs = AllPlaceArgs;
  1370. // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
  1371. DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
  1372. // FIXME: Missing call to CheckFunctionCall or equivalent
  1373. }
  1374. // Warn if the type is over-aligned and is being allocated by global operator
  1375. // new.
  1376. if (PlacementArgs.empty() && OperatorNew &&
  1377. (OperatorNew->isImplicit() ||
  1378. getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
  1379. if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
  1380. unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
  1381. if (Align > SuitableAlign)
  1382. Diag(StartLoc, diag::warn_overaligned_type)
  1383. << AllocType
  1384. << unsigned(Align / Context.getCharWidth())
  1385. << unsigned(SuitableAlign / Context.getCharWidth());
  1386. }
  1387. }
  1388. QualType InitType = AllocType;
  1389. // Array 'new' can't have any initializers except empty parentheses.
  1390. // Initializer lists are also allowed, in C++11. Rely on the parser for the
  1391. // dialect distinction.
  1392. if (ResultType->isArrayType() || ArraySize) {
  1393. if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
  1394. SourceRange InitRange(Inits[0]->getLocStart(),
  1395. Inits[NumInits - 1]->getLocEnd());
  1396. Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
  1397. return ExprError();
  1398. }
  1399. if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
  1400. // We do the initialization typechecking against the array type
  1401. // corresponding to the number of initializers + 1 (to also check
  1402. // default-initialization).
  1403. unsigned NumElements = ILE->getNumInits() + 1;
  1404. InitType = Context.getConstantArrayType(AllocType,
  1405. llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
  1406. ArrayType::Normal, 0);
  1407. }
  1408. }
  1409. // If we can perform the initialization, and we've not already done so,
  1410. // do it now.
  1411. if (!AllocType->isDependentType() &&
  1412. !Expr::hasAnyTypeDependentArguments(
  1413. llvm::makeArrayRef(Inits, NumInits))) {
  1414. // C++11 [expr.new]p15:
  1415. // A new-expression that creates an object of type T initializes that
  1416. // object as follows:
  1417. InitializationKind Kind
  1418. // - If the new-initializer is omitted, the object is default-
  1419. // initialized (8.5); if no initialization is performed,
  1420. // the object has indeterminate value
  1421. = initStyle == CXXNewExpr::NoInit
  1422. ? InitializationKind::CreateDefault(TypeRange.getBegin())
  1423. // - Otherwise, the new-initializer is interpreted according to the
  1424. // initialization rules of 8.5 for direct-initialization.
  1425. : initStyle == CXXNewExpr::ListInit
  1426. ? InitializationKind::CreateDirectList(TypeRange.getBegin())
  1427. : InitializationKind::CreateDirect(TypeRange.getBegin(),
  1428. DirectInitRange.getBegin(),
  1429. DirectInitRange.getEnd());
  1430. InitializedEntity Entity
  1431. = InitializedEntity::InitializeNew(StartLoc, InitType);
  1432. InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
  1433. ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
  1434. MultiExprArg(Inits, NumInits));
  1435. if (FullInit.isInvalid())
  1436. return ExprError();
  1437. // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
  1438. // we don't want the initialized object to be destructed.
  1439. if (CXXBindTemporaryExpr *Binder =
  1440. dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
  1441. FullInit = Binder->getSubExpr();
  1442. Initializer = FullInit.get();
  1443. }
  1444. // Mark the new and delete operators as referenced.
  1445. if (OperatorNew) {
  1446. if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
  1447. return ExprError();
  1448. MarkFunctionReferenced(StartLoc, OperatorNew);
  1449. }
  1450. if (OperatorDelete) {
  1451. if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
  1452. return ExprError();
  1453. MarkFunctionReferenced(StartLoc, OperatorDelete);
  1454. }
  1455. // C++0x [expr.new]p17:
  1456. // If the new expression creates an array of objects of class type,
  1457. // access and ambiguity control are done for the destructor.
  1458. QualType BaseAllocType = Context.getBaseElementType(AllocType);
  1459. if (ArraySize && !BaseAllocType->isDependentType()) {
  1460. if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
  1461. if (CXXDestructorDecl *dtor = LookupDestructor(
  1462. cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
  1463. MarkFunctionReferenced(StartLoc, dtor);
  1464. CheckDestructorAccess(StartLoc, dtor,
  1465. PDiag(diag::err_access_dtor)
  1466. << BaseAllocType);
  1467. if (DiagnoseUseOfDecl(dtor, StartLoc))
  1468. return ExprError();
  1469. }
  1470. }
  1471. }
  1472. return new (Context)
  1473. CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
  1474. UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
  1475. ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
  1476. Range, DirectInitRange);
  1477. }
  1478. /// \brief Checks that a type is suitable as the allocated type
  1479. /// in a new-expression.
  1480. bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
  1481. SourceRange R) {
  1482. // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
  1483. // abstract class type or array thereof.
  1484. if (AllocType->isFunctionType())
  1485. return Diag(Loc, diag::err_bad_new_type)
  1486. << AllocType << 0 << R;
  1487. else if (AllocType->isReferenceType())
  1488. return Diag(Loc, diag::err_bad_new_type)
  1489. << AllocType << 1 << R;
  1490. else if (!AllocType->isDependentType() &&
  1491. RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
  1492. return true;
  1493. else if (RequireNonAbstractType(Loc, AllocType,
  1494. diag::err_allocation_of_abstract_type))
  1495. return true;
  1496. else if (AllocType->isVariablyModifiedType())
  1497. return Diag(Loc, diag::err_variably_modified_new_type)
  1498. << AllocType;
  1499. else if (unsigned AddressSpace = AllocType.getAddressSpace())
  1500. return Diag(Loc, diag::err_address_space_qualified_new)
  1501. << AllocType.getUnqualifiedType() << AddressSpace;
  1502. else if (getLangOpts().ObjCAutoRefCount) {
  1503. if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
  1504. QualType BaseAllocType = Context.getBaseElementType(AT);
  1505. if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
  1506. BaseAllocType->isObjCLifetimeType())
  1507. return Diag(Loc, diag::err_arc_new_array_without_ownership)
  1508. << BaseAllocType;
  1509. }
  1510. }
  1511. return false;
  1512. }
  1513. /// \brief Determine whether the given function is a non-placement
  1514. /// deallocation function.
  1515. static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
  1516. if (FD->isInvalidDecl())
  1517. return false;
  1518. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
  1519. return Method->isUsualDeallocationFunction();
  1520. if (FD->getOverloadedOperator() != OO_Delete &&
  1521. FD->getOverloadedOperator() != OO_Array_Delete)
  1522. return false;
  1523. if (FD->getNumParams() == 1)
  1524. return true;
  1525. return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
  1526. S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
  1527. S.Context.getSizeType());
  1528. }
  1529. /// FindAllocationFunctions - Finds the overloads of operator new and delete
  1530. /// that are appropriate for the allocation.
  1531. bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
  1532. bool UseGlobal, QualType AllocType,
  1533. bool IsArray, MultiExprArg PlaceArgs,
  1534. FunctionDecl *&OperatorNew,
  1535. FunctionDecl *&OperatorDelete) {
  1536. // HLSL Change Starts Here
  1537. // No support for new and delete operators.
  1538. return false;
  1539. #if 0
  1540. // HLSL Change Ends Here
  1541. // --- Choosing an allocation function ---
  1542. // C++ 5.3.4p8 - 14 & 18
  1543. // 1) If UseGlobal is true, only look in the global scope. Else, also look
  1544. // in the scope of the allocated class.
  1545. // 2) If an array size is given, look for operator new[], else look for
  1546. // operator new.
  1547. // 3) The first argument is always size_t. Append the arguments from the
  1548. // placement form.
  1549. SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
  1550. // We don't care about the actual value of this argument.
  1551. // FIXME: Should the Sema create the expression and embed it in the syntax
  1552. // tree? Or should the consumer just recalculate the value?
  1553. IntegerLiteral Size(Context, llvm::APInt::getNullValue(
  1554. Context.getTargetInfo().getPointerWidth(0)),
  1555. Context.getSizeType(),
  1556. SourceLocation());
  1557. AllocArgs[0] = &Size;
  1558. std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
  1559. // C++ [expr.new]p8:
  1560. // If the allocated type is a non-array type, the allocation
  1561. // function's name is operator new and the deallocation function's
  1562. // name is operator delete. If the allocated type is an array
  1563. // type, the allocation function's name is operator new[] and the
  1564. // deallocation function's name is operator delete[].
  1565. DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
  1566. IsArray ? OO_Array_New : OO_New);
  1567. DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
  1568. IsArray ? OO_Array_Delete : OO_Delete);
  1569. QualType AllocElemType = Context.getBaseElementType(AllocType);
  1570. if (AllocElemType->isRecordType() && !UseGlobal) {
  1571. CXXRecordDecl *Record
  1572. = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
  1573. if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
  1574. /*AllowMissing=*/true, OperatorNew))
  1575. return true;
  1576. }
  1577. if (!OperatorNew) {
  1578. // Didn't find a member overload. Look for a global one.
  1579. DeclareGlobalNewDelete();
  1580. DeclContext *TUDecl = Context.getTranslationUnitDecl();
  1581. bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
  1582. if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
  1583. /*AllowMissing=*/FallbackEnabled, OperatorNew,
  1584. /*Diagnose=*/!FallbackEnabled)) {
  1585. if (!FallbackEnabled)
  1586. return true;
  1587. // MSVC will fall back on trying to find a matching global operator new
  1588. // if operator new[] cannot be found. Also, MSVC will leak by not
  1589. // generating a call to operator delete or operator delete[], but we
  1590. // will not replicate that bug.
  1591. NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
  1592. DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  1593. if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
  1594. /*AllowMissing=*/false, OperatorNew))
  1595. return true;
  1596. }
  1597. }
  1598. // We don't need an operator delete if we're running under
  1599. // -fno-exceptions.
  1600. if (!getLangOpts().Exceptions) {
  1601. OperatorDelete = nullptr;
  1602. return false;
  1603. }
  1604. // C++ [expr.new]p19:
  1605. //
  1606. // If the new-expression begins with a unary :: operator, the
  1607. // deallocation function's name is looked up in the global
  1608. // scope. Otherwise, if the allocated type is a class type T or an
  1609. // array thereof, the deallocation function's name is looked up in
  1610. // the scope of T. If this lookup fails to find the name, or if
  1611. // the allocated type is not a class type or array thereof, the
  1612. // deallocation function's name is looked up in the global scope.
  1613. LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
  1614. if (AllocElemType->isRecordType() && !UseGlobal) {
  1615. CXXRecordDecl *RD
  1616. = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
  1617. LookupQualifiedName(FoundDelete, RD);
  1618. }
  1619. if (FoundDelete.isAmbiguous())
  1620. return true; // FIXME: clean up expressions?
  1621. if (FoundDelete.empty()) {
  1622. DeclareGlobalNewDelete();
  1623. LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
  1624. }
  1625. FoundDelete.suppressDiagnostics();
  1626. SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
  1627. // Whether we're looking for a placement operator delete is dictated
  1628. // by whether we selected a placement operator new, not by whether
  1629. // we had explicit placement arguments. This matters for things like
  1630. // struct A { void *operator new(size_t, int = 0); ... };
  1631. // A *a = new A()
  1632. bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
  1633. if (isPlacementNew) {
  1634. // C++ [expr.new]p20:
  1635. // A declaration of a placement deallocation function matches the
  1636. // declaration of a placement allocation function if it has the
  1637. // same number of parameters and, after parameter transformations
  1638. // (8.3.5), all parameter types except the first are
  1639. // identical. [...]
  1640. //
  1641. // To perform this comparison, we compute the function type that
  1642. // the deallocation function should have, and use that type both
  1643. // for template argument deduction and for comparison purposes.
  1644. //
  1645. // FIXME: this comparison should ignore CC and the like.
  1646. QualType ExpectedFunctionType;
  1647. {
  1648. const FunctionProtoType *Proto
  1649. = OperatorNew->getType()->getAs<FunctionProtoType>();
  1650. SmallVector<QualType, 4> ArgTypes;
  1651. ArgTypes.push_back(Context.VoidPtrTy);
  1652. for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
  1653. ArgTypes.push_back(Proto->getParamType(I));
  1654. FunctionProtoType::ExtProtoInfo EPI;
  1655. EPI.Variadic = Proto->isVariadic();
  1656. ExpectedFunctionType
  1657. = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
  1658. }
  1659. for (LookupResult::iterator D = FoundDelete.begin(),
  1660. DEnd = FoundDelete.end();
  1661. D != DEnd; ++D) {
  1662. FunctionDecl *Fn = nullptr;
  1663. if (FunctionTemplateDecl *FnTmpl
  1664. = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
  1665. // Perform template argument deduction to try to match the
  1666. // expected function type.
  1667. TemplateDeductionInfo Info(StartLoc);
  1668. if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
  1669. Info))
  1670. continue;
  1671. } else
  1672. Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
  1673. if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
  1674. Matches.push_back(std::make_pair(D.getPair(), Fn));
  1675. }
  1676. } else {
  1677. // C++ [expr.new]p20:
  1678. // [...] Any non-placement deallocation function matches a
  1679. // non-placement allocation function. [...]
  1680. for (LookupResult::iterator D = FoundDelete.begin(),
  1681. DEnd = FoundDelete.end();
  1682. D != DEnd; ++D) {
  1683. if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
  1684. if (isNonPlacementDeallocationFunction(*this, Fn))
  1685. Matches.push_back(std::make_pair(D.getPair(), Fn));
  1686. }
  1687. // C++1y [expr.new]p22:
  1688. // For a non-placement allocation function, the normal deallocation
  1689. // function lookup is used
  1690. // C++1y [expr.delete]p?:
  1691. // If [...] deallocation function lookup finds both a usual deallocation
  1692. // function with only a pointer parameter and a usual deallocation
  1693. // function with both a pointer parameter and a size parameter, then the
  1694. // selected deallocation function shall be the one with two parameters.
  1695. // Otherwise, the selected deallocation function shall be the function
  1696. // with one parameter.
  1697. if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
  1698. if (Matches[0].second->getNumParams() == 1)
  1699. Matches.erase(Matches.begin());
  1700. else
  1701. Matches.erase(Matches.begin() + 1);
  1702. assert(Matches[0].second->getNumParams() == 2 &&
  1703. "found an unexpected usual deallocation function");
  1704. }
  1705. }
  1706. // C++ [expr.new]p20:
  1707. // [...] If the lookup finds a single matching deallocation
  1708. // function, that function will be called; otherwise, no
  1709. // deallocation function will be called.
  1710. if (Matches.size() == 1) {
  1711. OperatorDelete = Matches[0].second;
  1712. // C++0x [expr.new]p20:
  1713. // If the lookup finds the two-parameter form of a usual
  1714. // deallocation function (3.7.4.2) and that function, considered
  1715. // as a placement deallocation function, would have been
  1716. // selected as a match for the allocation function, the program
  1717. // is ill-formed.
  1718. if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
  1719. isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
  1720. Diag(StartLoc, diag::err_placement_new_non_placement_delete)
  1721. << SourceRange(PlaceArgs.front()->getLocStart(),
  1722. PlaceArgs.back()->getLocEnd());
  1723. if (!OperatorDelete->isImplicit())
  1724. Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
  1725. << DeleteName;
  1726. } else {
  1727. CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
  1728. Matches[0].first);
  1729. }
  1730. }
  1731. return false;
  1732. #endif // HLSL Change
  1733. }
  1734. /// \brief Find an fitting overload for the allocation function
  1735. /// in the specified scope.
  1736. ///
  1737. /// \param StartLoc The location of the 'new' token.
  1738. /// \param Range The range of the placement arguments.
  1739. /// \param Name The name of the function ('operator new' or 'operator new[]').
  1740. /// \param Args The placement arguments specified.
  1741. /// \param Ctx The scope in which we should search; either a class scope or the
  1742. /// translation unit.
  1743. /// \param AllowMissing If \c true, report an error if we can't find any
  1744. /// allocation functions. Otherwise, succeed but don't fill in \p
  1745. /// Operator.
  1746. /// \param Operator Filled in with the found allocation function. Unchanged if
  1747. /// no allocation function was found.
  1748. /// \param Diagnose If \c true, issue errors if the allocation function is not
  1749. /// usable.
  1750. bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
  1751. DeclarationName Name, MultiExprArg Args,
  1752. DeclContext *Ctx,
  1753. bool AllowMissing, FunctionDecl *&Operator,
  1754. bool Diagnose) {
  1755. LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
  1756. LookupQualifiedName(R, Ctx);
  1757. if (R.empty()) {
  1758. if (AllowMissing || !Diagnose)
  1759. return false;
  1760. return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
  1761. << Name << Range;
  1762. }
  1763. if (R.isAmbiguous())
  1764. return true;
  1765. R.suppressDiagnostics();
  1766. OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
  1767. for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
  1768. Alloc != AllocEnd; ++Alloc) {
  1769. // Even member operator new/delete are implicitly treated as
  1770. // static, so don't use AddMemberCandidate.
  1771. NamedDecl *D = (*Alloc)->getUnderlyingDecl();
  1772. if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
  1773. AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
  1774. /*ExplicitTemplateArgs=*/nullptr,
  1775. Args, Candidates,
  1776. /*SuppressUserConversions=*/false);
  1777. continue;
  1778. }
  1779. FunctionDecl *Fn = cast<FunctionDecl>(D);
  1780. AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
  1781. /*SuppressUserConversions=*/false);
  1782. }
  1783. // Do the resolution.
  1784. OverloadCandidateSet::iterator Best;
  1785. switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
  1786. case OR_Success: {
  1787. // Got one!
  1788. FunctionDecl *FnDecl = Best->Function;
  1789. if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
  1790. Best->FoundDecl, Diagnose) == AR_inaccessible)
  1791. return true;
  1792. Operator = FnDecl;
  1793. return false;
  1794. }
  1795. case OR_No_Viable_Function:
  1796. if (Diagnose) {
  1797. Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
  1798. << Name << Range;
  1799. Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
  1800. }
  1801. return true;
  1802. case OR_Ambiguous:
  1803. if (Diagnose) {
  1804. Diag(StartLoc, diag::err_ovl_ambiguous_call)
  1805. << Name << Range;
  1806. Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
  1807. }
  1808. return true;
  1809. case OR_Deleted: {
  1810. if (Diagnose) {
  1811. Diag(StartLoc, diag::err_ovl_deleted_call)
  1812. << Best->Function->isDeleted()
  1813. << Name
  1814. << getDeletedOrUnavailableSuffix(Best->Function)
  1815. << Range;
  1816. Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
  1817. }
  1818. return true;
  1819. }
  1820. }
  1821. llvm_unreachable("Unreachable, bad result from BestViableFunction");
  1822. }
  1823. /// DeclareGlobalNewDelete - Declare the global forms of operator new and
  1824. /// delete. These are:
  1825. /// @code
  1826. /// // C++03:
  1827. /// void* operator new(std::size_t) throw(std::bad_alloc);
  1828. /// void* operator new[](std::size_t) throw(std::bad_alloc);
  1829. /// void operator delete(void *) throw();
  1830. /// void operator delete[](void *) throw();
  1831. /// // C++11:
  1832. /// void* operator new(std::size_t);
  1833. /// void* operator new[](std::size_t);
  1834. /// void operator delete(void *) noexcept;
  1835. /// void operator delete[](void *) noexcept;
  1836. /// // C++1y:
  1837. /// void* operator new(std::size_t);
  1838. /// void* operator new[](std::size_t);
  1839. /// void operator delete(void *) noexcept;
  1840. /// void operator delete[](void *) noexcept;
  1841. /// void operator delete(void *, std::size_t) noexcept;
  1842. /// void operator delete[](void *, std::size_t) noexcept;
  1843. /// @endcode
  1844. /// Note that the placement and nothrow forms of new are *not* implicitly
  1845. /// declared. Their use requires including \<new\>.
  1846. void Sema::DeclareGlobalNewDelete() {
  1847. if (GlobalNewDeleteDeclared)
  1848. return;
  1849. // C++ [basic.std.dynamic]p2:
  1850. // [...] The following allocation and deallocation functions (18.4) are
  1851. // implicitly declared in global scope in each translation unit of a
  1852. // program
  1853. //
  1854. // C++03:
  1855. // void* operator new(std::size_t) throw(std::bad_alloc);
  1856. // void* operator new[](std::size_t) throw(std::bad_alloc);
  1857. // void operator delete(void*) throw();
  1858. // void operator delete[](void*) throw();
  1859. // C++11:
  1860. // void* operator new(std::size_t);
  1861. // void* operator new[](std::size_t);
  1862. // void operator delete(void*) noexcept;
  1863. // void operator delete[](void*) noexcept;
  1864. // C++1y:
  1865. // void* operator new(std::size_t);
  1866. // void* operator new[](std::size_t);
  1867. // void operator delete(void*) noexcept;
  1868. // void operator delete[](void*) noexcept;
  1869. // void operator delete(void*, std::size_t) noexcept;
  1870. // void operator delete[](void*, std::size_t) noexcept;
  1871. //
  1872. // These implicit declarations introduce only the function names operator
  1873. // new, operator new[], operator delete, operator delete[].
  1874. //
  1875. // Here, we need to refer to std::bad_alloc, so we will implicitly declare
  1876. // "std" or "bad_alloc" as necessary to form the exception specification.
  1877. // However, we do not make these implicit declarations visible to name
  1878. // lookup.
  1879. if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
  1880. // The "std::bad_alloc" class has not yet been declared, so build it
  1881. // implicitly.
  1882. StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
  1883. getOrCreateStdNamespace(),
  1884. SourceLocation(), SourceLocation(),
  1885. &PP.getIdentifierTable().get("bad_alloc"),
  1886. nullptr);
  1887. getStdBadAlloc()->setImplicit(true);
  1888. }
  1889. GlobalNewDeleteDeclared = true;
  1890. QualType VoidPtr = Context.getPointerType(Context.VoidTy);
  1891. QualType SizeT = Context.getSizeType();
  1892. bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
  1893. DeclareGlobalAllocationFunction(
  1894. Context.DeclarationNames.getCXXOperatorName(OO_New),
  1895. VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
  1896. DeclareGlobalAllocationFunction(
  1897. Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
  1898. VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
  1899. DeclareGlobalAllocationFunction(
  1900. Context.DeclarationNames.getCXXOperatorName(OO_Delete),
  1901. Context.VoidTy, VoidPtr);
  1902. DeclareGlobalAllocationFunction(
  1903. Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
  1904. Context.VoidTy, VoidPtr);
  1905. if (getLangOpts().SizedDeallocation) {
  1906. DeclareGlobalAllocationFunction(
  1907. Context.DeclarationNames.getCXXOperatorName(OO_Delete),
  1908. Context.VoidTy, VoidPtr, Context.getSizeType());
  1909. DeclareGlobalAllocationFunction(
  1910. Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
  1911. Context.VoidTy, VoidPtr, Context.getSizeType());
  1912. }
  1913. }
  1914. /// DeclareGlobalAllocationFunction - Declares a single implicit global
  1915. /// allocation function if it doesn't already exist.
  1916. void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
  1917. QualType Return,
  1918. QualType Param1, QualType Param2,
  1919. bool AddRestrictAttr) {
  1920. // HLSL Change Starts Here
  1921. // No support for new and delete operators.
  1922. llvm_unreachable("no support for new and delete in HLSL");
  1923. #if 0
  1924. // HLSL Change Ends Here DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
  1925. unsigned NumParams = Param2.isNull() ? 1 : 2;
  1926. // Check if this function is already declared.
  1927. DeclContext::lookup_result R = GlobalCtx->lookup(Name);
  1928. for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
  1929. Alloc != AllocEnd; ++Alloc) {
  1930. // Only look at non-template functions, as it is the predefined,
  1931. // non-templated allocation function we are trying to declare here.
  1932. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
  1933. if (Func->getNumParams() == NumParams) {
  1934. QualType InitialParam1Type =
  1935. Context.getCanonicalType(Func->getParamDecl(0)
  1936. ->getType().getUnqualifiedType());
  1937. QualType InitialParam2Type =
  1938. NumParams == 2
  1939. ? Context.getCanonicalType(Func->getParamDecl(1)
  1940. ->getType().getUnqualifiedType())
  1941. : QualType();
  1942. // FIXME: Do we need to check for default arguments here?
  1943. if (InitialParam1Type == Param1 &&
  1944. (NumParams == 1 || InitialParam2Type == Param2)) {
  1945. if (AddRestrictAttr && !Func->hasAttr<RestrictAttr>())
  1946. Func->addAttr(RestrictAttr::CreateImplicit(
  1947. Context, RestrictAttr::GNU_malloc));
  1948. // Make the function visible to name lookup, even if we found it in
  1949. // an unimported module. It either is an implicitly-declared global
  1950. // allocation function, or is suppressing that function.
  1951. Func->setHidden(false);
  1952. return;
  1953. }
  1954. }
  1955. }
  1956. }
  1957. FunctionProtoType::ExtProtoInfo EPI;
  1958. QualType BadAllocType;
  1959. bool HasBadAllocExceptionSpec
  1960. = (Name.getCXXOverloadedOperator() == OO_New ||
  1961. Name.getCXXOverloadedOperator() == OO_Array_New);
  1962. if (HasBadAllocExceptionSpec) {
  1963. if (!getLangOpts().CPlusPlus11) {
  1964. BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
  1965. assert(StdBadAlloc && "Must have std::bad_alloc declared");
  1966. EPI.ExceptionSpec.Type = EST_Dynamic;
  1967. EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
  1968. }
  1969. } else {
  1970. EPI.ExceptionSpec =
  1971. getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
  1972. }
  1973. QualType Params[] = { Param1, Param2 };
  1974. QualType FnType = Context.getFunctionType(
  1975. Return, llvm::makeArrayRef(Params, NumParams), EPI);
  1976. FunctionDecl *Alloc =
  1977. FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
  1978. SourceLocation(), Name,
  1979. FnType, /*TInfo=*/nullptr, SC_None, false, true);
  1980. Alloc->setImplicit();
  1981. // Implicit sized deallocation functions always have default visibility.
  1982. Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
  1983. VisibilityAttr::Default));
  1984. if (AddRestrictAttr)
  1985. Alloc->addAttr(
  1986. RestrictAttr::CreateImplicit(Context, RestrictAttr::GNU_malloc));
  1987. ParmVarDecl *ParamDecls[2];
  1988. for (unsigned I = 0; I != NumParams; ++I) {
  1989. ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
  1990. SourceLocation(), nullptr,
  1991. Params[I], /*TInfo=*/nullptr,
  1992. SC_None, nullptr);
  1993. ParamDecls[I]->setImplicit();
  1994. }
  1995. Alloc->setParams(llvm::makeArrayRef(ParamDecls, NumParams));
  1996. Context.getTranslationUnitDecl()->addDecl(Alloc);
  1997. IdResolver.tryAddTopLevelDecl(Alloc, Name);
  1998. #endif // HLSL Change
  1999. }
  2000. FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
  2001. bool CanProvideSize,
  2002. DeclarationName Name) {
  2003. DeclareGlobalNewDelete();
  2004. LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
  2005. LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
  2006. // C++ [expr.new]p20:
  2007. // [...] Any non-placement deallocation function matches a
  2008. // non-placement allocation function. [...]
  2009. llvm::SmallVector<FunctionDecl*, 2> Matches;
  2010. for (LookupResult::iterator D = FoundDelete.begin(),
  2011. DEnd = FoundDelete.end();
  2012. D != DEnd; ++D) {
  2013. if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
  2014. if (isNonPlacementDeallocationFunction(*this, Fn))
  2015. Matches.push_back(Fn);
  2016. }
  2017. // C++1y [expr.delete]p?:
  2018. // If the type is complete and deallocation function lookup finds both a
  2019. // usual deallocation function with only a pointer parameter and a usual
  2020. // deallocation function with both a pointer parameter and a size
  2021. // parameter, then the selected deallocation function shall be the one
  2022. // with two parameters. Otherwise, the selected deallocation function
  2023. // shall be the function with one parameter.
  2024. if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
  2025. unsigned NumArgs = CanProvideSize ? 2 : 1;
  2026. if (Matches[0]->getNumParams() != NumArgs)
  2027. Matches.erase(Matches.begin());
  2028. else
  2029. Matches.erase(Matches.begin() + 1);
  2030. assert(Matches[0]->getNumParams() == NumArgs &&
  2031. "found an unexpected usual deallocation function");
  2032. }
  2033. assert(Matches.size() == 1 &&
  2034. "unexpectedly have multiple usual deallocation functions");
  2035. return Matches.front();
  2036. }
  2037. bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
  2038. DeclarationName Name,
  2039. FunctionDecl* &Operator, bool Diagnose) {
  2040. LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
  2041. // Try to find operator delete/operator delete[] in class scope.
  2042. LookupQualifiedName(Found, RD);
  2043. if (Found.isAmbiguous())
  2044. return true;
  2045. Found.suppressDiagnostics();
  2046. SmallVector<DeclAccessPair,4> Matches;
  2047. for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
  2048. F != FEnd; ++F) {
  2049. NamedDecl *ND = (*F)->getUnderlyingDecl();
  2050. // Ignore template operator delete members from the check for a usual
  2051. // deallocation function.
  2052. if (isa<FunctionTemplateDecl>(ND))
  2053. continue;
  2054. if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
  2055. Matches.push_back(F.getPair());
  2056. }
  2057. // There's exactly one suitable operator; pick it.
  2058. if (Matches.size() == 1) {
  2059. Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
  2060. if (Operator->isDeleted()) {
  2061. if (Diagnose) {
  2062. Diag(StartLoc, diag::err_deleted_function_use);
  2063. NoteDeletedFunction(Operator);
  2064. }
  2065. return true;
  2066. }
  2067. if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
  2068. Matches[0], Diagnose) == AR_inaccessible)
  2069. return true;
  2070. return false;
  2071. // We found multiple suitable operators; complain about the ambiguity.
  2072. } else if (!Matches.empty()) {
  2073. if (Diagnose) {
  2074. Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
  2075. << Name << RD;
  2076. for (SmallVectorImpl<DeclAccessPair>::iterator
  2077. F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
  2078. Diag((*F)->getUnderlyingDecl()->getLocation(),
  2079. diag::note_member_declared_here) << Name;
  2080. }
  2081. return true;
  2082. }
  2083. // We did find operator delete/operator delete[] declarations, but
  2084. // none of them were suitable.
  2085. if (!Found.empty()) {
  2086. if (Diagnose) {
  2087. Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
  2088. << Name << RD;
  2089. for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
  2090. F != FEnd; ++F)
  2091. Diag((*F)->getUnderlyingDecl()->getLocation(),
  2092. diag::note_member_declared_here) << Name;
  2093. }
  2094. return true;
  2095. }
  2096. Operator = nullptr;
  2097. return false;
  2098. }
  2099. namespace {
  2100. /// \brief Checks whether delete-expression, and new-expression used for
  2101. /// initializing deletee have the same array form.
  2102. class MismatchingNewDeleteDetector {
  2103. public:
  2104. enum MismatchResult {
  2105. /// Indicates that there is no mismatch or a mismatch cannot be proven.
  2106. NoMismatch,
  2107. /// Indicates that variable is initialized with mismatching form of \a new.
  2108. VarInitMismatches,
  2109. /// Indicates that member is initialized with mismatching form of \a new.
  2110. MemberInitMismatches,
  2111. /// Indicates that 1 or more constructors' definitions could not been
  2112. /// analyzed, and they will be checked again at the end of translation unit.
  2113. AnalyzeLater
  2114. };
  2115. /// \param EndOfTU True, if this is the final analysis at the end of
  2116. /// translation unit. False, if this is the initial analysis at the point
  2117. /// delete-expression was encountered.
  2118. explicit MismatchingNewDeleteDetector(bool EndOfTU)
  2119. : IsArrayForm(false), Field(nullptr), EndOfTU(EndOfTU),
  2120. HasUndefinedConstructors(false) {}
  2121. /// \brief Checks whether pointee of a delete-expression is initialized with
  2122. /// matching form of new-expression.
  2123. ///
  2124. /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
  2125. /// point where delete-expression is encountered, then a warning will be
  2126. /// issued immediately. If return value is \c AnalyzeLater at the point where
  2127. /// delete-expression is seen, then member will be analyzed at the end of
  2128. /// translation unit. \c AnalyzeLater is returned iff at least one constructor
  2129. /// couldn't be analyzed. If at least one constructor initializes the member
  2130. /// with matching type of new, the return value is \c NoMismatch.
  2131. MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
  2132. /// \brief Analyzes a class member.
  2133. /// \param Field Class member to analyze.
  2134. /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
  2135. /// for deleting the \p Field.
  2136. MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
  2137. /// List of mismatching new-expressions used for initialization of the pointee
  2138. llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
  2139. /// Indicates whether delete-expression was in array form.
  2140. bool IsArrayForm;
  2141. FieldDecl *Field;
  2142. private:
  2143. const bool EndOfTU;
  2144. /// \brief Indicates that there is at least one constructor without body.
  2145. bool HasUndefinedConstructors;
  2146. /// \brief Returns \c CXXNewExpr from given initialization expression.
  2147. /// \param E Expression used for initializing pointee in delete-expression.
  2148. /// E can be a single-element \c InitListExpr consisting of new-expression.
  2149. const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
  2150. /// \brief Returns whether member is initialized with mismatching form of
  2151. /// \c new either by the member initializer or in-class initialization.
  2152. ///
  2153. /// If bodies of all constructors are not visible at the end of translation
  2154. /// unit or at least one constructor initializes member with the matching
  2155. /// form of \c new, mismatch cannot be proven, and this function will return
  2156. /// \c NoMismatch.
  2157. MismatchResult analyzeMemberExpr(const MemberExpr *ME);
  2158. /// \brief Returns whether variable is initialized with mismatching form of
  2159. /// \c new.
  2160. ///
  2161. /// If variable is initialized with matching form of \c new or variable is not
  2162. /// initialized with a \c new expression, this function will return true.
  2163. /// If variable is initialized with mismatching form of \c new, returns false.
  2164. /// \param D Variable to analyze.
  2165. bool hasMatchingVarInit(const DeclRefExpr *D);
  2166. /// \brief Checks whether the constructor initializes pointee with mismatching
  2167. /// form of \c new.
  2168. ///
  2169. /// Returns true, if member is initialized with matching form of \c new in
  2170. /// member initializer list. Returns false, if member is initialized with the
  2171. /// matching form of \c new in this constructor's initializer or given
  2172. /// constructor isn't defined at the point where delete-expression is seen, or
  2173. /// member isn't initialized by the constructor.
  2174. bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
  2175. /// \brief Checks whether member is initialized with matching form of
  2176. /// \c new in member initializer list.
  2177. bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
  2178. /// Checks whether member is initialized with mismatching form of \c new by
  2179. /// in-class initializer.
  2180. MismatchResult analyzeInClassInitializer();
  2181. };
  2182. }
  2183. MismatchingNewDeleteDetector::MismatchResult
  2184. MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
  2185. NewExprs.clear();
  2186. assert(DE && "Expected delete-expression");
  2187. IsArrayForm = DE->isArrayForm();
  2188. const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
  2189. if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
  2190. return analyzeMemberExpr(ME);
  2191. } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
  2192. if (!hasMatchingVarInit(D))
  2193. return VarInitMismatches;
  2194. }
  2195. return NoMismatch;
  2196. }
  2197. const CXXNewExpr *
  2198. MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
  2199. assert(E != nullptr && "Expected a valid initializer expression");
  2200. E = E->IgnoreParenImpCasts();
  2201. if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
  2202. if (ILE->getNumInits() == 1)
  2203. E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
  2204. }
  2205. return dyn_cast_or_null<const CXXNewExpr>(E);
  2206. }
  2207. bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
  2208. const CXXCtorInitializer *CI) {
  2209. const CXXNewExpr *NE = nullptr;
  2210. if (Field == CI->getMember() &&
  2211. (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
  2212. if (NE->isArray() == IsArrayForm)
  2213. return true;
  2214. else
  2215. NewExprs.push_back(NE);
  2216. }
  2217. return false;
  2218. }
  2219. bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
  2220. const CXXConstructorDecl *CD) {
  2221. if (CD->isImplicit())
  2222. return false;
  2223. const FunctionDecl *Definition = CD;
  2224. if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
  2225. HasUndefinedConstructors = true;
  2226. return EndOfTU;
  2227. }
  2228. for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
  2229. if (hasMatchingNewInCtorInit(CI))
  2230. return true;
  2231. }
  2232. return false;
  2233. }
  2234. MismatchingNewDeleteDetector::MismatchResult
  2235. MismatchingNewDeleteDetector::analyzeInClassInitializer() {
  2236. assert(Field != nullptr && "This should be called only for members");
  2237. if (const CXXNewExpr *NE =
  2238. getNewExprFromInitListOrExpr(Field->getInClassInitializer())) {
  2239. if (NE->isArray() != IsArrayForm) {
  2240. NewExprs.push_back(NE);
  2241. return MemberInitMismatches;
  2242. }
  2243. }
  2244. return NoMismatch;
  2245. }
  2246. MismatchingNewDeleteDetector::MismatchResult
  2247. MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
  2248. bool DeleteWasArrayForm) {
  2249. assert(Field != nullptr && "Analysis requires a valid class member.");
  2250. this->Field = Field;
  2251. IsArrayForm = DeleteWasArrayForm;
  2252. const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
  2253. for (const auto *CD : RD->ctors()) {
  2254. if (hasMatchingNewInCtor(CD))
  2255. return NoMismatch;
  2256. }
  2257. if (HasUndefinedConstructors)
  2258. return EndOfTU ? NoMismatch : AnalyzeLater;
  2259. if (!NewExprs.empty())
  2260. return MemberInitMismatches;
  2261. return Field->hasInClassInitializer() ? analyzeInClassInitializer()
  2262. : NoMismatch;
  2263. }
  2264. MismatchingNewDeleteDetector::MismatchResult
  2265. MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
  2266. assert(ME != nullptr && "Expected a member expression");
  2267. if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  2268. return analyzeField(F, IsArrayForm);
  2269. return NoMismatch;
  2270. }
  2271. bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
  2272. const CXXNewExpr *NE = nullptr;
  2273. if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
  2274. if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
  2275. NE->isArray() != IsArrayForm) {
  2276. NewExprs.push_back(NE);
  2277. }
  2278. }
  2279. return NewExprs.empty();
  2280. }
  2281. static void
  2282. DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
  2283. const MismatchingNewDeleteDetector &Detector) {
  2284. SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
  2285. FixItHint H;
  2286. if (!Detector.IsArrayForm)
  2287. H = FixItHint::CreateInsertion(EndOfDelete, "[]");
  2288. else {
  2289. SourceLocation RSquare = Lexer::findLocationAfterToken(
  2290. DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
  2291. SemaRef.getLangOpts(), true);
  2292. if (RSquare.isValid())
  2293. H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
  2294. }
  2295. SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
  2296. << Detector.IsArrayForm << H;
  2297. for (const auto *NE : Detector.NewExprs)
  2298. SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
  2299. << Detector.IsArrayForm;
  2300. }
  2301. void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
  2302. if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
  2303. return;
  2304. MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
  2305. switch (Detector.analyzeDeleteExpr(DE)) {
  2306. case MismatchingNewDeleteDetector::VarInitMismatches:
  2307. case MismatchingNewDeleteDetector::MemberInitMismatches: {
  2308. DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
  2309. break;
  2310. }
  2311. case MismatchingNewDeleteDetector::AnalyzeLater: {
  2312. DeleteExprs[Detector.Field].push_back(
  2313. std::make_pair(DE->getLocStart(), DE->isArrayForm()));
  2314. break;
  2315. }
  2316. case MismatchingNewDeleteDetector::NoMismatch:
  2317. break;
  2318. }
  2319. }
  2320. void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
  2321. bool DeleteWasArrayForm) {
  2322. MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
  2323. switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
  2324. case MismatchingNewDeleteDetector::VarInitMismatches:
  2325. llvm_unreachable("This analysis should have been done for class members.");
  2326. case MismatchingNewDeleteDetector::AnalyzeLater:
  2327. llvm_unreachable("Analysis cannot be postponed any point beyond end of "
  2328. "translation unit.");
  2329. case MismatchingNewDeleteDetector::MemberInitMismatches:
  2330. DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
  2331. break;
  2332. case MismatchingNewDeleteDetector::NoMismatch:
  2333. break;
  2334. }
  2335. }
  2336. /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
  2337. /// @code ::delete ptr; @endcode
  2338. /// or
  2339. /// @code delete [] ptr; @endcode
  2340. ExprResult
  2341. Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
  2342. bool ArrayForm, Expr *ExE) {
  2343. // C++ [expr.delete]p1:
  2344. // The operand shall have a pointer type, or a class type having a single
  2345. // non-explicit conversion function to a pointer type. The result has type
  2346. // void.
  2347. //
  2348. // DR599 amends "pointer type" to "pointer to object type" in both cases.
  2349. ExprResult Ex = ExE;
  2350. FunctionDecl *OperatorDelete = nullptr;
  2351. bool ArrayFormAsWritten = ArrayForm;
  2352. bool UsualArrayDeleteWantsSize = false;
  2353. if (!Ex.get()->isTypeDependent()) {
  2354. // Perform lvalue-to-rvalue cast, if needed.
  2355. Ex = DefaultLvalueConversion(Ex.get());
  2356. if (Ex.isInvalid())
  2357. return ExprError();
  2358. QualType Type = Ex.get()->getType();
  2359. class DeleteConverter : public ContextualImplicitConverter {
  2360. public:
  2361. DeleteConverter() : ContextualImplicitConverter(false, true) {}
  2362. bool match(QualType ConvType) override {
  2363. // FIXME: If we have an operator T* and an operator void*, we must pick
  2364. // the operator T*.
  2365. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  2366. if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
  2367. return true;
  2368. return false;
  2369. }
  2370. SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
  2371. QualType T) override {
  2372. return S.Diag(Loc, diag::err_delete_operand) << T;
  2373. }
  2374. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  2375. QualType T) override {
  2376. return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
  2377. }
  2378. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  2379. QualType T,
  2380. QualType ConvTy) override {
  2381. return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
  2382. }
  2383. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  2384. QualType ConvTy) override {
  2385. return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
  2386. << ConvTy;
  2387. }
  2388. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  2389. QualType T) override {
  2390. return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
  2391. }
  2392. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  2393. QualType ConvTy) override {
  2394. return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
  2395. << ConvTy;
  2396. }
  2397. SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
  2398. QualType T,
  2399. QualType ConvTy) override {
  2400. llvm_unreachable("conversion functions are permitted");
  2401. }
  2402. } Converter;
  2403. Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
  2404. if (Ex.isInvalid())
  2405. return ExprError();
  2406. Type = Ex.get()->getType();
  2407. if (!Converter.match(Type))
  2408. // FIXME: PerformContextualImplicitConversion should return ExprError
  2409. // itself in this case.
  2410. return ExprError();
  2411. QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
  2412. QualType PointeeElem = Context.getBaseElementType(Pointee);
  2413. if (unsigned AddressSpace = Pointee.getAddressSpace())
  2414. return Diag(Ex.get()->getLocStart(),
  2415. diag::err_address_space_qualified_delete)
  2416. << Pointee.getUnqualifiedType() << AddressSpace;
  2417. CXXRecordDecl *PointeeRD = nullptr;
  2418. if (Pointee->isVoidType() && !isSFINAEContext()) {
  2419. // The C++ standard bans deleting a pointer to a non-object type, which
  2420. // effectively bans deletion of "void*". However, most compilers support
  2421. // this, so we treat it as a warning unless we're in a SFINAE context.
  2422. Diag(StartLoc, diag::ext_delete_void_ptr_operand)
  2423. << Type << Ex.get()->getSourceRange();
  2424. } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
  2425. return ExprError(Diag(StartLoc, diag::err_delete_operand)
  2426. << Type << Ex.get()->getSourceRange());
  2427. } else if (!Pointee->isDependentType()) {
  2428. if (!RequireCompleteType(StartLoc, Pointee,
  2429. diag::warn_delete_incomplete, Ex.get())) {
  2430. if (const RecordType *RT = PointeeElem->getAs<RecordType>())
  2431. PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
  2432. }
  2433. }
  2434. if (Pointee->isArrayType() && !ArrayForm) {
  2435. Diag(StartLoc, diag::warn_delete_array_type)
  2436. << Type << Ex.get()->getSourceRange()
  2437. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
  2438. ArrayForm = true;
  2439. }
  2440. DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
  2441. ArrayForm ? OO_Array_Delete : OO_Delete);
  2442. if (PointeeRD) {
  2443. if (!UseGlobal &&
  2444. FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
  2445. OperatorDelete))
  2446. return ExprError();
  2447. // If we're allocating an array of records, check whether the
  2448. // usual operator delete[] has a size_t parameter.
  2449. if (ArrayForm) {
  2450. // If the user specifically asked to use the global allocator,
  2451. // we'll need to do the lookup into the class.
  2452. if (UseGlobal)
  2453. UsualArrayDeleteWantsSize =
  2454. doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
  2455. // Otherwise, the usual operator delete[] should be the
  2456. // function we just found.
  2457. else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
  2458. UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
  2459. }
  2460. if (!PointeeRD->hasIrrelevantDestructor())
  2461. if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
  2462. MarkFunctionReferenced(StartLoc,
  2463. const_cast<CXXDestructorDecl*>(Dtor));
  2464. if (DiagnoseUseOfDecl(Dtor, StartLoc))
  2465. return ExprError();
  2466. }
  2467. // C++ [expr.delete]p3:
  2468. // In the first alternative (delete object), if the static type of the
  2469. // object to be deleted is different from its dynamic type, the static
  2470. // type shall be a base class of the dynamic type of the object to be
  2471. // deleted and the static type shall have a virtual destructor or the
  2472. // behavior is undefined.
  2473. //
  2474. // Note: a final class cannot be derived from, no issue there
  2475. if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
  2476. CXXDestructorDecl *dtor = PointeeRD->getDestructor();
  2477. if (dtor && !dtor->isVirtual()) {
  2478. if (PointeeRD->isAbstract()) {
  2479. // If the class is abstract, we warn by default, because we're
  2480. // sure the code has undefined behavior.
  2481. Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
  2482. << PointeeElem;
  2483. } else if (!ArrayForm) {
  2484. // Otherwise, if this is not an array delete, it's a bit suspect,
  2485. // but not necessarily wrong.
  2486. Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
  2487. }
  2488. }
  2489. }
  2490. }
  2491. if (!OperatorDelete)
  2492. // Look for a global declaration.
  2493. OperatorDelete = FindUsualDeallocationFunction(
  2494. StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
  2495. (!ArrayForm || UsualArrayDeleteWantsSize ||
  2496. Pointee.isDestructedType()),
  2497. DeleteName);
  2498. MarkFunctionReferenced(StartLoc, OperatorDelete);
  2499. // Check access and ambiguity of operator delete and destructor.
  2500. if (PointeeRD) {
  2501. if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
  2502. CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
  2503. PDiag(diag::err_access_dtor) << PointeeElem);
  2504. }
  2505. }
  2506. }
  2507. CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
  2508. Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
  2509. UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
  2510. AnalyzeDeleteExprMismatch(Result);
  2511. return Result;
  2512. }
  2513. /// \brief Check the use of the given variable as a C++ condition in an if,
  2514. /// while, do-while, or switch statement.
  2515. ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
  2516. SourceLocation StmtLoc,
  2517. bool ConvertToBoolean) {
  2518. if (ConditionVar->isInvalidDecl())
  2519. return ExprError();
  2520. QualType T = ConditionVar->getType();
  2521. // C++ [stmt.select]p2:
  2522. // The declarator shall not specify a function or an array.
  2523. if (T->isFunctionType())
  2524. return ExprError(Diag(ConditionVar->getLocation(),
  2525. diag::err_invalid_use_of_function_type)
  2526. << ConditionVar->getSourceRange());
  2527. else if (T->isArrayType())
  2528. return ExprError(Diag(ConditionVar->getLocation(),
  2529. diag::err_invalid_use_of_array_type)
  2530. << ConditionVar->getSourceRange());
  2531. ExprResult Condition = DeclRefExpr::Create(
  2532. Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
  2533. /*enclosing*/ false, ConditionVar->getLocation(),
  2534. ConditionVar->getType().getNonReferenceType(), VK_LValue);
  2535. MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
  2536. if (ConvertToBoolean) {
  2537. Condition = CheckBooleanCondition(Condition.get(), StmtLoc);
  2538. if (Condition.isInvalid())
  2539. return ExprError();
  2540. }
  2541. return Condition;
  2542. }
  2543. /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
  2544. ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
  2545. // C++ 6.4p4:
  2546. // The value of a condition that is an initialized declaration in a statement
  2547. // other than a switch statement is the value of the declared variable
  2548. // implicitly converted to type bool. If that conversion is ill-formed, the
  2549. // program is ill-formed.
  2550. // The value of a condition that is an expression is the value of the
  2551. // expression, implicitly converted to bool.
  2552. //
  2553. return PerformContextuallyConvertToBool(CondExpr);
  2554. }
  2555. /// Helper function to determine whether this is the (deprecated) C++
  2556. /// conversion from a string literal to a pointer to non-const char or
  2557. /// non-const wchar_t (for narrow and wide string literals,
  2558. /// respectively).
  2559. bool
  2560. Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
  2561. // Look inside the implicit cast, if it exists.
  2562. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
  2563. From = Cast->getSubExpr();
  2564. // A string literal (2.13.4) that is not a wide string literal can
  2565. // be converted to an rvalue of type "pointer to char"; a wide
  2566. // string literal can be converted to an rvalue of type "pointer
  2567. // to wchar_t" (C++ 4.2p2).
  2568. if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
  2569. if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
  2570. if (const BuiltinType *ToPointeeType
  2571. = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
  2572. // This conversion is considered only when there is an
  2573. // explicit appropriate pointer target type (C++ 4.2p2).
  2574. if (!ToPtrType->getPointeeType().hasQualifiers()) {
  2575. switch (StrLit->getKind()) {
  2576. case StringLiteral::UTF8:
  2577. case StringLiteral::UTF16:
  2578. case StringLiteral::UTF32:
  2579. // We don't allow UTF literals to be implicitly converted
  2580. break;
  2581. case StringLiteral::Ascii:
  2582. return (ToPointeeType->getKind() == BuiltinType::Char_U ||
  2583. ToPointeeType->getKind() == BuiltinType::Char_S);
  2584. case StringLiteral::Wide:
  2585. return ToPointeeType->isWideCharType();
  2586. }
  2587. }
  2588. }
  2589. return false;
  2590. }
  2591. static ExprResult BuildCXXCastArgument(Sema &S,
  2592. SourceLocation CastLoc,
  2593. QualType Ty,
  2594. CastKind Kind,
  2595. CXXMethodDecl *Method,
  2596. DeclAccessPair FoundDecl,
  2597. bool HadMultipleCandidates,
  2598. Expr *From) {
  2599. switch (Kind) {
  2600. default: llvm_unreachable("Unhandled cast kind!");
  2601. case CK_ConstructorConversion: {
  2602. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
  2603. SmallVector<Expr*, 8> ConstructorArgs;
  2604. if (S.RequireNonAbstractType(CastLoc, Ty,
  2605. diag::err_allocation_of_abstract_type))
  2606. return ExprError();
  2607. if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
  2608. return ExprError();
  2609. S.CheckConstructorAccess(CastLoc, Constructor,
  2610. InitializedEntity::InitializeTemporary(Ty),
  2611. Constructor->getAccess());
  2612. if (S.DiagnoseUseOfDecl(Method, CastLoc))
  2613. return ExprError();
  2614. ExprResult Result = S.BuildCXXConstructExpr(
  2615. CastLoc, Ty, cast<CXXConstructorDecl>(Method),
  2616. ConstructorArgs, HadMultipleCandidates,
  2617. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  2618. CXXConstructExpr::CK_Complete, SourceRange());
  2619. if (Result.isInvalid())
  2620. return ExprError();
  2621. return S.MaybeBindToTemporary(Result.getAs<Expr>());
  2622. }
  2623. case CK_UserDefinedConversion: {
  2624. assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
  2625. S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
  2626. if (S.DiagnoseUseOfDecl(Method, CastLoc))
  2627. return ExprError();
  2628. // Create an implicit call expr that calls it.
  2629. CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
  2630. ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
  2631. HadMultipleCandidates);
  2632. if (Result.isInvalid())
  2633. return ExprError();
  2634. // Record usage of conversion in an implicit cast.
  2635. Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
  2636. CK_UserDefinedConversion, Result.get(),
  2637. nullptr, Result.get()->getValueKind());
  2638. return S.MaybeBindToTemporary(Result.get());
  2639. }
  2640. }
  2641. }
  2642. /// PerformImplicitConversion - Perform an implicit conversion of the
  2643. /// expression From to the type ToType using the pre-computed implicit
  2644. /// conversion sequence ICS. Returns the converted
  2645. /// expression. Action is the kind of conversion we're performing,
  2646. /// used in the error message.
  2647. ExprResult
  2648. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  2649. const ImplicitConversionSequence &ICS,
  2650. AssignmentAction Action,
  2651. CheckedConversionKind CCK) {
  2652. switch (ICS.getKind()) {
  2653. case ImplicitConversionSequence::StandardConversion: {
  2654. ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
  2655. Action, CCK);
  2656. if (Res.isInvalid())
  2657. return ExprError();
  2658. From = Res.get();
  2659. break;
  2660. }
  2661. case ImplicitConversionSequence::UserDefinedConversion: {
  2662. FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
  2663. CastKind CastKind;
  2664. QualType BeforeToType;
  2665. assert(FD && "no conversion function for user-defined conversion seq");
  2666. if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
  2667. CastKind = CK_UserDefinedConversion;
  2668. // If the user-defined conversion is specified by a conversion function,
  2669. // the initial standard conversion sequence converts the source type to
  2670. // the implicit object parameter of the conversion function.
  2671. BeforeToType = Context.getTagDeclType(Conv->getParent());
  2672. } else {
  2673. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
  2674. CastKind = CK_ConstructorConversion;
  2675. // Do no conversion if dealing with ... for the first conversion.
  2676. if (!ICS.UserDefined.EllipsisConversion) {
  2677. // If the user-defined conversion is specified by a constructor, the
  2678. // initial standard conversion sequence converts the source type to
  2679. // the type required by the argument of the constructor
  2680. BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
  2681. }
  2682. }
  2683. // Watch out for ellipsis conversion.
  2684. if (!ICS.UserDefined.EllipsisConversion) {
  2685. ExprResult Res =
  2686. PerformImplicitConversion(From, BeforeToType,
  2687. ICS.UserDefined.Before, AA_Converting,
  2688. CCK);
  2689. if (Res.isInvalid())
  2690. return ExprError();
  2691. From = Res.get();
  2692. }
  2693. ExprResult CastArg
  2694. = BuildCXXCastArgument(*this,
  2695. From->getLocStart(),
  2696. ToType.getNonReferenceType(),
  2697. CastKind, cast<CXXMethodDecl>(FD),
  2698. ICS.UserDefined.FoundConversionFunction,
  2699. ICS.UserDefined.HadMultipleCandidates,
  2700. From);
  2701. if (CastArg.isInvalid())
  2702. return ExprError();
  2703. From = CastArg.get();
  2704. return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
  2705. AA_Converting, CCK);
  2706. }
  2707. case ImplicitConversionSequence::AmbiguousConversion:
  2708. ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
  2709. PDiag(diag::err_typecheck_ambiguous_condition)
  2710. << From->getSourceRange());
  2711. return ExprError();
  2712. case ImplicitConversionSequence::EllipsisConversion:
  2713. llvm_unreachable("Cannot perform an ellipsis conversion");
  2714. case ImplicitConversionSequence::BadConversion:
  2715. return ExprError();
  2716. }
  2717. // Everything went well.
  2718. return From;
  2719. }
  2720. /// PerformImplicitConversion - Perform an implicit conversion of the
  2721. /// expression From to the type ToType by following the standard
  2722. /// conversion sequence SCS. Returns the converted
  2723. /// expression. Flavor is the context in which we're performing this
  2724. /// conversion, for use in error messages.
  2725. ExprResult
  2726. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  2727. const StandardConversionSequence& SCS,
  2728. AssignmentAction Action,
  2729. CheckedConversionKind CCK) {
  2730. bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
  2731. // Overall FIXME: we are recomputing too many types here and doing far too
  2732. // much extra work. What this means is that we need to keep track of more
  2733. // information that is computed when we try the implicit conversion initially,
  2734. // so that we don't need to recompute anything here.
  2735. QualType FromType = From->getType();
  2736. if (SCS.CopyConstructor) {
  2737. // FIXME: When can ToType be a reference type?
  2738. assert(!ToType->isReferenceType());
  2739. if (SCS.Second == ICK_Derived_To_Base) {
  2740. SmallVector<Expr*, 8> ConstructorArgs;
  2741. if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
  2742. From, /*FIXME:ConstructLoc*/SourceLocation(),
  2743. ConstructorArgs))
  2744. return ExprError();
  2745. return BuildCXXConstructExpr(
  2746. /*FIXME:ConstructLoc*/ SourceLocation(), ToType, SCS.CopyConstructor,
  2747. ConstructorArgs, /*HadMultipleCandidates*/ false,
  2748. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  2749. CXXConstructExpr::CK_Complete, SourceRange());
  2750. }
  2751. return BuildCXXConstructExpr(
  2752. /*FIXME:ConstructLoc*/ SourceLocation(), ToType, SCS.CopyConstructor,
  2753. From, /*HadMultipleCandidates*/ false,
  2754. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  2755. CXXConstructExpr::CK_Complete, SourceRange());
  2756. }
  2757. // Resolve overloaded function references.
  2758. if (Context.hasSameType(FromType, Context.OverloadTy)) {
  2759. DeclAccessPair Found;
  2760. FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
  2761. true, Found);
  2762. if (!Fn)
  2763. return ExprError();
  2764. if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
  2765. return ExprError();
  2766. From = FixOverloadedFunctionReference(From, Found, Fn);
  2767. FromType = From->getType();
  2768. }
  2769. // If we're converting to an atomic type, first convert to the corresponding
  2770. // non-atomic type.
  2771. QualType ToAtomicType;
  2772. if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
  2773. ToAtomicType = ToType;
  2774. ToType = ToAtomic->getValueType();
  2775. }
  2776. // Perform the first implicit conversion.
  2777. switch (SCS.First) {
  2778. case ICK_Identity:
  2779. if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
  2780. FromType = FromAtomic->getValueType().getUnqualifiedType();
  2781. From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
  2782. From, /*BasePath=*/nullptr, VK_RValue);
  2783. }
  2784. break;
  2785. case ICK_Lvalue_To_Rvalue: {
  2786. assert(From->getObjectKind() != OK_ObjCProperty);
  2787. ExprResult FromRes = DefaultLvalueConversion(From);
  2788. if (FromRes.isInvalid()) {
  2789. return ExprError();
  2790. }
  2791. From = FromRes.get();
  2792. FromType = From->getType();
  2793. break;
  2794. }
  2795. case ICK_Array_To_Pointer:
  2796. FromType = Context.getArrayDecayedType(FromType);
  2797. From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
  2798. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2799. break;
  2800. case ICK_Function_To_Pointer:
  2801. FromType = Context.getPointerType(FromType);
  2802. From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
  2803. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2804. break;
  2805. default:
  2806. llvm_unreachable("Improper first standard conversion");
  2807. }
  2808. // Perform the second implicit conversion
  2809. switch (SCS.Second) {
  2810. case ICK_Identity:
  2811. // C++ [except.spec]p5:
  2812. // [For] assignment to and initialization of pointers to functions,
  2813. // pointers to member functions, and references to functions: the
  2814. // target entity shall allow at least the exceptions allowed by the
  2815. // source value in the assignment or initialization.
  2816. switch (Action) {
  2817. case AA_Assigning:
  2818. case AA_Initializing:
  2819. // Note, function argument passing and returning are initialization.
  2820. case AA_Passing:
  2821. case AA_Returning:
  2822. case AA_Sending:
  2823. case AA_Passing_CFAudited:
  2824. if (CheckExceptionSpecCompatibility(From, ToType))
  2825. return ExprError();
  2826. break;
  2827. case AA_Casting:
  2828. case AA_Converting:
  2829. // Casts and implicit conversions are not initialization, so are not
  2830. // checked for exception specification mismatches.
  2831. break;
  2832. }
  2833. // Nothing else to do.
  2834. break;
  2835. case ICK_NoReturn_Adjustment:
  2836. // If both sides are functions (or pointers/references to them), there could
  2837. // be incompatible exception declarations.
  2838. if (CheckExceptionSpecCompatibility(From, ToType))
  2839. return ExprError();
  2840. From = ImpCastExprToType(From, ToType, CK_NoOp,
  2841. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2842. break;
  2843. case ICK_Integral_Promotion:
  2844. case ICK_Integral_Conversion:
  2845. if (ToType->isBooleanType()) {
  2846. assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
  2847. SCS.Second == ICK_Integral_Promotion &&
  2848. "only enums with fixed underlying type can promote to bool");
  2849. From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
  2850. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2851. } else {
  2852. From = ImpCastExprToType(From, ToType, CK_IntegralCast,
  2853. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2854. }
  2855. break;
  2856. case ICK_Floating_Promotion:
  2857. case ICK_Floating_Conversion:
  2858. From = ImpCastExprToType(From, ToType, CK_FloatingCast,
  2859. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2860. break;
  2861. case ICK_Complex_Promotion:
  2862. case ICK_Complex_Conversion: {
  2863. QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
  2864. QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
  2865. CastKind CK;
  2866. if (FromEl->isRealFloatingType()) {
  2867. if (ToEl->isRealFloatingType())
  2868. CK = CK_FloatingComplexCast;
  2869. else
  2870. CK = CK_FloatingComplexToIntegralComplex;
  2871. } else if (ToEl->isRealFloatingType()) {
  2872. CK = CK_IntegralComplexToFloatingComplex;
  2873. } else {
  2874. CK = CK_IntegralComplexCast;
  2875. }
  2876. From = ImpCastExprToType(From, ToType, CK,
  2877. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2878. break;
  2879. }
  2880. case ICK_Floating_Integral:
  2881. if (ToType->isRealFloatingType())
  2882. From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
  2883. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2884. else
  2885. From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
  2886. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2887. break;
  2888. case ICK_Compatible_Conversion:
  2889. From = ImpCastExprToType(From, ToType, CK_NoOp,
  2890. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2891. break;
  2892. case ICK_Writeback_Conversion:
  2893. case ICK_Pointer_Conversion: {
  2894. if (SCS.IncompatibleObjC && Action != AA_Casting) {
  2895. // Diagnose incompatible Objective-C conversions
  2896. if (Action == AA_Initializing || Action == AA_Assigning)
  2897. Diag(From->getLocStart(),
  2898. diag::ext_typecheck_convert_incompatible_pointer)
  2899. << ToType << From->getType() << Action
  2900. << From->getSourceRange() << 0;
  2901. else
  2902. Diag(From->getLocStart(),
  2903. diag::ext_typecheck_convert_incompatible_pointer)
  2904. << From->getType() << ToType << Action
  2905. << From->getSourceRange() << 0;
  2906. if (From->getType()->isObjCObjectPointerType() &&
  2907. ToType->isObjCObjectPointerType())
  2908. EmitRelatedResultTypeNote(From);
  2909. }
  2910. else if (getLangOpts().ObjCAutoRefCount &&
  2911. !CheckObjCARCUnavailableWeakConversion(ToType,
  2912. From->getType())) {
  2913. if (Action == AA_Initializing)
  2914. Diag(From->getLocStart(),
  2915. diag::err_arc_weak_unavailable_assign);
  2916. else
  2917. Diag(From->getLocStart(),
  2918. diag::err_arc_convesion_of_weak_unavailable)
  2919. << (Action == AA_Casting) << From->getType() << ToType
  2920. << From->getSourceRange();
  2921. }
  2922. CastKind Kind = CK_Invalid;
  2923. CXXCastPath BasePath;
  2924. if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
  2925. return ExprError();
  2926. // Make sure we extend blocks if necessary.
  2927. // FIXME: doing this here is really ugly.
  2928. if (Kind == CK_BlockPointerToObjCPointerCast) {
  2929. ExprResult E = From;
  2930. (void) PrepareCastToObjCObjectPointer(E);
  2931. From = E.get();
  2932. }
  2933. if (getLangOpts().ObjCAutoRefCount)
  2934. CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
  2935. From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
  2936. .get();
  2937. break;
  2938. }
  2939. case ICK_Pointer_Member: {
  2940. CastKind Kind = CK_Invalid;
  2941. CXXCastPath BasePath;
  2942. if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
  2943. return ExprError();
  2944. if (CheckExceptionSpecCompatibility(From, ToType))
  2945. return ExprError();
  2946. // We may not have been able to figure out what this member pointer resolved
  2947. // to up until this exact point. Attempt to lock-in it's inheritance model.
  2948. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2949. RequireCompleteType(From->getExprLoc(), From->getType(), 0);
  2950. RequireCompleteType(From->getExprLoc(), ToType, 0);
  2951. }
  2952. From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
  2953. .get();
  2954. break;
  2955. }
  2956. case ICK_Boolean_Conversion:
  2957. // Perform half-to-boolean conversion via float.
  2958. if (From->getType()->isHalfType()) {
  2959. From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
  2960. FromType = Context.FloatTy;
  2961. }
  2962. From = ImpCastExprToType(From, Context.BoolTy,
  2963. ScalarTypeToBooleanCastKind(FromType),
  2964. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2965. break;
  2966. case ICK_Derived_To_Base: {
  2967. CXXCastPath BasePath;
  2968. if (CheckDerivedToBaseConversion(From->getType(),
  2969. ToType.getNonReferenceType(),
  2970. From->getLocStart(),
  2971. From->getSourceRange(),
  2972. &BasePath,
  2973. CStyle))
  2974. return ExprError();
  2975. From = ImpCastExprToType(From, ToType.getNonReferenceType(),
  2976. CK_DerivedToBase, From->getValueKind(),
  2977. &BasePath, CCK).get();
  2978. break;
  2979. }
  2980. case ICK_Vector_Conversion:
  2981. From = ImpCastExprToType(From, ToType, CK_BitCast,
  2982. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2983. break;
  2984. case ICK_Vector_Splat:
  2985. // Vector splat from any arithmetic type to a vector.
  2986. // Cast to the element type.
  2987. {
  2988. QualType elType = ToType->getAs<ExtVectorType>()->getElementType();
  2989. if (elType != From->getType()) {
  2990. ExprResult E = From;
  2991. From = ImpCastExprToType(From, elType,
  2992. PrepareScalarCast(E, elType)).get();
  2993. }
  2994. From = ImpCastExprToType(From, ToType, CK_VectorSplat,
  2995. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2996. }
  2997. break;
  2998. case ICK_Complex_Real:
  2999. // Case 1. x -> _Complex y
  3000. if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
  3001. QualType ElType = ToComplex->getElementType();
  3002. bool isFloatingComplex = ElType->isRealFloatingType();
  3003. // x -> y
  3004. if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
  3005. // do nothing
  3006. } else if (From->getType()->isRealFloatingType()) {
  3007. From = ImpCastExprToType(From, ElType,
  3008. isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
  3009. } else {
  3010. assert(From->getType()->isIntegerType());
  3011. From = ImpCastExprToType(From, ElType,
  3012. isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
  3013. }
  3014. // y -> _Complex y
  3015. From = ImpCastExprToType(From, ToType,
  3016. isFloatingComplex ? CK_FloatingRealToComplex
  3017. : CK_IntegralRealToComplex).get();
  3018. // Case 2. _Complex x -> y
  3019. } else {
  3020. const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
  3021. assert(FromComplex);
  3022. QualType ElType = FromComplex->getElementType();
  3023. bool isFloatingComplex = ElType->isRealFloatingType();
  3024. // _Complex x -> x
  3025. From = ImpCastExprToType(From, ElType,
  3026. isFloatingComplex ? CK_FloatingComplexToReal
  3027. : CK_IntegralComplexToReal,
  3028. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3029. // x -> y
  3030. if (Context.hasSameUnqualifiedType(ElType, ToType)) {
  3031. // do nothing
  3032. } else if (ToType->isRealFloatingType()) {
  3033. From = ImpCastExprToType(From, ToType,
  3034. isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
  3035. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3036. } else {
  3037. assert(ToType->isIntegerType());
  3038. From = ImpCastExprToType(From, ToType,
  3039. isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
  3040. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3041. }
  3042. }
  3043. break;
  3044. case ICK_Block_Pointer_Conversion: {
  3045. From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
  3046. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3047. break;
  3048. }
  3049. // HLSL Change Starts
  3050. case ICK_Flat_Conversion:
  3051. case ICK_HLSL_Derived_To_Base:
  3052. case ICK_HLSLVector_Splat:
  3053. case ICK_HLSLVector_Scalar:
  3054. case ICK_HLSLVector_Truncation:
  3055. case ICK_HLSLVector_Conversion:
  3056. From = hlsl::PerformHLSLConversion(this, From, ToType.getUnqualifiedType(), SCS, CCK).get();
  3057. break;
  3058. // HLSL Change Ends
  3059. case ICK_TransparentUnionConversion: {
  3060. ExprResult FromRes = From;
  3061. Sema::AssignConvertType ConvTy =
  3062. CheckTransparentUnionArgumentConstraints(ToType, FromRes);
  3063. if (FromRes.isInvalid())
  3064. return ExprError();
  3065. From = FromRes.get();
  3066. assert ((ConvTy == Sema::Compatible) &&
  3067. "Improper transparent union conversion");
  3068. (void)ConvTy;
  3069. break;
  3070. }
  3071. case ICK_Zero_Event_Conversion:
  3072. From = ImpCastExprToType(From, ToType,
  3073. CK_ZeroToOCLEvent,
  3074. From->getValueKind()).get();
  3075. break;
  3076. case ICK_Lvalue_To_Rvalue:
  3077. case ICK_Array_To_Pointer:
  3078. case ICK_Function_To_Pointer:
  3079. case ICK_Qualification:
  3080. case ICK_Num_Conversion_Kinds:
  3081. llvm_unreachable("Improper second standard conversion");
  3082. }
  3083. switch (SCS.Third) {
  3084. case ICK_Identity:
  3085. // Nothing to do.
  3086. break;
  3087. case ICK_Qualification: {
  3088. // The qualification keeps the category of the inner expression, unless the
  3089. // target type isn't a reference.
  3090. ExprValueKind VK = ToType->isReferenceType() ?
  3091. From->getValueKind() : VK_RValue;
  3092. From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
  3093. CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
  3094. if (SCS.DeprecatedStringLiteralToCharPtr &&
  3095. !getLangOpts().WritableStrings) {
  3096. Diag(From->getLocStart(), getLangOpts().CPlusPlus11
  3097. ? diag::ext_deprecated_string_literal_conversion
  3098. : diag::warn_deprecated_string_literal_conversion)
  3099. << ToType.getNonReferenceType();
  3100. }
  3101. break;
  3102. }
  3103. default:
  3104. llvm_unreachable("Improper third standard conversion");
  3105. }
  3106. // If this conversion sequence involved a scalar -> atomic conversion, perform
  3107. // that conversion now.
  3108. if (!ToAtomicType.isNull()) {
  3109. assert(Context.hasSameType(
  3110. ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
  3111. From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
  3112. VK_RValue, nullptr, CCK).get();
  3113. }
  3114. return From;
  3115. }
  3116. /// \brief Check the completeness of a type in a unary type trait.
  3117. ///
  3118. /// If the particular type trait requires a complete type, tries to complete
  3119. /// it. If completing the type fails, a diagnostic is emitted and false
  3120. /// returned. If completing the type succeeds or no completion was required,
  3121. /// returns true.
  3122. static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
  3123. SourceLocation Loc,
  3124. QualType ArgTy) {
  3125. // C++0x [meta.unary.prop]p3:
  3126. // For all of the class templates X declared in this Clause, instantiating
  3127. // that template with a template argument that is a class template
  3128. // specialization may result in the implicit instantiation of the template
  3129. // argument if and only if the semantics of X require that the argument
  3130. // must be a complete type.
  3131. // We apply this rule to all the type trait expressions used to implement
  3132. // these class templates. We also try to follow any GCC documented behavior
  3133. // in these expressions to ensure portability of standard libraries.
  3134. switch (UTT) {
  3135. default: llvm_unreachable("not a UTT");
  3136. // is_complete_type somewhat obviously cannot require a complete type.
  3137. case UTT_IsCompleteType:
  3138. // Fall-through
  3139. // These traits are modeled on the type predicates in C++0x
  3140. // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
  3141. // requiring a complete type, as whether or not they return true cannot be
  3142. // impacted by the completeness of the type.
  3143. case UTT_IsVoid:
  3144. case UTT_IsIntegral:
  3145. case UTT_IsFloatingPoint:
  3146. case UTT_IsArray:
  3147. case UTT_IsPointer:
  3148. case UTT_IsLvalueReference:
  3149. case UTT_IsRvalueReference:
  3150. case UTT_IsMemberFunctionPointer:
  3151. case UTT_IsMemberObjectPointer:
  3152. case UTT_IsEnum:
  3153. case UTT_IsUnion:
  3154. case UTT_IsClass:
  3155. case UTT_IsFunction:
  3156. case UTT_IsReference:
  3157. case UTT_IsArithmetic:
  3158. case UTT_IsFundamental:
  3159. case UTT_IsObject:
  3160. case UTT_IsScalar:
  3161. case UTT_IsCompound:
  3162. case UTT_IsMemberPointer:
  3163. // Fall-through
  3164. // These traits are modeled on type predicates in C++0x [meta.unary.prop]
  3165. // which requires some of its traits to have the complete type. However,
  3166. // the completeness of the type cannot impact these traits' semantics, and
  3167. // so they don't require it. This matches the comments on these traits in
  3168. // Table 49.
  3169. case UTT_IsConst:
  3170. case UTT_IsVolatile:
  3171. case UTT_IsSigned:
  3172. case UTT_IsUnsigned:
  3173. return true;
  3174. // C++0x [meta.unary.prop] Table 49 requires the following traits to be
  3175. // applied to a complete type.
  3176. case UTT_IsTrivial:
  3177. case UTT_IsTriviallyCopyable:
  3178. case UTT_IsStandardLayout:
  3179. case UTT_IsPOD:
  3180. case UTT_IsLiteral:
  3181. case UTT_IsEmpty:
  3182. case UTT_IsPolymorphic:
  3183. case UTT_IsAbstract:
  3184. case UTT_IsInterfaceClass:
  3185. case UTT_IsDestructible:
  3186. case UTT_IsNothrowDestructible:
  3187. // Fall-through
  3188. // These traits require a complete type.
  3189. case UTT_IsFinal:
  3190. case UTT_IsSealed:
  3191. // These trait expressions are designed to help implement predicates in
  3192. // [meta.unary.prop] despite not being named the same. They are specified
  3193. // by both GCC and the Embarcadero C++ compiler, and require the complete
  3194. // type due to the overarching C++0x type predicates being implemented
  3195. // requiring the complete type.
  3196. case UTT_HasNothrowAssign:
  3197. case UTT_HasNothrowMoveAssign:
  3198. case UTT_HasNothrowConstructor:
  3199. case UTT_HasNothrowCopy:
  3200. case UTT_HasTrivialAssign:
  3201. case UTT_HasTrivialMoveAssign:
  3202. case UTT_HasTrivialDefaultConstructor:
  3203. case UTT_HasTrivialMoveConstructor:
  3204. case UTT_HasTrivialCopy:
  3205. case UTT_HasTrivialDestructor:
  3206. case UTT_HasVirtualDestructor:
  3207. // Arrays of unknown bound are expressly allowed.
  3208. QualType ElTy = ArgTy;
  3209. if (ArgTy->isIncompleteArrayType())
  3210. ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
  3211. // The void type is expressly allowed.
  3212. if (ElTy->isVoidType())
  3213. return true;
  3214. return !S.RequireCompleteType(
  3215. Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
  3216. }
  3217. }
  3218. static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
  3219. Sema &Self, SourceLocation KeyLoc, ASTContext &C,
  3220. bool (CXXRecordDecl::*HasTrivial)() const,
  3221. bool (CXXRecordDecl::*HasNonTrivial)() const,
  3222. bool (CXXMethodDecl::*IsDesiredOp)() const)
  3223. {
  3224. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  3225. if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
  3226. return true;
  3227. DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
  3228. DeclarationNameInfo NameInfo(Name, KeyLoc);
  3229. LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
  3230. if (Self.LookupQualifiedName(Res, RD)) {
  3231. bool FoundOperator = false;
  3232. Res.suppressDiagnostics();
  3233. for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
  3234. Op != OpEnd; ++Op) {
  3235. if (isa<FunctionTemplateDecl>(*Op))
  3236. continue;
  3237. CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
  3238. if((Operator->*IsDesiredOp)()) {
  3239. FoundOperator = true;
  3240. const FunctionProtoType *CPT =
  3241. Operator->getType()->getAs<FunctionProtoType>();
  3242. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  3243. if (!CPT || !CPT->isNothrow(C))
  3244. return false;
  3245. }
  3246. }
  3247. return FoundOperator;
  3248. }
  3249. return false;
  3250. }
  3251. static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
  3252. SourceLocation KeyLoc, QualType T) {
  3253. assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
  3254. ASTContext &C = Self.Context;
  3255. switch(UTT) {
  3256. default: llvm_unreachable("not a UTT");
  3257. // Type trait expressions corresponding to the primary type category
  3258. // predicates in C++0x [meta.unary.cat].
  3259. case UTT_IsVoid:
  3260. return T->isVoidType();
  3261. case UTT_IsIntegral:
  3262. return T->isIntegralType(C);
  3263. case UTT_IsFloatingPoint:
  3264. return T->isFloatingType();
  3265. case UTT_IsArray:
  3266. return T->isArrayType();
  3267. case UTT_IsPointer:
  3268. return T->isPointerType();
  3269. case UTT_IsLvalueReference:
  3270. return T->isLValueReferenceType();
  3271. case UTT_IsRvalueReference:
  3272. return T->isRValueReferenceType();
  3273. case UTT_IsMemberFunctionPointer:
  3274. return T->isMemberFunctionPointerType();
  3275. case UTT_IsMemberObjectPointer:
  3276. return T->isMemberDataPointerType();
  3277. case UTT_IsEnum:
  3278. return T->isEnumeralType();
  3279. case UTT_IsUnion:
  3280. return T->isUnionType();
  3281. case UTT_IsClass:
  3282. return T->isClassType() || T->isStructureType() || T->isInterfaceType();
  3283. case UTT_IsFunction:
  3284. return T->isFunctionType();
  3285. // Type trait expressions which correspond to the convenient composition
  3286. // predicates in C++0x [meta.unary.comp].
  3287. case UTT_IsReference:
  3288. return T->isReferenceType();
  3289. case UTT_IsArithmetic:
  3290. return T->isArithmeticType() && !T->isEnumeralType();
  3291. case UTT_IsFundamental:
  3292. return T->isFundamentalType();
  3293. case UTT_IsObject:
  3294. return T->isObjectType();
  3295. case UTT_IsScalar:
  3296. // Note: semantic analysis depends on Objective-C lifetime types to be
  3297. // considered scalar types. However, such types do not actually behave
  3298. // like scalar types at run time (since they may require retain/release
  3299. // operations), so we report them as non-scalar.
  3300. if (T->isObjCLifetimeType()) {
  3301. switch (T.getObjCLifetime()) {
  3302. case Qualifiers::OCL_None:
  3303. case Qualifiers::OCL_ExplicitNone:
  3304. return true;
  3305. case Qualifiers::OCL_Strong:
  3306. case Qualifiers::OCL_Weak:
  3307. case Qualifiers::OCL_Autoreleasing:
  3308. return false;
  3309. }
  3310. }
  3311. return T->isScalarType();
  3312. case UTT_IsCompound:
  3313. return T->isCompoundType();
  3314. case UTT_IsMemberPointer:
  3315. return T->isMemberPointerType();
  3316. // Type trait expressions which correspond to the type property predicates
  3317. // in C++0x [meta.unary.prop].
  3318. case UTT_IsConst:
  3319. return T.isConstQualified();
  3320. case UTT_IsVolatile:
  3321. return T.isVolatileQualified();
  3322. case UTT_IsTrivial:
  3323. return T.isTrivialType(Self.Context);
  3324. case UTT_IsTriviallyCopyable:
  3325. return T.isTriviallyCopyableType(Self.Context);
  3326. case UTT_IsStandardLayout:
  3327. return T->isStandardLayoutType();
  3328. case UTT_IsPOD:
  3329. return T.isPODType(Self.Context);
  3330. case UTT_IsLiteral:
  3331. return T->isLiteralType(Self.Context);
  3332. case UTT_IsEmpty:
  3333. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3334. return !RD->isUnion() && RD->isEmpty();
  3335. return false;
  3336. case UTT_IsPolymorphic:
  3337. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3338. return RD->isPolymorphic();
  3339. return false;
  3340. case UTT_IsAbstract:
  3341. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3342. return RD->isAbstract();
  3343. return false;
  3344. case UTT_IsInterfaceClass:
  3345. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3346. return RD->isInterface();
  3347. return false;
  3348. case UTT_IsFinal:
  3349. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3350. return RD->hasAttr<FinalAttr>();
  3351. return false;
  3352. case UTT_IsSealed:
  3353. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3354. if (FinalAttr *FA = RD->getAttr<FinalAttr>())
  3355. return FA->isSpelledAsSealed();
  3356. return false;
  3357. case UTT_IsSigned:
  3358. return T->isSignedIntegerType();
  3359. case UTT_IsUnsigned:
  3360. return T->isUnsignedIntegerType();
  3361. // Type trait expressions which query classes regarding their construction,
  3362. // destruction, and copying. Rather than being based directly on the
  3363. // related type predicates in the standard, they are specified by both
  3364. // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
  3365. // specifications.
  3366. //
  3367. // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
  3368. // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
  3369. //
  3370. // Note that these builtins do not behave as documented in g++: if a class
  3371. // has both a trivial and a non-trivial special member of a particular kind,
  3372. // they return false! For now, we emulate this behavior.
  3373. // FIXME: This appears to be a g++ bug: more complex cases reveal that it
  3374. // does not correctly compute triviality in the presence of multiple special
  3375. // members of the same kind. Revisit this once the g++ bug is fixed.
  3376. case UTT_HasTrivialDefaultConstructor:
  3377. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3378. // If __is_pod (type) is true then the trait is true, else if type is
  3379. // a cv class or union type (or array thereof) with a trivial default
  3380. // constructor ([class.ctor]) then the trait is true, else it is false.
  3381. if (T.isPODType(Self.Context))
  3382. return true;
  3383. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  3384. return RD->hasTrivialDefaultConstructor() &&
  3385. !RD->hasNonTrivialDefaultConstructor();
  3386. return false;
  3387. case UTT_HasTrivialMoveConstructor:
  3388. // This trait is implemented by MSVC 2012 and needed to parse the
  3389. // standard library headers. Specifically this is used as the logic
  3390. // behind std::is_trivially_move_constructible (20.9.4.3).
  3391. if (T.isPODType(Self.Context))
  3392. return true;
  3393. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  3394. return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
  3395. return false;
  3396. case UTT_HasTrivialCopy:
  3397. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3398. // If __is_pod (type) is true or type is a reference type then
  3399. // the trait is true, else if type is a cv class or union type
  3400. // with a trivial copy constructor ([class.copy]) then the trait
  3401. // is true, else it is false.
  3402. if (T.isPODType(Self.Context) || T->isReferenceType())
  3403. return true;
  3404. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3405. return RD->hasTrivialCopyConstructor() &&
  3406. !RD->hasNonTrivialCopyConstructor();
  3407. return false;
  3408. case UTT_HasTrivialMoveAssign:
  3409. // This trait is implemented by MSVC 2012 and needed to parse the
  3410. // standard library headers. Specifically it is used as the logic
  3411. // behind std::is_trivially_move_assignable (20.9.4.3)
  3412. if (T.isPODType(Self.Context))
  3413. return true;
  3414. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  3415. return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
  3416. return false;
  3417. case UTT_HasTrivialAssign:
  3418. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3419. // If type is const qualified or is a reference type then the
  3420. // trait is false. Otherwise if __is_pod (type) is true then the
  3421. // trait is true, else if type is a cv class or union type with
  3422. // a trivial copy assignment ([class.copy]) then the trait is
  3423. // true, else it is false.
  3424. // Note: the const and reference restrictions are interesting,
  3425. // given that const and reference members don't prevent a class
  3426. // from having a trivial copy assignment operator (but do cause
  3427. // errors if the copy assignment operator is actually used, q.v.
  3428. // [class.copy]p12).
  3429. if (T.isConstQualified())
  3430. return false;
  3431. if (T.isPODType(Self.Context))
  3432. return true;
  3433. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3434. return RD->hasTrivialCopyAssignment() &&
  3435. !RD->hasNonTrivialCopyAssignment();
  3436. return false;
  3437. case UTT_IsDestructible:
  3438. case UTT_IsNothrowDestructible:
  3439. // FIXME: Implement UTT_IsDestructible and UTT_IsNothrowDestructible.
  3440. // For now, let's fall through.
  3441. case UTT_HasTrivialDestructor:
  3442. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
  3443. // If __is_pod (type) is true or type is a reference type
  3444. // then the trait is true, else if type is a cv class or union
  3445. // type (or array thereof) with a trivial destructor
  3446. // ([class.dtor]) then the trait is true, else it is
  3447. // false.
  3448. if (T.isPODType(Self.Context) || T->isReferenceType())
  3449. return true;
  3450. // Objective-C++ ARC: autorelease types don't require destruction.
  3451. if (T->isObjCLifetimeType() &&
  3452. T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
  3453. return true;
  3454. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  3455. return RD->hasTrivialDestructor();
  3456. return false;
  3457. // TODO: Propagate nothrowness for implicitly declared special members.
  3458. case UTT_HasNothrowAssign:
  3459. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3460. // If type is const qualified or is a reference type then the
  3461. // trait is false. Otherwise if __has_trivial_assign (type)
  3462. // is true then the trait is true, else if type is a cv class
  3463. // or union type with copy assignment operators that are known
  3464. // not to throw an exception then the trait is true, else it is
  3465. // false.
  3466. if (C.getBaseElementType(T).isConstQualified())
  3467. return false;
  3468. if (T->isReferenceType())
  3469. return false;
  3470. if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
  3471. return true;
  3472. if (const RecordType *RT = T->getAs<RecordType>())
  3473. return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
  3474. &CXXRecordDecl::hasTrivialCopyAssignment,
  3475. &CXXRecordDecl::hasNonTrivialCopyAssignment,
  3476. &CXXMethodDecl::isCopyAssignmentOperator);
  3477. return false;
  3478. case UTT_HasNothrowMoveAssign:
  3479. // This trait is implemented by MSVC 2012 and needed to parse the
  3480. // standard library headers. Specifically this is used as the logic
  3481. // behind std::is_nothrow_move_assignable (20.9.4.3).
  3482. if (T.isPODType(Self.Context))
  3483. return true;
  3484. if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
  3485. return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
  3486. &CXXRecordDecl::hasTrivialMoveAssignment,
  3487. &CXXRecordDecl::hasNonTrivialMoveAssignment,
  3488. &CXXMethodDecl::isMoveAssignmentOperator);
  3489. return false;
  3490. case UTT_HasNothrowCopy:
  3491. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3492. // If __has_trivial_copy (type) is true then the trait is true, else
  3493. // if type is a cv class or union type with copy constructors that are
  3494. // known not to throw an exception then the trait is true, else it is
  3495. // false.
  3496. if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
  3497. return true;
  3498. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  3499. if (RD->hasTrivialCopyConstructor() &&
  3500. !RD->hasNonTrivialCopyConstructor())
  3501. return true;
  3502. bool FoundConstructor = false;
  3503. unsigned FoundTQs;
  3504. DeclContext::lookup_result R = Self.LookupConstructors(RD);
  3505. for (DeclContext::lookup_iterator Con = R.begin(),
  3506. ConEnd = R.end(); Con != ConEnd; ++Con) {
  3507. // A template constructor is never a copy constructor.
  3508. // FIXME: However, it may actually be selected at the actual overload
  3509. // resolution point.
  3510. if (isa<FunctionTemplateDecl>(*Con))
  3511. continue;
  3512. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
  3513. if (Constructor->isCopyConstructor(FoundTQs)) {
  3514. FoundConstructor = true;
  3515. const FunctionProtoType *CPT
  3516. = Constructor->getType()->getAs<FunctionProtoType>();
  3517. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  3518. if (!CPT)
  3519. return false;
  3520. // TODO: check whether evaluating default arguments can throw.
  3521. // For now, we'll be conservative and assume that they can throw.
  3522. if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 1)
  3523. return false;
  3524. }
  3525. }
  3526. return FoundConstructor;
  3527. }
  3528. return false;
  3529. case UTT_HasNothrowConstructor:
  3530. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
  3531. // If __has_trivial_constructor (type) is true then the trait is
  3532. // true, else if type is a cv class or union type (or array
  3533. // thereof) with a default constructor that is known not to
  3534. // throw an exception then the trait is true, else it is false.
  3535. if (T.isPODType(C) || T->isObjCLifetimeType())
  3536. return true;
  3537. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
  3538. if (RD->hasTrivialDefaultConstructor() &&
  3539. !RD->hasNonTrivialDefaultConstructor())
  3540. return true;
  3541. bool FoundConstructor = false;
  3542. DeclContext::lookup_result R = Self.LookupConstructors(RD);
  3543. for (DeclContext::lookup_iterator Con = R.begin(),
  3544. ConEnd = R.end(); Con != ConEnd; ++Con) {
  3545. // FIXME: In C++0x, a constructor template can be a default constructor.
  3546. if (isa<FunctionTemplateDecl>(*Con))
  3547. continue;
  3548. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
  3549. if (Constructor->isDefaultConstructor()) {
  3550. FoundConstructor = true;
  3551. const FunctionProtoType *CPT
  3552. = Constructor->getType()->getAs<FunctionProtoType>();
  3553. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  3554. if (!CPT)
  3555. return false;
  3556. // FIXME: check whether evaluating default arguments can throw.
  3557. // For now, we'll be conservative and assume that they can throw.
  3558. if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 0)
  3559. return false;
  3560. }
  3561. }
  3562. return FoundConstructor;
  3563. }
  3564. return false;
  3565. case UTT_HasVirtualDestructor:
  3566. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3567. // If type is a class type with a virtual destructor ([class.dtor])
  3568. // then the trait is true, else it is false.
  3569. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3570. if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
  3571. return Destructor->isVirtual();
  3572. return false;
  3573. // These type trait expressions are modeled on the specifications for the
  3574. // Embarcadero C++0x type trait functions:
  3575. // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
  3576. case UTT_IsCompleteType:
  3577. // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
  3578. // Returns True if and only if T is a complete type at the point of the
  3579. // function call.
  3580. return !T->isIncompleteType();
  3581. }
  3582. }
  3583. /// \brief Determine whether T has a non-trivial Objective-C lifetime in
  3584. /// ARC mode.
  3585. static bool hasNontrivialObjCLifetime(QualType T) {
  3586. switch (T.getObjCLifetime()) {
  3587. case Qualifiers::OCL_ExplicitNone:
  3588. return false;
  3589. case Qualifiers::OCL_Strong:
  3590. case Qualifiers::OCL_Weak:
  3591. case Qualifiers::OCL_Autoreleasing:
  3592. return true;
  3593. case Qualifiers::OCL_None:
  3594. return T->isObjCLifetimeType();
  3595. }
  3596. llvm_unreachable("Unknown ObjC lifetime qualifier");
  3597. }
  3598. static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
  3599. QualType RhsT, SourceLocation KeyLoc);
  3600. static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
  3601. ArrayRef<TypeSourceInfo *> Args,
  3602. SourceLocation RParenLoc) {
  3603. if (Kind <= UTT_Last)
  3604. return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
  3605. if (Kind <= BTT_Last)
  3606. return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
  3607. Args[1]->getType(), RParenLoc);
  3608. switch (Kind) {
  3609. case clang::TT_IsConstructible:
  3610. case clang::TT_IsNothrowConstructible:
  3611. case clang::TT_IsTriviallyConstructible: {
  3612. // C++11 [meta.unary.prop]:
  3613. // is_trivially_constructible is defined as:
  3614. //
  3615. // is_constructible<T, Args...>::value is true and the variable
  3616. // definition for is_constructible, as defined below, is known to call
  3617. // no operation that is not trivial.
  3618. //
  3619. // The predicate condition for a template specialization
  3620. // is_constructible<T, Args...> shall be satisfied if and only if the
  3621. // following variable definition would be well-formed for some invented
  3622. // variable t:
  3623. //
  3624. // T t(create<Args>()...);
  3625. assert(!Args.empty());
  3626. // Precondition: T and all types in the parameter pack Args shall be
  3627. // complete types, (possibly cv-qualified) void, or arrays of
  3628. // unknown bound.
  3629. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3630. QualType ArgTy = Args[I]->getType();
  3631. if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
  3632. continue;
  3633. if (S.RequireCompleteType(KWLoc, ArgTy,
  3634. diag::err_incomplete_type_used_in_type_trait_expr))
  3635. return false;
  3636. }
  3637. // Make sure the first argument is a complete type.
  3638. if (Args[0]->getType()->isIncompleteType())
  3639. return false;
  3640. // Make sure the first argument is not an abstract type.
  3641. CXXRecordDecl *RD = Args[0]->getType()->getAsCXXRecordDecl();
  3642. if (RD && RD->isAbstract())
  3643. return false;
  3644. SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
  3645. SmallVector<Expr *, 2> ArgExprs;
  3646. ArgExprs.reserve(Args.size() - 1);
  3647. for (unsigned I = 1, N = Args.size(); I != N; ++I) {
  3648. QualType T = Args[I]->getType();
  3649. if (T->isObjectType() || T->isFunctionType())
  3650. T = S.Context.getRValueReferenceType(T);
  3651. OpaqueArgExprs.push_back(
  3652. OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
  3653. T.getNonLValueExprType(S.Context),
  3654. Expr::getValueKindForType(T)));
  3655. }
  3656. for (Expr &E : OpaqueArgExprs)
  3657. ArgExprs.push_back(&E);
  3658. // Perform the initialization in an unevaluated context within a SFINAE
  3659. // trap at translation unit scope.
  3660. EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
  3661. Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
  3662. Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
  3663. InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
  3664. InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
  3665. RParenLoc));
  3666. InitializationSequence Init(S, To, InitKind, ArgExprs);
  3667. if (Init.Failed())
  3668. return false;
  3669. ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
  3670. if (Result.isInvalid() || SFINAE.hasErrorOccurred())
  3671. return false;
  3672. if (Kind == clang::TT_IsConstructible)
  3673. return true;
  3674. if (Kind == clang::TT_IsNothrowConstructible)
  3675. return S.canThrow(Result.get()) == CT_Cannot;
  3676. if (Kind == clang::TT_IsTriviallyConstructible) {
  3677. // Under Objective-C ARC, if the destination has non-trivial Objective-C
  3678. // lifetime, this is a non-trivial construction.
  3679. if (S.getLangOpts().ObjCAutoRefCount &&
  3680. hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
  3681. return false;
  3682. // The initialization succeeded; now make sure there are no non-trivial
  3683. // calls.
  3684. return !Result.get()->hasNonTrivialCall(S.Context);
  3685. }
  3686. llvm_unreachable("unhandled type trait");
  3687. return false;
  3688. }
  3689. default: llvm_unreachable("not a TT");
  3690. }
  3691. return false;
  3692. }
  3693. ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
  3694. ArrayRef<TypeSourceInfo *> Args,
  3695. SourceLocation RParenLoc) {
  3696. QualType ResultType = Context.getLogicalOperationType();
  3697. if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
  3698. *this, Kind, KWLoc, Args[0]->getType()))
  3699. return ExprError();
  3700. bool Dependent = false;
  3701. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3702. if (Args[I]->getType()->isDependentType()) {
  3703. Dependent = true;
  3704. break;
  3705. }
  3706. }
  3707. bool Result = false;
  3708. if (!Dependent)
  3709. Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
  3710. return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
  3711. RParenLoc, Result);
  3712. }
  3713. ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
  3714. ArrayRef<ParsedType> Args,
  3715. SourceLocation RParenLoc) {
  3716. SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
  3717. ConvertedArgs.reserve(Args.size());
  3718. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3719. TypeSourceInfo *TInfo;
  3720. QualType T = GetTypeFromParser(Args[I], &TInfo);
  3721. if (!TInfo)
  3722. TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
  3723. ConvertedArgs.push_back(TInfo);
  3724. }
  3725. return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
  3726. }
  3727. static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
  3728. QualType RhsT, SourceLocation KeyLoc) {
  3729. assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
  3730. "Cannot evaluate traits of dependent types");
  3731. switch(BTT) {
  3732. case BTT_IsBaseOf: {
  3733. // C++0x [meta.rel]p2
  3734. // Base is a base class of Derived without regard to cv-qualifiers or
  3735. // Base and Derived are not unions and name the same class type without
  3736. // regard to cv-qualifiers.
  3737. const RecordType *lhsRecord = LhsT->getAs<RecordType>();
  3738. if (!lhsRecord) return false;
  3739. const RecordType *rhsRecord = RhsT->getAs<RecordType>();
  3740. if (!rhsRecord) return false;
  3741. assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
  3742. == (lhsRecord == rhsRecord));
  3743. if (lhsRecord == rhsRecord)
  3744. return !lhsRecord->getDecl()->isUnion();
  3745. // C++0x [meta.rel]p2:
  3746. // If Base and Derived are class types and are different types
  3747. // (ignoring possible cv-qualifiers) then Derived shall be a
  3748. // complete type.
  3749. if (Self.RequireCompleteType(KeyLoc, RhsT,
  3750. diag::err_incomplete_type_used_in_type_trait_expr))
  3751. return false;
  3752. return cast<CXXRecordDecl>(rhsRecord->getDecl())
  3753. ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
  3754. }
  3755. case BTT_IsSame:
  3756. return Self.Context.hasSameType(LhsT, RhsT);
  3757. case BTT_TypeCompatible:
  3758. return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
  3759. RhsT.getUnqualifiedType());
  3760. case BTT_IsConvertible:
  3761. case BTT_IsConvertibleTo: {
  3762. // C++0x [meta.rel]p4:
  3763. // Given the following function prototype:
  3764. //
  3765. // template <class T>
  3766. // typename add_rvalue_reference<T>::type create();
  3767. //
  3768. // the predicate condition for a template specialization
  3769. // is_convertible<From, To> shall be satisfied if and only if
  3770. // the return expression in the following code would be
  3771. // well-formed, including any implicit conversions to the return
  3772. // type of the function:
  3773. //
  3774. // To test() {
  3775. // return create<From>();
  3776. // }
  3777. //
  3778. // Access checking is performed as if in a context unrelated to To and
  3779. // From. Only the validity of the immediate context of the expression
  3780. // of the return-statement (including conversions to the return type)
  3781. // is considered.
  3782. //
  3783. // We model the initialization as a copy-initialization of a temporary
  3784. // of the appropriate type, which for this expression is identical to the
  3785. // return statement (since NRVO doesn't apply).
  3786. // Functions aren't allowed to return function or array types.
  3787. if (RhsT->isFunctionType() || RhsT->isArrayType())
  3788. return false;
  3789. // A return statement in a void function must have void type.
  3790. if (RhsT->isVoidType())
  3791. return LhsT->isVoidType();
  3792. // A function definition requires a complete, non-abstract return type.
  3793. if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
  3794. Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
  3795. return false;
  3796. // Compute the result of add_rvalue_reference.
  3797. if (LhsT->isObjectType() || LhsT->isFunctionType())
  3798. LhsT = Self.Context.getRValueReferenceType(LhsT);
  3799. // Build a fake source and destination for initialization.
  3800. InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
  3801. OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
  3802. Expr::getValueKindForType(LhsT));
  3803. Expr *FromPtr = &From;
  3804. InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
  3805. SourceLocation()));
  3806. // Perform the initialization in an unevaluated context within a SFINAE
  3807. // trap at translation unit scope.
  3808. EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
  3809. Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
  3810. Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
  3811. InitializationSequence Init(Self, To, Kind, FromPtr);
  3812. if (Init.Failed())
  3813. return false;
  3814. ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
  3815. return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
  3816. }
  3817. case BTT_IsNothrowAssignable:
  3818. case BTT_IsTriviallyAssignable: {
  3819. // C++11 [meta.unary.prop]p3:
  3820. // is_trivially_assignable is defined as:
  3821. // is_assignable<T, U>::value is true and the assignment, as defined by
  3822. // is_assignable, is known to call no operation that is not trivial
  3823. //
  3824. // is_assignable is defined as:
  3825. // The expression declval<T>() = declval<U>() is well-formed when
  3826. // treated as an unevaluated operand (Clause 5).
  3827. //
  3828. // For both, T and U shall be complete types, (possibly cv-qualified)
  3829. // void, or arrays of unknown bound.
  3830. if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
  3831. Self.RequireCompleteType(KeyLoc, LhsT,
  3832. diag::err_incomplete_type_used_in_type_trait_expr))
  3833. return false;
  3834. if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
  3835. Self.RequireCompleteType(KeyLoc, RhsT,
  3836. diag::err_incomplete_type_used_in_type_trait_expr))
  3837. return false;
  3838. // cv void is never assignable.
  3839. if (LhsT->isVoidType() || RhsT->isVoidType())
  3840. return false;
  3841. // Build expressions that emulate the effect of declval<T>() and
  3842. // declval<U>().
  3843. if (LhsT->isObjectType() || LhsT->isFunctionType())
  3844. LhsT = Self.Context.getRValueReferenceType(LhsT);
  3845. if (RhsT->isObjectType() || RhsT->isFunctionType())
  3846. RhsT = Self.Context.getRValueReferenceType(RhsT);
  3847. OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
  3848. Expr::getValueKindForType(LhsT));
  3849. OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
  3850. Expr::getValueKindForType(RhsT));
  3851. // Attempt the assignment in an unevaluated context within a SFINAE
  3852. // trap at translation unit scope.
  3853. EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
  3854. Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
  3855. Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
  3856. ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
  3857. &Rhs);
  3858. if (Result.isInvalid() || SFINAE.hasErrorOccurred())
  3859. return false;
  3860. if (BTT == BTT_IsNothrowAssignable)
  3861. return Self.canThrow(Result.get()) == CT_Cannot;
  3862. if (BTT == BTT_IsTriviallyAssignable) {
  3863. // Under Objective-C ARC, if the destination has non-trivial Objective-C
  3864. // lifetime, this is a non-trivial assignment.
  3865. if (Self.getLangOpts().ObjCAutoRefCount &&
  3866. hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
  3867. return false;
  3868. return !Result.get()->hasNonTrivialCall(Self.Context);
  3869. }
  3870. llvm_unreachable("unhandled type trait");
  3871. return false;
  3872. }
  3873. default: llvm_unreachable("not a BTT");
  3874. }
  3875. llvm_unreachable("Unknown type trait or not implemented");
  3876. }
  3877. ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
  3878. SourceLocation KWLoc,
  3879. ParsedType Ty,
  3880. Expr* DimExpr,
  3881. SourceLocation RParen) {
  3882. TypeSourceInfo *TSInfo;
  3883. QualType T = GetTypeFromParser(Ty, &TSInfo);
  3884. if (!TSInfo)
  3885. TSInfo = Context.getTrivialTypeSourceInfo(T);
  3886. return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
  3887. }
  3888. static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
  3889. QualType T, Expr *DimExpr,
  3890. SourceLocation KeyLoc) {
  3891. assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
  3892. switch(ATT) {
  3893. case ATT_ArrayRank:
  3894. if (T->isArrayType()) {
  3895. unsigned Dim = 0;
  3896. while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
  3897. ++Dim;
  3898. T = AT->getElementType();
  3899. }
  3900. return Dim;
  3901. }
  3902. return 0;
  3903. case ATT_ArrayExtent: {
  3904. llvm::APSInt Value;
  3905. uint64_t Dim;
  3906. if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
  3907. diag::err_dimension_expr_not_constant_integer,
  3908. false).isInvalid())
  3909. return 0;
  3910. if (Value.isSigned() && Value.isNegative()) {
  3911. Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
  3912. << DimExpr->getSourceRange();
  3913. return 0;
  3914. }
  3915. Dim = Value.getLimitedValue();
  3916. if (T->isArrayType()) {
  3917. unsigned D = 0;
  3918. bool Matched = false;
  3919. while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
  3920. if (Dim == D) {
  3921. Matched = true;
  3922. break;
  3923. }
  3924. ++D;
  3925. T = AT->getElementType();
  3926. }
  3927. if (Matched && T->isArrayType()) {
  3928. if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
  3929. return CAT->getSize().getLimitedValue();
  3930. }
  3931. }
  3932. return 0;
  3933. }
  3934. }
  3935. llvm_unreachable("Unknown type trait or not implemented");
  3936. }
  3937. ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
  3938. SourceLocation KWLoc,
  3939. TypeSourceInfo *TSInfo,
  3940. Expr* DimExpr,
  3941. SourceLocation RParen) {
  3942. QualType T = TSInfo->getType();
  3943. // FIXME: This should likely be tracked as an APInt to remove any host
  3944. // assumptions about the width of size_t on the target.
  3945. uint64_t Value = 0;
  3946. if (!T->isDependentType())
  3947. Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
  3948. // While the specification for these traits from the Embarcadero C++
  3949. // compiler's documentation says the return type is 'unsigned int', Clang
  3950. // returns 'size_t'. On Windows, the primary platform for the Embarcadero
  3951. // compiler, there is no difference. On several other platforms this is an
  3952. // important distinction.
  3953. return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
  3954. RParen, Context.getSizeType());
  3955. }
  3956. ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
  3957. SourceLocation KWLoc,
  3958. Expr *Queried,
  3959. SourceLocation RParen) {
  3960. // If error parsing the expression, ignore.
  3961. if (!Queried)
  3962. return ExprError();
  3963. ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
  3964. return Result;
  3965. }
  3966. static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
  3967. switch (ET) {
  3968. case ET_IsLValueExpr: return E->isLValue();
  3969. case ET_IsRValueExpr: return E->isRValue();
  3970. }
  3971. llvm_unreachable("Expression trait not covered by switch");
  3972. }
  3973. ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
  3974. SourceLocation KWLoc,
  3975. Expr *Queried,
  3976. SourceLocation RParen) {
  3977. if (Queried->isTypeDependent()) {
  3978. // Delay type-checking for type-dependent expressions.
  3979. } else if (Queried->getType()->isPlaceholderType()) {
  3980. ExprResult PE = CheckPlaceholderExpr(Queried);
  3981. if (PE.isInvalid()) return ExprError();
  3982. return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
  3983. }
  3984. bool Value = EvaluateExpressionTrait(ET, Queried);
  3985. return new (Context)
  3986. ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
  3987. }
  3988. QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
  3989. ExprValueKind &VK,
  3990. SourceLocation Loc,
  3991. bool isIndirect) {
  3992. assert(!LHS.get()->getType()->isPlaceholderType() &&
  3993. !RHS.get()->getType()->isPlaceholderType() &&
  3994. "placeholders should have been weeded out by now");
  3995. // The LHS undergoes lvalue conversions if this is ->*.
  3996. if (isIndirect) {
  3997. LHS = DefaultLvalueConversion(LHS.get());
  3998. if (LHS.isInvalid()) return QualType();
  3999. }
  4000. // The RHS always undergoes lvalue conversions.
  4001. RHS = DefaultLvalueConversion(RHS.get());
  4002. if (RHS.isInvalid()) return QualType();
  4003. const char *OpSpelling = isIndirect ? "->*" : ".*";
  4004. // C++ 5.5p2
  4005. // The binary operator .* [p3: ->*] binds its second operand, which shall
  4006. // be of type "pointer to member of T" (where T is a completely-defined
  4007. // class type) [...]
  4008. QualType RHSType = RHS.get()->getType();
  4009. const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
  4010. if (!MemPtr) {
  4011. Diag(Loc, diag::err_bad_memptr_rhs)
  4012. << OpSpelling << RHSType << RHS.get()->getSourceRange();
  4013. return QualType();
  4014. }
  4015. QualType Class(MemPtr->getClass(), 0);
  4016. // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
  4017. // member pointer points must be completely-defined. However, there is no
  4018. // reason for this semantic distinction, and the rule is not enforced by
  4019. // other compilers. Therefore, we do not check this property, as it is
  4020. // likely to be considered a defect.
  4021. // C++ 5.5p2
  4022. // [...] to its first operand, which shall be of class T or of a class of
  4023. // which T is an unambiguous and accessible base class. [p3: a pointer to
  4024. // such a class]
  4025. QualType LHSType = LHS.get()->getType();
  4026. if (isIndirect) {
  4027. if (const PointerType *Ptr = LHSType->getAs<PointerType>())
  4028. LHSType = Ptr->getPointeeType();
  4029. else {
  4030. Diag(Loc, diag::err_bad_memptr_lhs)
  4031. << OpSpelling << 1 << LHSType
  4032. << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
  4033. return QualType();
  4034. }
  4035. }
  4036. if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
  4037. // If we want to check the hierarchy, we need a complete type.
  4038. if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
  4039. OpSpelling, (int)isIndirect)) {
  4040. return QualType();
  4041. }
  4042. if (!IsDerivedFrom(LHSType, Class)) {
  4043. Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
  4044. << (int)isIndirect << LHS.get()->getType();
  4045. return QualType();
  4046. }
  4047. CXXCastPath BasePath;
  4048. if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
  4049. SourceRange(LHS.get()->getLocStart(),
  4050. RHS.get()->getLocEnd()),
  4051. &BasePath))
  4052. return QualType();
  4053. // Cast LHS to type of use.
  4054. QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
  4055. ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
  4056. LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
  4057. &BasePath);
  4058. }
  4059. if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
  4060. // Diagnose use of pointer-to-member type which when used as
  4061. // the functional cast in a pointer-to-member expression.
  4062. Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
  4063. return QualType();
  4064. }
  4065. // C++ 5.5p2
  4066. // The result is an object or a function of the type specified by the
  4067. // second operand.
  4068. // The cv qualifiers are the union of those in the pointer and the left side,
  4069. // in accordance with 5.5p5 and 5.2.5.
  4070. QualType Result = MemPtr->getPointeeType();
  4071. Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
  4072. // C++0x [expr.mptr.oper]p6:
  4073. // In a .* expression whose object expression is an rvalue, the program is
  4074. // ill-formed if the second operand is a pointer to member function with
  4075. // ref-qualifier &. In a ->* expression or in a .* expression whose object
  4076. // expression is an lvalue, the program is ill-formed if the second operand
  4077. // is a pointer to member function with ref-qualifier &&.
  4078. if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
  4079. switch (Proto->getRefQualifier()) {
  4080. case RQ_None:
  4081. // Do nothing
  4082. break;
  4083. case RQ_LValue:
  4084. if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
  4085. Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
  4086. << RHSType << 1 << LHS.get()->getSourceRange();
  4087. break;
  4088. case RQ_RValue:
  4089. if (isIndirect || !LHS.get()->Classify(Context).isRValue())
  4090. Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
  4091. << RHSType << 0 << LHS.get()->getSourceRange();
  4092. break;
  4093. }
  4094. }
  4095. // C++ [expr.mptr.oper]p6:
  4096. // The result of a .* expression whose second operand is a pointer
  4097. // to a data member is of the same value category as its
  4098. // first operand. The result of a .* expression whose second
  4099. // operand is a pointer to a member function is a prvalue. The
  4100. // result of an ->* expression is an lvalue if its second operand
  4101. // is a pointer to data member and a prvalue otherwise.
  4102. if (Result->isFunctionType()) {
  4103. VK = VK_RValue;
  4104. return Context.BoundMemberTy;
  4105. } else if (isIndirect) {
  4106. VK = VK_LValue;
  4107. } else {
  4108. VK = LHS.get()->getValueKind();
  4109. }
  4110. return Result;
  4111. }
  4112. /// \brief Try to convert a type to another according to C++0x 5.16p3.
  4113. ///
  4114. /// This is part of the parameter validation for the ? operator. If either
  4115. /// value operand is a class type, the two operands are attempted to be
  4116. /// converted to each other. This function does the conversion in one direction.
  4117. /// It returns true if the program is ill-formed and has already been diagnosed
  4118. /// as such.
  4119. static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
  4120. SourceLocation QuestionLoc,
  4121. bool &HaveConversion,
  4122. QualType &ToType) {
  4123. HaveConversion = false;
  4124. ToType = To->getType();
  4125. InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
  4126. SourceLocation());
  4127. // C++0x 5.16p3
  4128. // The process for determining whether an operand expression E1 of type T1
  4129. // can be converted to match an operand expression E2 of type T2 is defined
  4130. // as follows:
  4131. // -- If E2 is an lvalue:
  4132. bool ToIsLvalue = To->isLValue();
  4133. if (ToIsLvalue) {
  4134. // E1 can be converted to match E2 if E1 can be implicitly converted to
  4135. // type "lvalue reference to T2", subject to the constraint that in the
  4136. // conversion the reference must bind directly to E1.
  4137. QualType T = Self.Context.getLValueReferenceType(ToType);
  4138. InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
  4139. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4140. if (InitSeq.isDirectReferenceBinding()) {
  4141. ToType = T;
  4142. HaveConversion = true;
  4143. return false;
  4144. }
  4145. if (InitSeq.isAmbiguous())
  4146. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4147. }
  4148. // -- If E2 is an rvalue, or if the conversion above cannot be done:
  4149. // -- if E1 and E2 have class type, and the underlying class types are
  4150. // the same or one is a base class of the other:
  4151. QualType FTy = From->getType();
  4152. QualType TTy = To->getType();
  4153. const RecordType *FRec = FTy->getAs<RecordType>();
  4154. const RecordType *TRec = TTy->getAs<RecordType>();
  4155. bool FDerivedFromT = FRec && TRec && FRec != TRec &&
  4156. Self.IsDerivedFrom(FTy, TTy);
  4157. if (FRec && TRec &&
  4158. (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
  4159. // E1 can be converted to match E2 if the class of T2 is the
  4160. // same type as, or a base class of, the class of T1, and
  4161. // [cv2 > cv1].
  4162. if (FRec == TRec || FDerivedFromT) {
  4163. if (TTy.isAtLeastAsQualifiedAs(FTy)) {
  4164. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
  4165. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4166. if (InitSeq) {
  4167. HaveConversion = true;
  4168. return false;
  4169. }
  4170. if (InitSeq.isAmbiguous())
  4171. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4172. }
  4173. }
  4174. return false;
  4175. }
  4176. // -- Otherwise: E1 can be converted to match E2 if E1 can be
  4177. // implicitly converted to the type that expression E2 would have
  4178. // if E2 were converted to an rvalue (or the type it has, if E2 is
  4179. // an rvalue).
  4180. //
  4181. // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
  4182. // to the array-to-pointer or function-to-pointer conversions.
  4183. if (!TTy->getAs<TagType>())
  4184. TTy = TTy.getUnqualifiedType();
  4185. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
  4186. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4187. HaveConversion = !InitSeq.Failed();
  4188. ToType = TTy;
  4189. if (InitSeq.isAmbiguous())
  4190. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4191. return false;
  4192. }
  4193. /// \brief Try to find a common type for two according to C++0x 5.16p5.
  4194. ///
  4195. /// This is part of the parameter validation for the ? operator. If either
  4196. /// value operand is a class type, overload resolution is used to find a
  4197. /// conversion to a common type.
  4198. static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
  4199. SourceLocation QuestionLoc) {
  4200. Expr *Args[2] = { LHS.get(), RHS.get() };
  4201. OverloadCandidateSet CandidateSet(QuestionLoc,
  4202. OverloadCandidateSet::CSK_Operator);
  4203. Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
  4204. CandidateSet);
  4205. OverloadCandidateSet::iterator Best;
  4206. switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
  4207. case OR_Success: {
  4208. // We found a match. Perform the conversions on the arguments and move on.
  4209. ExprResult LHSRes =
  4210. Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
  4211. Best->Conversions[0], Sema::AA_Converting);
  4212. if (LHSRes.isInvalid())
  4213. break;
  4214. LHS = LHSRes;
  4215. ExprResult RHSRes =
  4216. Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
  4217. Best->Conversions[1], Sema::AA_Converting);
  4218. if (RHSRes.isInvalid())
  4219. break;
  4220. RHS = RHSRes;
  4221. if (Best->Function)
  4222. Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
  4223. return false;
  4224. }
  4225. case OR_No_Viable_Function:
  4226. // Emit a better diagnostic if one of the expressions is a null pointer
  4227. // constant and the other is a pointer type. In this case, the user most
  4228. // likely forgot to take the address of the other expression.
  4229. if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  4230. return true;
  4231. Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  4232. << LHS.get()->getType() << RHS.get()->getType()
  4233. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4234. return true;
  4235. case OR_Ambiguous:
  4236. Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
  4237. << LHS.get()->getType() << RHS.get()->getType()
  4238. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4239. // FIXME: Print the possible common types by printing the return types of
  4240. // the viable candidates.
  4241. break;
  4242. case OR_Deleted:
  4243. llvm_unreachable("Conditional operator has only built-in overloads");
  4244. }
  4245. return true;
  4246. }
  4247. /// \brief Perform an "extended" implicit conversion as returned by
  4248. /// TryClassUnification.
  4249. static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
  4250. InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
  4251. InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
  4252. SourceLocation());
  4253. Expr *Arg = E.get();
  4254. InitializationSequence InitSeq(Self, Entity, Kind, Arg);
  4255. ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
  4256. if (Result.isInvalid())
  4257. return true;
  4258. E = Result;
  4259. return false;
  4260. }
  4261. /// \brief Check the operands of ?: under C++ semantics.
  4262. ///
  4263. /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
  4264. /// extension. In this case, LHS == Cond. (But they're not aliases.)
  4265. QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  4266. ExprResult &RHS, ExprValueKind &VK,
  4267. ExprObjectKind &OK,
  4268. SourceLocation QuestionLoc) {
  4269. // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
  4270. // interface pointers.
  4271. // C++11 [expr.cond]p1
  4272. // The first expression is contextually converted to bool.
  4273. if (!Cond.get()->isTypeDependent()) {
  4274. ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
  4275. if (CondRes.isInvalid())
  4276. return QualType();
  4277. Cond = CondRes;
  4278. }
  4279. // Assume r-value.
  4280. VK = VK_RValue;
  4281. OK = OK_Ordinary;
  4282. // Either of the arguments dependent?
  4283. if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
  4284. return Context.DependentTy;
  4285. // C++11 [expr.cond]p2
  4286. // If either the second or the third operand has type (cv) void, ...
  4287. QualType LTy = LHS.get()->getType();
  4288. QualType RTy = RHS.get()->getType();
  4289. bool LVoid = LTy->isVoidType();
  4290. bool RVoid = RTy->isVoidType();
  4291. if (LVoid || RVoid) {
  4292. // ... one of the following shall hold:
  4293. // -- The second or the third operand (but not both) is a (possibly
  4294. // parenthesized) throw-expression; the result is of the type
  4295. // and value category of the other.
  4296. bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
  4297. bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
  4298. if (LThrow != RThrow) {
  4299. Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
  4300. VK = NonThrow->getValueKind();
  4301. // DR (no number yet): the result is a bit-field if the
  4302. // non-throw-expression operand is a bit-field.
  4303. OK = NonThrow->getObjectKind();
  4304. return NonThrow->getType();
  4305. }
  4306. // -- Both the second and third operands have type void; the result is of
  4307. // type void and is a prvalue.
  4308. if (LVoid && RVoid)
  4309. return Context.VoidTy;
  4310. // Neither holds, error.
  4311. Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
  4312. << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
  4313. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4314. return QualType();
  4315. }
  4316. // Neither is void.
  4317. // C++11 [expr.cond]p3
  4318. // Otherwise, if the second and third operand have different types, and
  4319. // either has (cv) class type [...] an attempt is made to convert each of
  4320. // those operands to the type of the other.
  4321. if (!Context.hasSameType(LTy, RTy) &&
  4322. (LTy->isRecordType() || RTy->isRecordType())) {
  4323. // These return true if a single direction is already ambiguous.
  4324. QualType L2RType, R2LType;
  4325. bool HaveL2R, HaveR2L;
  4326. if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
  4327. return QualType();
  4328. if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
  4329. return QualType();
  4330. // If both can be converted, [...] the program is ill-formed.
  4331. if (HaveL2R && HaveR2L) {
  4332. Diag(QuestionLoc, diag::err_conditional_ambiguous)
  4333. << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4334. return QualType();
  4335. }
  4336. // If exactly one conversion is possible, that conversion is applied to
  4337. // the chosen operand and the converted operands are used in place of the
  4338. // original operands for the remainder of this section.
  4339. if (HaveL2R) {
  4340. if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
  4341. return QualType();
  4342. LTy = LHS.get()->getType();
  4343. } else if (HaveR2L) {
  4344. if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
  4345. return QualType();
  4346. RTy = RHS.get()->getType();
  4347. }
  4348. }
  4349. // C++11 [expr.cond]p3
  4350. // if both are glvalues of the same value category and the same type except
  4351. // for cv-qualification, an attempt is made to convert each of those
  4352. // operands to the type of the other.
  4353. ExprValueKind LVK = LHS.get()->getValueKind();
  4354. ExprValueKind RVK = RHS.get()->getValueKind();
  4355. if (!Context.hasSameType(LTy, RTy) &&
  4356. Context.hasSameUnqualifiedType(LTy, RTy) &&
  4357. LVK == RVK && LVK != VK_RValue) {
  4358. // Since the unqualified types are reference-related and we require the
  4359. // result to be as if a reference bound directly, the only conversion
  4360. // we can perform is to add cv-qualifiers.
  4361. Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
  4362. Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
  4363. if (RCVR.isStrictSupersetOf(LCVR)) {
  4364. LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
  4365. LTy = LHS.get()->getType();
  4366. }
  4367. else if (LCVR.isStrictSupersetOf(RCVR)) {
  4368. RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
  4369. RTy = RHS.get()->getType();
  4370. }
  4371. }
  4372. // C++11 [expr.cond]p4
  4373. // If the second and third operands are glvalues of the same value
  4374. // category and have the same type, the result is of that type and
  4375. // value category and it is a bit-field if the second or the third
  4376. // operand is a bit-field, or if both are bit-fields.
  4377. // We only extend this to bitfields, not to the crazy other kinds of
  4378. // l-values.
  4379. bool Same = Context.hasSameType(LTy, RTy);
  4380. if (Same && LVK == RVK && LVK != VK_RValue &&
  4381. LHS.get()->isOrdinaryOrBitFieldObject() &&
  4382. RHS.get()->isOrdinaryOrBitFieldObject()) {
  4383. VK = LHS.get()->getValueKind();
  4384. if (LHS.get()->getObjectKind() == OK_BitField ||
  4385. RHS.get()->getObjectKind() == OK_BitField)
  4386. OK = OK_BitField;
  4387. return LTy;
  4388. }
  4389. // C++11 [expr.cond]p5
  4390. // Otherwise, the result is a prvalue. If the second and third operands
  4391. // do not have the same type, and either has (cv) class type, ...
  4392. if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
  4393. // ... overload resolution is used to determine the conversions (if any)
  4394. // to be applied to the operands. If the overload resolution fails, the
  4395. // program is ill-formed.
  4396. if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
  4397. return QualType();
  4398. }
  4399. // C++11 [expr.cond]p6
  4400. // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
  4401. // conversions are performed on the second and third operands.
  4402. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  4403. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  4404. if (LHS.isInvalid() || RHS.isInvalid())
  4405. return QualType();
  4406. LTy = LHS.get()->getType();
  4407. RTy = RHS.get()->getType();
  4408. // After those conversions, one of the following shall hold:
  4409. // -- The second and third operands have the same type; the result
  4410. // is of that type. If the operands have class type, the result
  4411. // is a prvalue temporary of the result type, which is
  4412. // copy-initialized from either the second operand or the third
  4413. // operand depending on the value of the first operand.
  4414. if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
  4415. if (LTy->isRecordType()) {
  4416. // The operands have class type. Make a temporary copy.
  4417. if (RequireNonAbstractType(QuestionLoc, LTy,
  4418. diag::err_allocation_of_abstract_type))
  4419. return QualType();
  4420. InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
  4421. ExprResult LHSCopy = PerformCopyInitialization(Entity,
  4422. SourceLocation(),
  4423. LHS);
  4424. if (LHSCopy.isInvalid())
  4425. return QualType();
  4426. ExprResult RHSCopy = PerformCopyInitialization(Entity,
  4427. SourceLocation(),
  4428. RHS);
  4429. if (RHSCopy.isInvalid())
  4430. return QualType();
  4431. LHS = LHSCopy;
  4432. RHS = RHSCopy;
  4433. }
  4434. return LTy;
  4435. }
  4436. // Extension: conditional operator involving vector types.
  4437. if (LTy->isVectorType() || RTy->isVectorType())
  4438. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  4439. /*AllowBothBool*/true,
  4440. /*AllowBoolConversions*/false);
  4441. // -- The second and third operands have arithmetic or enumeration type;
  4442. // the usual arithmetic conversions are performed to bring them to a
  4443. // common type, and the result is of that type.
  4444. if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
  4445. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  4446. if (LHS.isInvalid() || RHS.isInvalid())
  4447. return QualType();
  4448. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  4449. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  4450. return ResTy;
  4451. }
  4452. // -- The second and third operands have pointer type, or one has pointer
  4453. // type and the other is a null pointer constant, or both are null
  4454. // pointer constants, at least one of which is non-integral; pointer
  4455. // conversions and qualification conversions are performed to bring them
  4456. // to their composite pointer type. The result is of the composite
  4457. // pointer type.
  4458. // -- The second and third operands have pointer to member type, or one has
  4459. // pointer to member type and the other is a null pointer constant;
  4460. // pointer to member conversions and qualification conversions are
  4461. // performed to bring them to a common type, whose cv-qualification
  4462. // shall match the cv-qualification of either the second or the third
  4463. // operand. The result is of the common type.
  4464. bool NonStandardCompositeType = false;
  4465. QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
  4466. isSFINAEContext() ? nullptr
  4467. : &NonStandardCompositeType);
  4468. if (!Composite.isNull()) {
  4469. if (NonStandardCompositeType)
  4470. Diag(QuestionLoc,
  4471. diag::ext_typecheck_cond_incompatible_operands_nonstandard)
  4472. << LTy << RTy << Composite
  4473. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4474. return Composite;
  4475. }
  4476. // Similarly, attempt to find composite type of two objective-c pointers.
  4477. Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
  4478. if (!Composite.isNull())
  4479. return Composite;
  4480. // Check if we are using a null with a non-pointer type.
  4481. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  4482. return QualType();
  4483. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  4484. << LHS.get()->getType() << RHS.get()->getType()
  4485. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4486. return QualType();
  4487. }
  4488. /// \brief Find a merged pointer type and convert the two expressions to it.
  4489. ///
  4490. /// This finds the composite pointer type (or member pointer type) for @p E1
  4491. /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
  4492. /// type and returns it.
  4493. /// It does not emit diagnostics.
  4494. ///
  4495. /// \param Loc The location of the operator requiring these two expressions to
  4496. /// be converted to the composite pointer type.
  4497. ///
  4498. /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
  4499. /// a non-standard (but still sane) composite type to which both expressions
  4500. /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
  4501. /// will be set true.
  4502. QualType Sema::FindCompositePointerType(SourceLocation Loc,
  4503. Expr *&E1, Expr *&E2,
  4504. bool *NonStandardCompositeType) {
  4505. if (NonStandardCompositeType)
  4506. *NonStandardCompositeType = false;
  4507. assert(getLangOpts().CPlusPlus && "This function assumes C++");
  4508. QualType T1 = E1->getType(), T2 = E2->getType();
  4509. // C++11 5.9p2
  4510. // Pointer conversions and qualification conversions are performed on
  4511. // pointer operands to bring them to their composite pointer type. If
  4512. // one operand is a null pointer constant, the composite pointer type is
  4513. // std::nullptr_t if the other operand is also a null pointer constant or,
  4514. // if the other operand is a pointer, the type of the other operand.
  4515. if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
  4516. !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
  4517. if (T1->isNullPtrType() &&
  4518. E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  4519. E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
  4520. return T1;
  4521. }
  4522. if (T2->isNullPtrType() &&
  4523. E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  4524. E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
  4525. return T2;
  4526. }
  4527. return QualType();
  4528. }
  4529. if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  4530. if (T2->isMemberPointerType())
  4531. E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
  4532. else
  4533. E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
  4534. return T2;
  4535. }
  4536. if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  4537. if (T1->isMemberPointerType())
  4538. E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
  4539. else
  4540. E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
  4541. return T1;
  4542. }
  4543. // Now both have to be pointers or member pointers.
  4544. if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
  4545. (!T2->isPointerType() && !T2->isMemberPointerType()))
  4546. return QualType();
  4547. // Otherwise, of one of the operands has type "pointer to cv1 void," then
  4548. // the other has type "pointer to cv2 T" and the composite pointer type is
  4549. // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
  4550. // Otherwise, the composite pointer type is a pointer type similar to the
  4551. // type of one of the operands, with a cv-qualification signature that is
  4552. // the union of the cv-qualification signatures of the operand types.
  4553. // In practice, the first part here is redundant; it's subsumed by the second.
  4554. // What we do here is, we build the two possible composite types, and try the
  4555. // conversions in both directions. If only one works, or if the two composite
  4556. // types are the same, we have succeeded.
  4557. // FIXME: extended qualifiers?
  4558. typedef SmallVector<unsigned, 4> QualifierVector;
  4559. QualifierVector QualifierUnion;
  4560. typedef SmallVector<std::pair<const Type *, const Type *>, 4>
  4561. ContainingClassVector;
  4562. ContainingClassVector MemberOfClass;
  4563. QualType Composite1 = Context.getCanonicalType(T1),
  4564. Composite2 = Context.getCanonicalType(T2);
  4565. unsigned NeedConstBefore = 0;
  4566. do {
  4567. const PointerType *Ptr1, *Ptr2;
  4568. if ((Ptr1 = Composite1->getAs<PointerType>()) &&
  4569. (Ptr2 = Composite2->getAs<PointerType>())) {
  4570. Composite1 = Ptr1->getPointeeType();
  4571. Composite2 = Ptr2->getPointeeType();
  4572. // If we're allowed to create a non-standard composite type, keep track
  4573. // of where we need to fill in additional 'const' qualifiers.
  4574. if (NonStandardCompositeType &&
  4575. Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
  4576. NeedConstBefore = QualifierUnion.size();
  4577. QualifierUnion.push_back(
  4578. Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
  4579. MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
  4580. continue;
  4581. }
  4582. const MemberPointerType *MemPtr1, *MemPtr2;
  4583. if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
  4584. (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
  4585. Composite1 = MemPtr1->getPointeeType();
  4586. Composite2 = MemPtr2->getPointeeType();
  4587. // If we're allowed to create a non-standard composite type, keep track
  4588. // of where we need to fill in additional 'const' qualifiers.
  4589. if (NonStandardCompositeType &&
  4590. Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
  4591. NeedConstBefore = QualifierUnion.size();
  4592. QualifierUnion.push_back(
  4593. Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
  4594. MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
  4595. MemPtr2->getClass()));
  4596. continue;
  4597. }
  4598. // FIXME: block pointer types?
  4599. // Cannot unwrap any more types.
  4600. break;
  4601. } while (true);
  4602. if (NeedConstBefore && NonStandardCompositeType) {
  4603. // Extension: Add 'const' to qualifiers that come before the first qualifier
  4604. // mismatch, so that our (non-standard!) composite type meets the
  4605. // requirements of C++ [conv.qual]p4 bullet 3.
  4606. for (unsigned I = 0; I != NeedConstBefore; ++I) {
  4607. if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
  4608. QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
  4609. *NonStandardCompositeType = true;
  4610. }
  4611. }
  4612. }
  4613. // Rewrap the composites as pointers or member pointers with the union CVRs.
  4614. ContainingClassVector::reverse_iterator MOC
  4615. = MemberOfClass.rbegin();
  4616. for (QualifierVector::reverse_iterator
  4617. I = QualifierUnion.rbegin(),
  4618. E = QualifierUnion.rend();
  4619. I != E; (void)++I, ++MOC) {
  4620. Qualifiers Quals = Qualifiers::fromCVRMask(*I);
  4621. if (MOC->first && MOC->second) {
  4622. // Rebuild member pointer type
  4623. Composite1 = Context.getMemberPointerType(
  4624. Context.getQualifiedType(Composite1, Quals),
  4625. MOC->first);
  4626. Composite2 = Context.getMemberPointerType(
  4627. Context.getQualifiedType(Composite2, Quals),
  4628. MOC->second);
  4629. } else {
  4630. // Rebuild pointer type
  4631. Composite1
  4632. = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
  4633. Composite2
  4634. = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
  4635. }
  4636. }
  4637. // Try to convert to the first composite pointer type.
  4638. InitializedEntity Entity1
  4639. = InitializedEntity::InitializeTemporary(Composite1);
  4640. InitializationKind Kind
  4641. = InitializationKind::CreateCopy(Loc, SourceLocation());
  4642. InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
  4643. InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
  4644. if (E1ToC1 && E2ToC1) {
  4645. // Conversion to Composite1 is viable.
  4646. if (!Context.hasSameType(Composite1, Composite2)) {
  4647. // Composite2 is a different type from Composite1. Check whether
  4648. // Composite2 is also viable.
  4649. InitializedEntity Entity2
  4650. = InitializedEntity::InitializeTemporary(Composite2);
  4651. InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
  4652. InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
  4653. if (E1ToC2 && E2ToC2) {
  4654. // Both Composite1 and Composite2 are viable and are different;
  4655. // this is an ambiguity.
  4656. return QualType();
  4657. }
  4658. }
  4659. // Convert E1 to Composite1
  4660. ExprResult E1Result
  4661. = E1ToC1.Perform(*this, Entity1, Kind, E1);
  4662. if (E1Result.isInvalid())
  4663. return QualType();
  4664. E1 = E1Result.getAs<Expr>();
  4665. // Convert E2 to Composite1
  4666. ExprResult E2Result
  4667. = E2ToC1.Perform(*this, Entity1, Kind, E2);
  4668. if (E2Result.isInvalid())
  4669. return QualType();
  4670. E2 = E2Result.getAs<Expr>();
  4671. return Composite1;
  4672. }
  4673. // Check whether Composite2 is viable.
  4674. InitializedEntity Entity2
  4675. = InitializedEntity::InitializeTemporary(Composite2);
  4676. InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
  4677. InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
  4678. if (!E1ToC2 || !E2ToC2)
  4679. return QualType();
  4680. // Convert E1 to Composite2
  4681. ExprResult E1Result
  4682. = E1ToC2.Perform(*this, Entity2, Kind, E1);
  4683. if (E1Result.isInvalid())
  4684. return QualType();
  4685. E1 = E1Result.getAs<Expr>();
  4686. // Convert E2 to Composite2
  4687. ExprResult E2Result
  4688. = E2ToC2.Perform(*this, Entity2, Kind, E2);
  4689. if (E2Result.isInvalid())
  4690. return QualType();
  4691. E2 = E2Result.getAs<Expr>();
  4692. return Composite2;
  4693. }
  4694. ExprResult Sema::MaybeBindToTemporary(Expr *E) {
  4695. if (!E)
  4696. return ExprError();
  4697. assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
  4698. // If the result is a glvalue, we shouldn't bind it.
  4699. if (!E->isRValue())
  4700. return E;
  4701. // In ARC, calls that return a retainable type can return retained,
  4702. // in which case we have to insert a consuming cast.
  4703. if (getLangOpts().ObjCAutoRefCount &&
  4704. E->getType()->isObjCRetainableType()) {
  4705. bool ReturnsRetained;
  4706. // For actual calls, we compute this by examining the type of the
  4707. // called value.
  4708. if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
  4709. Expr *Callee = Call->getCallee()->IgnoreParens();
  4710. QualType T = Callee->getType();
  4711. if (T == Context.BoundMemberTy) {
  4712. // Handle pointer-to-members.
  4713. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
  4714. T = BinOp->getRHS()->getType();
  4715. else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
  4716. T = Mem->getMemberDecl()->getType();
  4717. }
  4718. if (const PointerType *Ptr = T->getAs<PointerType>())
  4719. T = Ptr->getPointeeType();
  4720. else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
  4721. T = Ptr->getPointeeType();
  4722. else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
  4723. T = MemPtr->getPointeeType();
  4724. const FunctionType *FTy = T->getAs<FunctionType>();
  4725. assert(FTy && "call to value not of function type?");
  4726. ReturnsRetained = FTy->getExtInfo().getProducesResult();
  4727. // ActOnStmtExpr arranges things so that StmtExprs of retainable
  4728. // type always produce a +1 object.
  4729. } else if (isa<StmtExpr>(E)) {
  4730. ReturnsRetained = true;
  4731. // We hit this case with the lambda conversion-to-block optimization;
  4732. // we don't want any extra casts here.
  4733. } else if (isa<CastExpr>(E) &&
  4734. isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
  4735. return E;
  4736. // For message sends and property references, we try to find an
  4737. // actual method. FIXME: we should infer retention by selector in
  4738. // cases where we don't have an actual method.
  4739. } else {
  4740. ObjCMethodDecl *D = nullptr;
  4741. if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
  4742. D = Send->getMethodDecl();
  4743. } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
  4744. D = BoxedExpr->getBoxingMethod();
  4745. } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
  4746. D = ArrayLit->getArrayWithObjectsMethod();
  4747. } else if (ObjCDictionaryLiteral *DictLit
  4748. = dyn_cast<ObjCDictionaryLiteral>(E)) {
  4749. D = DictLit->getDictWithObjectsMethod();
  4750. }
  4751. ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
  4752. // Don't do reclaims on performSelector calls; despite their
  4753. // return type, the invoked method doesn't necessarily actually
  4754. // return an object.
  4755. if (!ReturnsRetained &&
  4756. D && D->getMethodFamily() == OMF_performSelector)
  4757. return E;
  4758. }
  4759. // Don't reclaim an object of Class type.
  4760. if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
  4761. return E;
  4762. ExprNeedsCleanups = true;
  4763. CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
  4764. : CK_ARCReclaimReturnedObject);
  4765. return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
  4766. VK_RValue);
  4767. }
  4768. if (!getLangOpts().CPlusPlus)
  4769. return E;
  4770. // Search for the base element type (cf. ASTContext::getBaseElementType) with
  4771. // a fast path for the common case that the type is directly a RecordType.
  4772. const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
  4773. const RecordType *RT = nullptr;
  4774. while (!RT) {
  4775. switch (T->getTypeClass()) {
  4776. case Type::Record:
  4777. RT = cast<RecordType>(T);
  4778. break;
  4779. case Type::ConstantArray:
  4780. case Type::IncompleteArray:
  4781. case Type::VariableArray:
  4782. case Type::DependentSizedArray:
  4783. T = cast<ArrayType>(T)->getElementType().getTypePtr();
  4784. break;
  4785. default:
  4786. return E;
  4787. }
  4788. }
  4789. // That should be enough to guarantee that this type is complete, if we're
  4790. // not processing a decltype expression.
  4791. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  4792. if (RD->isInvalidDecl() || RD->isDependentContext())
  4793. return E;
  4794. bool IsDecltype = ExprEvalContexts.back().IsDecltype;
  4795. CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
  4796. if (Destructor) {
  4797. MarkFunctionReferenced(E->getExprLoc(), Destructor);
  4798. CheckDestructorAccess(E->getExprLoc(), Destructor,
  4799. PDiag(diag::err_access_dtor_temp)
  4800. << E->getType());
  4801. if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
  4802. return ExprError();
  4803. // If destructor is trivial, we can avoid the extra copy.
  4804. if (Destructor->isTrivial())
  4805. return E;
  4806. // We need a cleanup, but we don't need to remember the temporary.
  4807. ExprNeedsCleanups = true;
  4808. }
  4809. CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
  4810. CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
  4811. if (IsDecltype)
  4812. ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
  4813. return Bind;
  4814. }
  4815. ExprResult
  4816. Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
  4817. if (SubExpr.isInvalid())
  4818. return ExprError();
  4819. return MaybeCreateExprWithCleanups(SubExpr.get());
  4820. }
  4821. Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
  4822. assert(SubExpr && "subexpression can't be null!");
  4823. CleanupVarDeclMarking();
  4824. unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
  4825. assert(ExprCleanupObjects.size() >= FirstCleanup);
  4826. assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
  4827. if (!ExprNeedsCleanups)
  4828. return SubExpr;
  4829. auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
  4830. ExprCleanupObjects.size() - FirstCleanup);
  4831. Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
  4832. DiscardCleanupsInEvaluationContext();
  4833. return E;
  4834. }
  4835. Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
  4836. assert(SubStmt && "sub-statement can't be null!");
  4837. CleanupVarDeclMarking();
  4838. if (!ExprNeedsCleanups)
  4839. return SubStmt;
  4840. // FIXME: In order to attach the temporaries, wrap the statement into
  4841. // a StmtExpr; currently this is only used for asm statements.
  4842. // This is hacky, either create a new CXXStmtWithTemporaries statement or
  4843. // a new AsmStmtWithTemporaries.
  4844. CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
  4845. SourceLocation(),
  4846. SourceLocation());
  4847. Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
  4848. SourceLocation());
  4849. return MaybeCreateExprWithCleanups(E);
  4850. }
  4851. /// Process the expression contained within a decltype. For such expressions,
  4852. /// certain semantic checks on temporaries are delayed until this point, and
  4853. /// are omitted for the 'topmost' call in the decltype expression. If the
  4854. /// topmost call bound a temporary, strip that temporary off the expression.
  4855. ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
  4856. assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
  4857. // C++11 [expr.call]p11:
  4858. // If a function call is a prvalue of object type,
  4859. // -- if the function call is either
  4860. // -- the operand of a decltype-specifier, or
  4861. // -- the right operand of a comma operator that is the operand of a
  4862. // decltype-specifier,
  4863. // a temporary object is not introduced for the prvalue.
  4864. // Recursively rebuild ParenExprs and comma expressions to strip out the
  4865. // outermost CXXBindTemporaryExpr, if any.
  4866. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  4867. ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
  4868. if (SubExpr.isInvalid())
  4869. return ExprError();
  4870. if (SubExpr.get() == PE->getSubExpr())
  4871. return E;
  4872. return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
  4873. }
  4874. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  4875. if (BO->getOpcode() == BO_Comma) {
  4876. ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
  4877. if (RHS.isInvalid())
  4878. return ExprError();
  4879. if (RHS.get() == BO->getRHS())
  4880. return E;
  4881. return new (Context) BinaryOperator(
  4882. BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
  4883. BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
  4884. }
  4885. }
  4886. CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
  4887. CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
  4888. : nullptr;
  4889. if (TopCall)
  4890. E = TopCall;
  4891. else
  4892. TopBind = nullptr;
  4893. // Disable the special decltype handling now.
  4894. ExprEvalContexts.back().IsDecltype = false;
  4895. // In MS mode, don't perform any extra checking of call return types within a
  4896. // decltype expression.
  4897. if (getLangOpts().MSVCCompat)
  4898. return E;
  4899. // Perform the semantic checks we delayed until this point.
  4900. for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
  4901. I != N; ++I) {
  4902. CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
  4903. if (Call == TopCall)
  4904. continue;
  4905. if (CheckCallReturnType(Call->getCallReturnType(Context),
  4906. Call->getLocStart(),
  4907. Call, Call->getDirectCallee()))
  4908. return ExprError();
  4909. }
  4910. // Now all relevant types are complete, check the destructors are accessible
  4911. // and non-deleted, and annotate them on the temporaries.
  4912. for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
  4913. I != N; ++I) {
  4914. CXXBindTemporaryExpr *Bind =
  4915. ExprEvalContexts.back().DelayedDecltypeBinds[I];
  4916. if (Bind == TopBind)
  4917. continue;
  4918. CXXTemporary *Temp = Bind->getTemporary();
  4919. CXXRecordDecl *RD =
  4920. Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  4921. CXXDestructorDecl *Destructor = LookupDestructor(RD);
  4922. Temp->setDestructor(Destructor);
  4923. MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
  4924. CheckDestructorAccess(Bind->getExprLoc(), Destructor,
  4925. PDiag(diag::err_access_dtor_temp)
  4926. << Bind->getType());
  4927. if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
  4928. return ExprError();
  4929. // We need a cleanup, but we don't need to remember the temporary.
  4930. ExprNeedsCleanups = true;
  4931. }
  4932. // Possibly strip off the top CXXBindTemporaryExpr.
  4933. return E;
  4934. }
  4935. /// Note a set of 'operator->' functions that were used for a member access.
  4936. static void noteOperatorArrows(Sema &S,
  4937. ArrayRef<FunctionDecl *> OperatorArrows) {
  4938. unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
  4939. // FIXME: Make this configurable?
  4940. unsigned Limit = 9;
  4941. if (OperatorArrows.size() > Limit) {
  4942. // Produce Limit-1 normal notes and one 'skipping' note.
  4943. SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
  4944. SkipCount = OperatorArrows.size() - (Limit - 1);
  4945. }
  4946. for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
  4947. if (I == SkipStart) {
  4948. S.Diag(OperatorArrows[I]->getLocation(),
  4949. diag::note_operator_arrows_suppressed)
  4950. << SkipCount;
  4951. I += SkipCount;
  4952. } else {
  4953. S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
  4954. << OperatorArrows[I]->getCallResultType();
  4955. ++I;
  4956. }
  4957. }
  4958. }
  4959. ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
  4960. SourceLocation OpLoc,
  4961. tok::TokenKind OpKind,
  4962. ParsedType &ObjectType,
  4963. bool &MayBePseudoDestructor) {
  4964. // Since this might be a postfix expression, get rid of ParenListExprs.
  4965. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
  4966. if (Result.isInvalid()) return ExprError();
  4967. Base = Result.get();
  4968. Result = CheckPlaceholderExpr(Base);
  4969. if (Result.isInvalid()) return ExprError();
  4970. Base = Result.get();
  4971. // HLSL Change Starts
  4972. assert(OpKind == tok::arrow || OpKind == tok::period);
  4973. if (getLangOpts().HLSL && OpKind != tok::period) {
  4974. // continue processing as if it was a period accessor
  4975. Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  4976. OpKind = tok::period;
  4977. }
  4978. // HLSL Change Ends
  4979. QualType BaseType = Base->getType();
  4980. MayBePseudoDestructor = false;
  4981. if (BaseType->isDependentType()) {
  4982. // If we have a pointer to a dependent type and are using the -> operator,
  4983. // the object type is the type that the pointer points to. We might still
  4984. // have enough information about that type to do something useful.
  4985. if (OpKind == tok::arrow)
  4986. if (const PointerType *Ptr = BaseType->getAs<PointerType>())
  4987. BaseType = Ptr->getPointeeType();
  4988. ObjectType = ParsedType::make(BaseType);
  4989. MayBePseudoDestructor = true;
  4990. return Base;
  4991. }
  4992. // C++ [over.match.oper]p8:
  4993. // [...] When operator->returns, the operator-> is applied to the value
  4994. // returned, with the original second operand.
  4995. if (OpKind == tok::arrow) {
  4996. QualType StartingType = BaseType;
  4997. bool NoArrowOperatorFound = false;
  4998. bool FirstIteration = true;
  4999. FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
  5000. // The set of types we've considered so far.
  5001. llvm::SmallPtrSet<CanQualType,8> CTypes;
  5002. SmallVector<FunctionDecl*, 8> OperatorArrows;
  5003. CTypes.insert(Context.getCanonicalType(BaseType));
  5004. while (BaseType->isRecordType()) {
  5005. if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
  5006. Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
  5007. << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
  5008. noteOperatorArrows(*this, OperatorArrows);
  5009. Diag(OpLoc, diag::note_operator_arrow_depth)
  5010. << getLangOpts().ArrowDepth;
  5011. return ExprError();
  5012. }
  5013. Result = BuildOverloadedArrowExpr(
  5014. S, Base, OpLoc,
  5015. // When in a template specialization and on the first loop iteration,
  5016. // potentially give the default diagnostic (with the fixit in a
  5017. // separate note) instead of having the error reported back to here
  5018. // and giving a diagnostic with a fixit attached to the error itself.
  5019. (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
  5020. ? nullptr
  5021. : &NoArrowOperatorFound);
  5022. if (Result.isInvalid()) {
  5023. if (NoArrowOperatorFound) {
  5024. if (FirstIteration) {
  5025. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  5026. << BaseType << 1 << Base->getSourceRange()
  5027. << FixItHint::CreateReplacement(OpLoc, ".");
  5028. OpKind = tok::period;
  5029. break;
  5030. }
  5031. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  5032. << BaseType << Base->getSourceRange();
  5033. CallExpr *CE = dyn_cast<CallExpr>(Base);
  5034. if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
  5035. Diag(CD->getLocStart(),
  5036. diag::note_member_reference_arrow_from_operator_arrow);
  5037. }
  5038. }
  5039. return ExprError();
  5040. }
  5041. Base = Result.get();
  5042. if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
  5043. OperatorArrows.push_back(OpCall->getDirectCallee());
  5044. BaseType = Base->getType();
  5045. CanQualType CBaseType = Context.getCanonicalType(BaseType);
  5046. if (!CTypes.insert(CBaseType).second) {
  5047. Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
  5048. noteOperatorArrows(*this, OperatorArrows);
  5049. return ExprError();
  5050. }
  5051. FirstIteration = false;
  5052. }
  5053. if (OpKind == tok::arrow &&
  5054. (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
  5055. BaseType = BaseType->getPointeeType();
  5056. }
  5057. // Objective-C properties allow "." access on Objective-C pointer types,
  5058. // so adjust the base type to the object type itself.
  5059. if (BaseType->isObjCObjectPointerType())
  5060. BaseType = BaseType->getPointeeType();
  5061. // C++ [basic.lookup.classref]p2:
  5062. // [...] If the type of the object expression is of pointer to scalar
  5063. // type, the unqualified-id is looked up in the context of the complete
  5064. // postfix-expression.
  5065. //
  5066. // This also indicates that we could be parsing a pseudo-destructor-name.
  5067. // Note that Objective-C class and object types can be pseudo-destructor
  5068. // expressions or normal member (ivar or property) access expressions.
  5069. if (BaseType->isObjCObjectOrInterfaceType()) {
  5070. MayBePseudoDestructor = true;
  5071. } else if (!BaseType->isRecordType()) {
  5072. ObjectType = ParsedType();
  5073. MayBePseudoDestructor = true;
  5074. return Base;
  5075. }
  5076. // The object type must be complete (or dependent), or
  5077. // C++11 [expr.prim.general]p3:
  5078. // Unlike the object expression in other contexts, *this is not required to
  5079. // be of complete type for purposes of class member access (5.2.5) outside
  5080. // the member function body.
  5081. if (!BaseType->isDependentType() &&
  5082. !isThisOutsideMemberFunctionBody(BaseType) &&
  5083. RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
  5084. return ExprError();
  5085. // C++ [basic.lookup.classref]p2:
  5086. // If the id-expression in a class member access (5.2.5) is an
  5087. // unqualified-id, and the type of the object expression is of a class
  5088. // type C (or of pointer to a class type C), the unqualified-id is looked
  5089. // up in the scope of class C. [...]
  5090. ObjectType = ParsedType::make(BaseType);
  5091. return Base;
  5092. }
  5093. static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
  5094. tok::TokenKind& OpKind, SourceLocation OpLoc) {
  5095. if (Base->hasPlaceholderType()) {
  5096. ExprResult result = S.CheckPlaceholderExpr(Base);
  5097. if (result.isInvalid()) return true;
  5098. Base = result.get();
  5099. }
  5100. ObjectType = Base->getType();
  5101. // C++ [expr.pseudo]p2:
  5102. // The left-hand side of the dot operator shall be of scalar type. The
  5103. // left-hand side of the arrow operator shall be of pointer to scalar type.
  5104. // This scalar type is the object type.
  5105. // Note that this is rather different from the normal handling for the
  5106. // arrow operator.
  5107. if (OpKind == tok::arrow) {
  5108. if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
  5109. ObjectType = Ptr->getPointeeType();
  5110. } else if (!Base->isTypeDependent()) {
  5111. // The user wrote "p->" when she probably meant "p."; fix it.
  5112. S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  5113. << ObjectType << true
  5114. << FixItHint::CreateReplacement(OpLoc, ".");
  5115. if (S.isSFINAEContext())
  5116. return true;
  5117. OpKind = tok::period;
  5118. }
  5119. }
  5120. return false;
  5121. }
  5122. ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
  5123. SourceLocation OpLoc,
  5124. tok::TokenKind OpKind,
  5125. const CXXScopeSpec &SS,
  5126. TypeSourceInfo *ScopeTypeInfo,
  5127. SourceLocation CCLoc,
  5128. SourceLocation TildeLoc,
  5129. PseudoDestructorTypeStorage Destructed) {
  5130. TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
  5131. QualType ObjectType;
  5132. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  5133. return ExprError();
  5134. if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
  5135. !ObjectType->isVectorType()) {
  5136. if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
  5137. Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
  5138. else {
  5139. Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
  5140. << ObjectType << Base->getSourceRange();
  5141. return ExprError();
  5142. }
  5143. }
  5144. // C++ [expr.pseudo]p2:
  5145. // [...] The cv-unqualified versions of the object type and of the type
  5146. // designated by the pseudo-destructor-name shall be the same type.
  5147. if (DestructedTypeInfo) {
  5148. QualType DestructedType = DestructedTypeInfo->getType();
  5149. SourceLocation DestructedTypeStart
  5150. = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
  5151. if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
  5152. if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
  5153. Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
  5154. << ObjectType << DestructedType << Base->getSourceRange()
  5155. << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
  5156. // Recover by setting the destructed type to the object type.
  5157. DestructedType = ObjectType;
  5158. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
  5159. DestructedTypeStart);
  5160. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  5161. } else if (DestructedType.getObjCLifetime() !=
  5162. ObjectType.getObjCLifetime()) {
  5163. if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
  5164. // Okay: just pretend that the user provided the correctly-qualified
  5165. // type.
  5166. } else {
  5167. Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
  5168. << ObjectType << DestructedType << Base->getSourceRange()
  5169. << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
  5170. }
  5171. // Recover by setting the destructed type to the object type.
  5172. DestructedType = ObjectType;
  5173. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
  5174. DestructedTypeStart);
  5175. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  5176. }
  5177. }
  5178. }
  5179. // C++ [expr.pseudo]p2:
  5180. // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
  5181. // form
  5182. //
  5183. // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
  5184. //
  5185. // shall designate the same scalar type.
  5186. if (ScopeTypeInfo) {
  5187. QualType ScopeType = ScopeTypeInfo->getType();
  5188. if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
  5189. !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
  5190. Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
  5191. diag::err_pseudo_dtor_type_mismatch)
  5192. << ObjectType << ScopeType << Base->getSourceRange()
  5193. << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
  5194. ScopeType = QualType();
  5195. ScopeTypeInfo = nullptr;
  5196. }
  5197. }
  5198. Expr *Result
  5199. = new (Context) CXXPseudoDestructorExpr(Context, Base,
  5200. OpKind == tok::arrow, OpLoc,
  5201. SS.getWithLocInContext(Context),
  5202. ScopeTypeInfo,
  5203. CCLoc,
  5204. TildeLoc,
  5205. Destructed);
  5206. return Result;
  5207. }
  5208. ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
  5209. SourceLocation OpLoc,
  5210. tok::TokenKind OpKind,
  5211. CXXScopeSpec &SS,
  5212. UnqualifiedId &FirstTypeName,
  5213. SourceLocation CCLoc,
  5214. SourceLocation TildeLoc,
  5215. UnqualifiedId &SecondTypeName) {
  5216. assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
  5217. FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
  5218. "Invalid first type name in pseudo-destructor");
  5219. assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
  5220. SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
  5221. "Invalid second type name in pseudo-destructor");
  5222. QualType ObjectType;
  5223. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  5224. return ExprError();
  5225. // Compute the object type that we should use for name lookup purposes. Only
  5226. // record types and dependent types matter.
  5227. ParsedType ObjectTypePtrForLookup;
  5228. if (!SS.isSet()) {
  5229. if (ObjectType->isRecordType())
  5230. ObjectTypePtrForLookup = ParsedType::make(ObjectType);
  5231. else if (ObjectType->isDependentType())
  5232. ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
  5233. }
  5234. // Convert the name of the type being destructed (following the ~) into a
  5235. // type (with source-location information).
  5236. QualType DestructedType;
  5237. TypeSourceInfo *DestructedTypeInfo = nullptr;
  5238. PseudoDestructorTypeStorage Destructed;
  5239. if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
  5240. ParsedType T = getTypeName(*SecondTypeName.Identifier,
  5241. SecondTypeName.StartLocation,
  5242. S, &SS, true, false, ObjectTypePtrForLookup);
  5243. if (!T &&
  5244. ((SS.isSet() && !computeDeclContext(SS, false)) ||
  5245. (!SS.isSet() && ObjectType->isDependentType()))) {
  5246. // The name of the type being destroyed is a dependent name, and we
  5247. // couldn't find anything useful in scope. Just store the identifier and
  5248. // it's location, and we'll perform (qualified) name lookup again at
  5249. // template instantiation time.
  5250. Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
  5251. SecondTypeName.StartLocation);
  5252. } else if (!T) {
  5253. Diag(SecondTypeName.StartLocation,
  5254. diag::err_pseudo_dtor_destructor_non_type)
  5255. << SecondTypeName.Identifier << ObjectType;
  5256. if (isSFINAEContext())
  5257. return ExprError();
  5258. // Recover by assuming we had the right type all along.
  5259. DestructedType = ObjectType;
  5260. } else
  5261. DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
  5262. } else {
  5263. // Resolve the template-id to a type.
  5264. TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
  5265. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  5266. TemplateId->NumArgs);
  5267. TypeResult T = ActOnTemplateIdType(TemplateId->SS,
  5268. TemplateId->TemplateKWLoc,
  5269. TemplateId->Template,
  5270. TemplateId->TemplateNameLoc,
  5271. TemplateId->LAngleLoc,
  5272. TemplateArgsPtr,
  5273. TemplateId->RAngleLoc);
  5274. if (T.isInvalid() || !T.get()) {
  5275. // Recover by assuming we had the right type all along.
  5276. DestructedType = ObjectType;
  5277. } else
  5278. DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
  5279. }
  5280. // If we've performed some kind of recovery, (re-)build the type source
  5281. // information.
  5282. if (!DestructedType.isNull()) {
  5283. if (!DestructedTypeInfo)
  5284. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
  5285. SecondTypeName.StartLocation);
  5286. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  5287. }
  5288. // Convert the name of the scope type (the type prior to '::') into a type.
  5289. TypeSourceInfo *ScopeTypeInfo = nullptr;
  5290. QualType ScopeType;
  5291. if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
  5292. FirstTypeName.Identifier) {
  5293. if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
  5294. ParsedType T = getTypeName(*FirstTypeName.Identifier,
  5295. FirstTypeName.StartLocation,
  5296. S, &SS, true, false, ObjectTypePtrForLookup);
  5297. if (!T) {
  5298. Diag(FirstTypeName.StartLocation,
  5299. diag::err_pseudo_dtor_destructor_non_type)
  5300. << FirstTypeName.Identifier << ObjectType;
  5301. if (isSFINAEContext())
  5302. return ExprError();
  5303. // Just drop this type. It's unnecessary anyway.
  5304. ScopeType = QualType();
  5305. } else
  5306. ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
  5307. } else {
  5308. // Resolve the template-id to a type.
  5309. TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
  5310. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  5311. TemplateId->NumArgs);
  5312. TypeResult T = ActOnTemplateIdType(TemplateId->SS,
  5313. TemplateId->TemplateKWLoc,
  5314. TemplateId->Template,
  5315. TemplateId->TemplateNameLoc,
  5316. TemplateId->LAngleLoc,
  5317. TemplateArgsPtr,
  5318. TemplateId->RAngleLoc);
  5319. if (T.isInvalid() || !T.get()) {
  5320. // Recover by dropping this type.
  5321. ScopeType = QualType();
  5322. } else
  5323. ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
  5324. }
  5325. }
  5326. if (!ScopeType.isNull() && !ScopeTypeInfo)
  5327. ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
  5328. FirstTypeName.StartLocation);
  5329. return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
  5330. ScopeTypeInfo, CCLoc, TildeLoc,
  5331. Destructed);
  5332. }
  5333. ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
  5334. SourceLocation OpLoc,
  5335. tok::TokenKind OpKind,
  5336. SourceLocation TildeLoc,
  5337. const DeclSpec& DS) {
  5338. QualType ObjectType;
  5339. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  5340. return ExprError();
  5341. QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
  5342. false);
  5343. TypeLocBuilder TLB;
  5344. DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
  5345. DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
  5346. TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
  5347. PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
  5348. return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
  5349. nullptr, SourceLocation(), TildeLoc,
  5350. Destructed);
  5351. }
  5352. ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
  5353. CXXConversionDecl *Method,
  5354. bool HadMultipleCandidates) {
  5355. if (Method->getParent()->isLambda() &&
  5356. Method->getConversionType()->isBlockPointerType()) {
  5357. // This is a lambda coversion to block pointer; check if the argument
  5358. // is a LambdaExpr.
  5359. Expr *SubE = E;
  5360. CastExpr *CE = dyn_cast<CastExpr>(SubE);
  5361. if (CE && CE->getCastKind() == CK_NoOp)
  5362. SubE = CE->getSubExpr();
  5363. SubE = SubE->IgnoreParens();
  5364. if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
  5365. SubE = BE->getSubExpr();
  5366. if (isa<LambdaExpr>(SubE)) {
  5367. // For the conversion to block pointer on a lambda expression, we
  5368. // construct a special BlockLiteral instead; this doesn't really make
  5369. // a difference in ARC, but outside of ARC the resulting block literal
  5370. // follows the normal lifetime rules for block literals instead of being
  5371. // autoreleased.
  5372. DiagnosticErrorTrap Trap(Diags);
  5373. ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
  5374. E->getExprLoc(),
  5375. Method, E);
  5376. if (Exp.isInvalid())
  5377. Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
  5378. return Exp;
  5379. }
  5380. }
  5381. ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
  5382. FoundDecl, Method);
  5383. if (Exp.isInvalid())
  5384. return true;
  5385. MemberExpr *ME = new (Context) MemberExpr(
  5386. Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
  5387. Context.BoundMemberTy, VK_RValue, OK_Ordinary);
  5388. if (HadMultipleCandidates)
  5389. ME->setHadMultipleCandidates(true);
  5390. MarkMemberReferenced(ME);
  5391. QualType ResultType = Method->getReturnType();
  5392. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  5393. ResultType = ResultType.getNonLValueExprType(Context);
  5394. CXXMemberCallExpr *CE =
  5395. new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
  5396. Exp.get()->getLocEnd());
  5397. return CE;
  5398. }
  5399. ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
  5400. SourceLocation RParen) {
  5401. // If the operand is an unresolved lookup expression, the expression is ill-
  5402. // formed per [over.over]p1, because overloaded function names cannot be used
  5403. // without arguments except in explicit contexts.
  5404. ExprResult R = CheckPlaceholderExpr(Operand);
  5405. if (R.isInvalid())
  5406. return R;
  5407. // The operand may have been modified when checking the placeholder type.
  5408. Operand = R.get();
  5409. if (ActiveTemplateInstantiations.empty() &&
  5410. Operand->HasSideEffects(Context, false)) {
  5411. // The expression operand for noexcept is in an unevaluated expression
  5412. // context, so side effects could result in unintended consequences.
  5413. Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  5414. }
  5415. CanThrowResult CanThrow = canThrow(Operand);
  5416. return new (Context)
  5417. CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
  5418. }
  5419. ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
  5420. Expr *Operand, SourceLocation RParen) {
  5421. return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
  5422. }
  5423. static bool IsSpecialDiscardedValue(Expr *E) {
  5424. // In C++11, discarded-value expressions of a certain form are special,
  5425. // according to [expr]p10:
  5426. // The lvalue-to-rvalue conversion (4.1) is applied only if the
  5427. // expression is an lvalue of volatile-qualified type and it has
  5428. // one of the following forms:
  5429. E = E->IgnoreParens();
  5430. // - id-expression (5.1.1),
  5431. if (isa<DeclRefExpr>(E))
  5432. return true;
  5433. // - subscripting (5.2.1),
  5434. if (isa<ArraySubscriptExpr>(E))
  5435. return true;
  5436. // - class member access (5.2.5),
  5437. if (isa<MemberExpr>(E))
  5438. return true;
  5439. // - indirection (5.3.1),
  5440. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
  5441. if (UO->getOpcode() == UO_Deref)
  5442. return true;
  5443. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  5444. // - pointer-to-member operation (5.5),
  5445. if (BO->isPtrMemOp())
  5446. return true;
  5447. // - comma expression (5.18) where the right operand is one of the above.
  5448. if (BO->getOpcode() == BO_Comma)
  5449. return IsSpecialDiscardedValue(BO->getRHS());
  5450. }
  5451. // - conditional expression (5.16) where both the second and the third
  5452. // operands are one of the above, or
  5453. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
  5454. return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
  5455. IsSpecialDiscardedValue(CO->getFalseExpr());
  5456. // The related edge case of "*x ?: *x".
  5457. if (BinaryConditionalOperator *BCO =
  5458. dyn_cast<BinaryConditionalOperator>(E)) {
  5459. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
  5460. return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
  5461. IsSpecialDiscardedValue(BCO->getFalseExpr());
  5462. }
  5463. // Objective-C++ extensions to the rule.
  5464. if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
  5465. return true;
  5466. return false;
  5467. }
  5468. /// Perform the conversions required for an expression used in a
  5469. /// context that ignores the result.
  5470. ExprResult Sema::IgnoredValueConversions(Expr *E) {
  5471. if (E->hasPlaceholderType()) {
  5472. ExprResult result = CheckPlaceholderExpr(E);
  5473. if (result.isInvalid()) return E;
  5474. E = result.get();
  5475. }
  5476. // C99 6.3.2.1:
  5477. // [Except in specific positions,] an lvalue that does not have
  5478. // array type is converted to the value stored in the
  5479. // designated object (and is no longer an lvalue).
  5480. if (E->isRValue()) {
  5481. // In C, function designators (i.e. expressions of function type)
  5482. // are r-values, but we still want to do function-to-pointer decay
  5483. // on them. This is both technically correct and convenient for
  5484. // some clients.
  5485. if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
  5486. return DefaultFunctionArrayConversion(E);
  5487. return E;
  5488. }
  5489. if (getLangOpts().CPlusPlus) {
  5490. // The C++11 standard defines the notion of a discarded-value expression;
  5491. // normally, we don't need to do anything to handle it, but if it is a
  5492. // volatile lvalue with a special form, we perform an lvalue-to-rvalue
  5493. // conversion.
  5494. if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
  5495. E->getType().isVolatileQualified() &&
  5496. IsSpecialDiscardedValue(E)) {
  5497. ExprResult Res = DefaultLvalueConversion(E);
  5498. if (Res.isInvalid())
  5499. return E;
  5500. E = Res.get();
  5501. }
  5502. return E;
  5503. }
  5504. // GCC seems to also exclude expressions of incomplete enum type.
  5505. if (const EnumType *T = E->getType()->getAs<EnumType>()) {
  5506. if (!T->getDecl()->isComplete()) {
  5507. // FIXME: stupid workaround for a codegen bug!
  5508. E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
  5509. return E;
  5510. }
  5511. }
  5512. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  5513. if (Res.isInvalid())
  5514. return E;
  5515. E = Res.get();
  5516. if (!E->getType()->isVoidType())
  5517. RequireCompleteType(E->getExprLoc(), E->getType(),
  5518. diag::err_incomplete_type);
  5519. return E;
  5520. }
  5521. // If we can unambiguously determine whether Var can never be used
  5522. // in a constant expression, return true.
  5523. // - if the variable and its initializer are non-dependent, then
  5524. // we can unambiguously check if the variable is a constant expression.
  5525. // - if the initializer is not value dependent - we can determine whether
  5526. // it can be used to initialize a constant expression. If Init can not
  5527. // be used to initialize a constant expression we conclude that Var can
  5528. // never be a constant expression.
  5529. // - FXIME: if the initializer is dependent, we can still do some analysis and
  5530. // identify certain cases unambiguously as non-const by using a Visitor:
  5531. // - such as those that involve odr-use of a ParmVarDecl, involve a new
  5532. // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
  5533. static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
  5534. ASTContext &Context) {
  5535. if (isa<ParmVarDecl>(Var)) return true;
  5536. const VarDecl *DefVD = nullptr;
  5537. // If there is no initializer - this can not be a constant expression.
  5538. if (!Var->getAnyInitializer(DefVD)) return true;
  5539. assert(DefVD);
  5540. if (DefVD->isWeak()) return false;
  5541. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  5542. Expr *Init = cast<Expr>(Eval->Value);
  5543. if (Var->getType()->isDependentType() || Init->isValueDependent()) {
  5544. // FIXME: Teach the constant evaluator to deal with the non-dependent parts
  5545. // of value-dependent expressions, and use it here to determine whether the
  5546. // initializer is a potential constant expression.
  5547. return false;
  5548. }
  5549. return !IsVariableAConstantExpression(Var, Context);
  5550. }
  5551. /// \brief Check if the current lambda has any potential captures
  5552. /// that must be captured by any of its enclosing lambdas that are ready to
  5553. /// capture. If there is a lambda that can capture a nested
  5554. /// potential-capture, go ahead and do so. Also, check to see if any
  5555. /// variables are uncaptureable or do not involve an odr-use so do not
  5556. /// need to be captured.
  5557. static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
  5558. Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
  5559. assert(!S.isUnevaluatedContext());
  5560. assert(S.CurContext->isDependentContext());
  5561. assert(CurrentLSI->CallOperator == S.CurContext &&
  5562. "The current call operator must be synchronized with Sema's CurContext");
  5563. const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
  5564. ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
  5565. S.FunctionScopes.data(), S.FunctionScopes.size());
  5566. // All the potentially captureable variables in the current nested
  5567. // lambda (within a generic outer lambda), must be captured by an
  5568. // outer lambda that is enclosed within a non-dependent context.
  5569. const unsigned NumPotentialCaptures =
  5570. CurrentLSI->getNumPotentialVariableCaptures();
  5571. for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
  5572. Expr *VarExpr = nullptr;
  5573. VarDecl *Var = nullptr;
  5574. CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
  5575. // If the variable is clearly identified as non-odr-used and the full
  5576. // expression is not instantiation dependent, only then do we not
  5577. // need to check enclosing lambda's for speculative captures.
  5578. // For e.g.:
  5579. // Even though 'x' is not odr-used, it should be captured.
  5580. // int test() {
  5581. // const int x = 10;
  5582. // auto L = [=](auto a) {
  5583. // (void) +x + a;
  5584. // };
  5585. // }
  5586. if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
  5587. !IsFullExprInstantiationDependent)
  5588. continue;
  5589. // If we have a capture-capable lambda for the variable, go ahead and
  5590. // capture the variable in that lambda (and all its enclosing lambdas).
  5591. if (const Optional<unsigned> Index =
  5592. getStackIndexOfNearestEnclosingCaptureCapableLambda(
  5593. FunctionScopesArrayRef, Var, S)) {
  5594. const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
  5595. MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
  5596. &FunctionScopeIndexOfCapturableLambda);
  5597. }
  5598. const bool IsVarNeverAConstantExpression =
  5599. VariableCanNeverBeAConstantExpression(Var, S.Context);
  5600. if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
  5601. // This full expression is not instantiation dependent or the variable
  5602. // can not be used in a constant expression - which means
  5603. // this variable must be odr-used here, so diagnose a
  5604. // capture violation early, if the variable is un-captureable.
  5605. // This is purely for diagnosing errors early. Otherwise, this
  5606. // error would get diagnosed when the lambda becomes capture ready.
  5607. QualType CaptureType, DeclRefType;
  5608. SourceLocation ExprLoc = VarExpr->getExprLoc();
  5609. if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
  5610. /*EllipsisLoc*/ SourceLocation(),
  5611. /*BuildAndDiagnose*/false, CaptureType,
  5612. DeclRefType, nullptr)) {
  5613. // We will never be able to capture this variable, and we need
  5614. // to be able to in any and all instantiations, so diagnose it.
  5615. S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
  5616. /*EllipsisLoc*/ SourceLocation(),
  5617. /*BuildAndDiagnose*/true, CaptureType,
  5618. DeclRefType, nullptr);
  5619. }
  5620. }
  5621. }
  5622. // Check if 'this' needs to be captured.
  5623. if (CurrentLSI->hasPotentialThisCapture()) {
  5624. // If we have a capture-capable lambda for 'this', go ahead and capture
  5625. // 'this' in that lambda (and all its enclosing lambdas).
  5626. if (const Optional<unsigned> Index =
  5627. getStackIndexOfNearestEnclosingCaptureCapableLambda(
  5628. FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
  5629. const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
  5630. S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
  5631. /*Explicit*/ false, /*BuildAndDiagnose*/ true,
  5632. &FunctionScopeIndexOfCapturableLambda);
  5633. }
  5634. }
  5635. // Reset all the potential captures at the end of each full-expression.
  5636. CurrentLSI->clearPotentialCaptures();
  5637. }
  5638. static ExprResult attemptRecovery(Sema &SemaRef,
  5639. const TypoCorrectionConsumer &Consumer,
  5640. TypoCorrection TC) {
  5641. LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
  5642. Consumer.getLookupResult().getLookupKind());
  5643. const CXXScopeSpec *SS = Consumer.getSS();
  5644. CXXScopeSpec NewSS;
  5645. // Use an approprate CXXScopeSpec for building the expr.
  5646. if (auto *NNS = TC.getCorrectionSpecifier())
  5647. NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
  5648. else if (SS && !TC.WillReplaceSpecifier())
  5649. NewSS = *SS;
  5650. if (auto *ND = TC.getCorrectionDecl()) {
  5651. R.setLookupName(ND->getDeclName());
  5652. R.addDecl(ND);
  5653. if (ND->isCXXClassMember()) {
  5654. // Figure out the correct naming class to add to the LookupResult.
  5655. CXXRecordDecl *Record = nullptr;
  5656. if (auto *NNS = TC.getCorrectionSpecifier())
  5657. Record = NNS->getAsType()->getAsCXXRecordDecl();
  5658. if (!Record)
  5659. Record =
  5660. dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
  5661. if (Record)
  5662. R.setNamingClass(Record);
  5663. // Detect and handle the case where the decl might be an implicit
  5664. // member.
  5665. bool MightBeImplicitMember;
  5666. if (!Consumer.isAddressOfOperand())
  5667. MightBeImplicitMember = true;
  5668. else if (!NewSS.isEmpty())
  5669. MightBeImplicitMember = false;
  5670. else if (R.isOverloadedResult())
  5671. MightBeImplicitMember = false;
  5672. else if (R.isUnresolvableResult())
  5673. MightBeImplicitMember = true;
  5674. else
  5675. MightBeImplicitMember = isa<FieldDecl>(ND) ||
  5676. isa<IndirectFieldDecl>(ND) ||
  5677. isa<MSPropertyDecl>(ND);
  5678. if (MightBeImplicitMember)
  5679. return SemaRef.BuildPossibleImplicitMemberExpr(
  5680. NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
  5681. /*TemplateArgs*/ nullptr);
  5682. } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
  5683. return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
  5684. Ivar->getIdentifier());
  5685. }
  5686. }
  5687. return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
  5688. /*AcceptInvalidDecl*/ true);
  5689. }
  5690. namespace {
  5691. class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
  5692. llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
  5693. public:
  5694. explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
  5695. : TypoExprs(TypoExprs) {}
  5696. bool VisitTypoExpr(TypoExpr *TE) {
  5697. TypoExprs.insert(TE);
  5698. return true;
  5699. }
  5700. };
  5701. class TransformTypos : public TreeTransform<TransformTypos> {
  5702. typedef TreeTransform<TransformTypos> BaseTransform;
  5703. VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
  5704. // process of being initialized.
  5705. llvm::function_ref<ExprResult(Expr *)> ExprFilter;
  5706. llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
  5707. llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
  5708. llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
  5709. /// \brief Emit diagnostics for all of the TypoExprs encountered.
  5710. /// If the TypoExprs were successfully corrected, then the diagnostics should
  5711. /// suggest the corrections. Otherwise the diagnostics will not suggest
  5712. /// anything (having been passed an empty TypoCorrection).
  5713. void EmitAllDiagnostics() {
  5714. for (auto E : TypoExprs) {
  5715. TypoExpr *TE = cast<TypoExpr>(E);
  5716. auto &State = SemaRef.getTypoExprState(TE);
  5717. if (State.DiagHandler) {
  5718. TypoCorrection TC = State.Consumer->getCurrentCorrection();
  5719. ExprResult Replacement = TransformCache[TE];
  5720. // Extract the NamedDecl from the transformed TypoExpr and add it to the
  5721. // TypoCorrection, replacing the existing decls. This ensures the right
  5722. // NamedDecl is used in diagnostics e.g. in the case where overload
  5723. // resolution was used to select one from several possible decls that
  5724. // had been stored in the TypoCorrection.
  5725. if (auto *ND = getDeclFromExpr(
  5726. Replacement.isInvalid() ? nullptr : Replacement.get()))
  5727. TC.setCorrectionDecl(ND);
  5728. State.DiagHandler(TC);
  5729. }
  5730. SemaRef.clearDelayedTypo(TE);
  5731. }
  5732. }
  5733. /// \brief If corrections for the first TypoExpr have been exhausted for a
  5734. /// given combination of the other TypoExprs, retry those corrections against
  5735. /// the next combination of substitutions for the other TypoExprs by advancing
  5736. /// to the next potential correction of the second TypoExpr. For the second
  5737. /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
  5738. /// the stream is reset and the next TypoExpr's stream is advanced by one (a
  5739. /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
  5740. /// TransformCache). Returns true if there is still any untried combinations
  5741. /// of corrections.
  5742. bool CheckAndAdvanceTypoExprCorrectionStreams() {
  5743. for (auto TE : TypoExprs) {
  5744. auto &State = SemaRef.getTypoExprState(TE);
  5745. TransformCache.erase(TE);
  5746. if (!State.Consumer->finished())
  5747. return true;
  5748. State.Consumer->resetCorrectionStream();
  5749. }
  5750. return false;
  5751. }
  5752. NamedDecl *getDeclFromExpr(Expr *E) {
  5753. if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
  5754. E = OverloadResolution[OE];
  5755. if (!E)
  5756. return nullptr;
  5757. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  5758. return DRE->getDecl();
  5759. if (auto *ME = dyn_cast<MemberExpr>(E))
  5760. return ME->getMemberDecl();
  5761. // FIXME: Add any other expr types that could be be seen by the delayed typo
  5762. // correction TreeTransform for which the corresponding TypoCorrection could
  5763. // contain multiple decls.
  5764. return nullptr;
  5765. }
  5766. ExprResult TryTransform(Expr *E) {
  5767. Sema::SFINAETrap Trap(SemaRef);
  5768. ExprResult Res = TransformExpr(E);
  5769. if (Trap.hasErrorOccurred() || Res.isInvalid())
  5770. return ExprError();
  5771. return ExprFilter(Res.get());
  5772. }
  5773. public:
  5774. TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
  5775. : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
  5776. ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
  5777. MultiExprArg Args,
  5778. SourceLocation RParenLoc,
  5779. Expr *ExecConfig = nullptr) {
  5780. auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
  5781. RParenLoc, ExecConfig);
  5782. if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
  5783. if (Result.isUsable()) {
  5784. Expr *ResultCall = Result.get();
  5785. if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
  5786. ResultCall = BE->getSubExpr();
  5787. if (auto *CE = dyn_cast<CallExpr>(ResultCall))
  5788. OverloadResolution[OE] = CE->getCallee();
  5789. }
  5790. }
  5791. return Result;
  5792. }
  5793. ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
  5794. ExprResult Transform(Expr *E) {
  5795. ExprResult Res;
  5796. while (true) {
  5797. Res = TryTransform(E);
  5798. // Exit if either the transform was valid or if there were no TypoExprs
  5799. // to transform that still have any untried correction candidates..
  5800. if (!Res.isInvalid() ||
  5801. !CheckAndAdvanceTypoExprCorrectionStreams())
  5802. break;
  5803. }
  5804. // Ensure none of the TypoExprs have multiple typo correction candidates
  5805. // with the same edit length that pass all the checks and filters.
  5806. // TODO: Properly handle various permutations of possible corrections when
  5807. // there is more than one potentially ambiguous typo correction.
  5808. // Also, disable typo correction while attempting the transform when
  5809. // handling potentially ambiguous typo corrections as any new TypoExprs will
  5810. // have been introduced by the application of one of the correction
  5811. // candidates and add little to no value if corrected.
  5812. SemaRef.DisableTypoCorrection = true;
  5813. while (!AmbiguousTypoExprs.empty()) {
  5814. auto TE = AmbiguousTypoExprs.back();
  5815. auto Cached = TransformCache[TE];
  5816. auto &State = SemaRef.getTypoExprState(TE);
  5817. State.Consumer->saveCurrentPosition();
  5818. TransformCache.erase(TE);
  5819. if (!TryTransform(E).isInvalid()) {
  5820. State.Consumer->resetCorrectionStream();
  5821. TransformCache.erase(TE);
  5822. Res = ExprError();
  5823. break;
  5824. }
  5825. AmbiguousTypoExprs.remove(TE);
  5826. State.Consumer->restoreSavedPosition();
  5827. TransformCache[TE] = Cached;
  5828. }
  5829. SemaRef.DisableTypoCorrection = false;
  5830. // Ensure that all of the TypoExprs within the current Expr have been found.
  5831. if (!Res.isUsable())
  5832. FindTypoExprs(TypoExprs).TraverseStmt(E);
  5833. EmitAllDiagnostics();
  5834. return Res;
  5835. }
  5836. ExprResult TransformTypoExpr(TypoExpr *E) {
  5837. // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
  5838. // cached transformation result if there is one and the TypoExpr isn't the
  5839. // first one that was encountered.
  5840. auto &CacheEntry = TransformCache[E];
  5841. if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
  5842. return CacheEntry;
  5843. }
  5844. auto &State = SemaRef.getTypoExprState(E);
  5845. assert(State.Consumer && "Cannot transform a cleared TypoExpr");
  5846. // For the first TypoExpr and an uncached TypoExpr, find the next likely
  5847. // typo correction and return it.
  5848. while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
  5849. if (InitDecl && TC.getCorrectionDecl() == InitDecl)
  5850. continue;
  5851. ExprResult NE = State.RecoveryHandler ?
  5852. State.RecoveryHandler(SemaRef, E, TC) :
  5853. attemptRecovery(SemaRef, *State.Consumer, TC);
  5854. if (!NE.isInvalid()) {
  5855. // Check whether there may be a second viable correction with the same
  5856. // edit distance; if so, remember this TypoExpr may have an ambiguous
  5857. // correction so it can be more thoroughly vetted later.
  5858. TypoCorrection Next;
  5859. if ((Next = State.Consumer->peekNextCorrection()) &&
  5860. Next.getEditDistance(false) == TC.getEditDistance(false)) {
  5861. AmbiguousTypoExprs.insert(E);
  5862. } else {
  5863. AmbiguousTypoExprs.remove(E);
  5864. }
  5865. assert(!NE.isUnset() &&
  5866. "Typo was transformed into a valid-but-null ExprResult");
  5867. return CacheEntry = NE;
  5868. }
  5869. }
  5870. return CacheEntry = ExprError();
  5871. }
  5872. };
  5873. }
  5874. ExprResult
  5875. Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
  5876. llvm::function_ref<ExprResult(Expr *)> Filter) {
  5877. // If the current evaluation context indicates there are uncorrected typos
  5878. // and the current expression isn't guaranteed to not have typos, try to
  5879. // resolve any TypoExpr nodes that might be in the expression.
  5880. if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
  5881. (E->isTypeDependent() || E->isValueDependent() ||
  5882. E->isInstantiationDependent())) {
  5883. auto TyposInContext = ExprEvalContexts.back().NumTypos;
  5884. assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
  5885. ExprEvalContexts.back().NumTypos = ~0U;
  5886. auto TyposResolved = DelayedTypos.size();
  5887. auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
  5888. ExprEvalContexts.back().NumTypos = TyposInContext;
  5889. TyposResolved -= DelayedTypos.size();
  5890. if (Result.isInvalid() || Result.get() != E) {
  5891. ExprEvalContexts.back().NumTypos -= TyposResolved;
  5892. return Result;
  5893. }
  5894. assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
  5895. }
  5896. return E;
  5897. }
  5898. ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
  5899. bool DiscardedValue,
  5900. bool IsConstexpr,
  5901. bool IsLambdaInitCaptureInitializer) {
  5902. ExprResult FullExpr = FE;
  5903. if (!FullExpr.get())
  5904. return ExprError();
  5905. // If we are an init-expression in a lambdas init-capture, we should not
  5906. // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
  5907. // containing full-expression is done).
  5908. // template<class ... Ts> void test(Ts ... t) {
  5909. // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
  5910. // return a;
  5911. // }() ...);
  5912. // }
  5913. // FIXME: This is a hack. It would be better if we pushed the lambda scope
  5914. // when we parse the lambda introducer, and teach capturing (but not
  5915. // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
  5916. // corresponding class yet (that is, have LambdaScopeInfo either represent a
  5917. // lambda where we've entered the introducer but not the body, or represent a
  5918. // lambda where we've entered the body, depending on where the
  5919. // parser/instantiation has got to).
  5920. if (!IsLambdaInitCaptureInitializer &&
  5921. DiagnoseUnexpandedParameterPack(FullExpr.get()))
  5922. return ExprError();
  5923. // Top-level expressions default to 'id' when we're in a debugger.
  5924. if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
  5925. FullExpr.get()->getType() == Context.UnknownAnyTy) {
  5926. FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
  5927. if (FullExpr.isInvalid())
  5928. return ExprError();
  5929. }
  5930. if (DiscardedValue) {
  5931. FullExpr = CheckPlaceholderExpr(FullExpr.get());
  5932. if (FullExpr.isInvalid())
  5933. return ExprError();
  5934. FullExpr = IgnoredValueConversions(FullExpr.get());
  5935. if (FullExpr.isInvalid())
  5936. return ExprError();
  5937. }
  5938. FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
  5939. if (FullExpr.isInvalid())
  5940. return ExprError();
  5941. CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
  5942. // At the end of this full expression (which could be a deeply nested
  5943. // lambda), if there is a potential capture within the nested lambda,
  5944. // have the outer capture-able lambda try and capture it.
  5945. // Consider the following code:
  5946. // void f(int, int);
  5947. // void f(const int&, double);
  5948. // void foo() {
  5949. // const int x = 10, y = 20;
  5950. // auto L = [=](auto a) {
  5951. // auto M = [=](auto b) {
  5952. // f(x, b); <-- requires x to be captured by L and M
  5953. // f(y, a); <-- requires y to be captured by L, but not all Ms
  5954. // };
  5955. // };
  5956. // }
  5957. // FIXME: Also consider what happens for something like this that involves
  5958. // the gnu-extension statement-expressions or even lambda-init-captures:
  5959. // void f() {
  5960. // const int n = 0;
  5961. // auto L = [&](auto a) {
  5962. // +n + ({ 0; a; });
  5963. // };
  5964. // }
  5965. //
  5966. // Here, we see +n, and then the full-expression 0; ends, so we don't
  5967. // capture n (and instead remove it from our list of potential captures),
  5968. // and then the full-expression +n + ({ 0; }); ends, but it's too late
  5969. // for us to see that we need to capture n after all.
  5970. LambdaScopeInfo *const CurrentLSI = getCurLambda();
  5971. // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
  5972. // even if CurContext is not a lambda call operator. Refer to that Bug Report
  5973. // for an example of the code that might cause this asynchrony.
  5974. // By ensuring we are in the context of a lambda's call operator
  5975. // we can fix the bug (we only need to check whether we need to capture
  5976. // if we are within a lambda's body); but per the comments in that
  5977. // PR, a proper fix would entail :
  5978. // "Alternative suggestion:
  5979. // - Add to Sema an integer holding the smallest (outermost) scope
  5980. // index that we are *lexically* within, and save/restore/set to
  5981. // FunctionScopes.size() in InstantiatingTemplate's
  5982. // constructor/destructor.
  5983. // - Teach the handful of places that iterate over FunctionScopes to
  5984. // stop at the outermost enclosing lexical scope."
  5985. const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
  5986. if (IsInLambdaDeclContext && CurrentLSI &&
  5987. CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
  5988. CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
  5989. *this);
  5990. return MaybeCreateExprWithCleanups(FullExpr);
  5991. }
  5992. StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
  5993. if (!FullStmt) return StmtError();
  5994. return MaybeCreateStmtWithCleanups(FullStmt);
  5995. }
  5996. Sema::IfExistsResult
  5997. Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
  5998. CXXScopeSpec &SS,
  5999. const DeclarationNameInfo &TargetNameInfo) {
  6000. DeclarationName TargetName = TargetNameInfo.getName();
  6001. if (!TargetName)
  6002. return IER_DoesNotExist;
  6003. // If the name itself is dependent, then the result is dependent.
  6004. if (TargetName.isDependentName())
  6005. return IER_Dependent;
  6006. // Do the redeclaration lookup in the current scope.
  6007. LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
  6008. Sema::NotForRedeclaration);
  6009. LookupParsedName(R, S, &SS);
  6010. R.suppressDiagnostics();
  6011. switch (R.getResultKind()) {
  6012. case LookupResult::Found:
  6013. case LookupResult::FoundOverloaded:
  6014. case LookupResult::FoundUnresolvedValue:
  6015. case LookupResult::Ambiguous:
  6016. return IER_Exists;
  6017. case LookupResult::NotFound:
  6018. return IER_DoesNotExist;
  6019. case LookupResult::NotFoundInCurrentInstantiation:
  6020. return IER_Dependent;
  6021. }
  6022. llvm_unreachable("Invalid LookupResult Kind!");
  6023. }
  6024. Sema::IfExistsResult
  6025. Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
  6026. bool IsIfExists, CXXScopeSpec &SS,
  6027. UnqualifiedId &Name) {
  6028. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  6029. // Check for unexpanded parameter packs.
  6030. SmallVector<UnexpandedParameterPack, 4> Unexpanded;
  6031. collectUnexpandedParameterPacks(SS, Unexpanded);
  6032. collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
  6033. if (!Unexpanded.empty()) {
  6034. DiagnoseUnexpandedParameterPacks(KeywordLoc,
  6035. IsIfExists? UPPC_IfExists
  6036. : UPPC_IfNotExists,
  6037. Unexpanded);
  6038. return IER_Error;
  6039. }
  6040. return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
  6041. }