SemaExprCXX.cpp 269 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823
  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. assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
  2789. From = FromRes.get();
  2790. FromType = From->getType();
  2791. break;
  2792. }
  2793. case ICK_Array_To_Pointer:
  2794. FromType = Context.getArrayDecayedType(FromType);
  2795. From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
  2796. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2797. break;
  2798. case ICK_Function_To_Pointer:
  2799. FromType = Context.getPointerType(FromType);
  2800. From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
  2801. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2802. break;
  2803. default:
  2804. llvm_unreachable("Improper first standard conversion");
  2805. }
  2806. // Perform the second implicit conversion
  2807. switch (SCS.Second) {
  2808. case ICK_Identity:
  2809. // C++ [except.spec]p5:
  2810. // [For] assignment to and initialization of pointers to functions,
  2811. // pointers to member functions, and references to functions: the
  2812. // target entity shall allow at least the exceptions allowed by the
  2813. // source value in the assignment or initialization.
  2814. switch (Action) {
  2815. case AA_Assigning:
  2816. case AA_Initializing:
  2817. // Note, function argument passing and returning are initialization.
  2818. case AA_Passing:
  2819. case AA_Returning:
  2820. case AA_Sending:
  2821. case AA_Passing_CFAudited:
  2822. if (CheckExceptionSpecCompatibility(From, ToType))
  2823. return ExprError();
  2824. break;
  2825. case AA_Casting:
  2826. case AA_Converting:
  2827. // Casts and implicit conversions are not initialization, so are not
  2828. // checked for exception specification mismatches.
  2829. break;
  2830. }
  2831. // Nothing else to do.
  2832. break;
  2833. case ICK_NoReturn_Adjustment:
  2834. // If both sides are functions (or pointers/references to them), there could
  2835. // be incompatible exception declarations.
  2836. if (CheckExceptionSpecCompatibility(From, ToType))
  2837. return ExprError();
  2838. From = ImpCastExprToType(From, ToType, CK_NoOp,
  2839. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2840. break;
  2841. case ICK_Integral_Promotion:
  2842. case ICK_Integral_Conversion:
  2843. if (ToType->isBooleanType()) {
  2844. assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
  2845. SCS.Second == ICK_Integral_Promotion &&
  2846. "only enums with fixed underlying type can promote to bool");
  2847. From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
  2848. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2849. } else {
  2850. From = ImpCastExprToType(From, ToType, CK_IntegralCast,
  2851. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2852. }
  2853. break;
  2854. case ICK_Floating_Promotion:
  2855. case ICK_Floating_Conversion:
  2856. From = ImpCastExprToType(From, ToType, CK_FloatingCast,
  2857. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2858. break;
  2859. case ICK_Complex_Promotion:
  2860. case ICK_Complex_Conversion: {
  2861. QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
  2862. QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
  2863. CastKind CK;
  2864. if (FromEl->isRealFloatingType()) {
  2865. if (ToEl->isRealFloatingType())
  2866. CK = CK_FloatingComplexCast;
  2867. else
  2868. CK = CK_FloatingComplexToIntegralComplex;
  2869. } else if (ToEl->isRealFloatingType()) {
  2870. CK = CK_IntegralComplexToFloatingComplex;
  2871. } else {
  2872. CK = CK_IntegralComplexCast;
  2873. }
  2874. From = ImpCastExprToType(From, ToType, CK,
  2875. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2876. break;
  2877. }
  2878. case ICK_Floating_Integral:
  2879. if (ToType->isRealFloatingType())
  2880. From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
  2881. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2882. else
  2883. From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
  2884. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2885. break;
  2886. case ICK_Compatible_Conversion:
  2887. From = ImpCastExprToType(From, ToType, CK_NoOp,
  2888. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2889. break;
  2890. case ICK_Writeback_Conversion:
  2891. case ICK_Pointer_Conversion: {
  2892. if (SCS.IncompatibleObjC && Action != AA_Casting) {
  2893. // Diagnose incompatible Objective-C conversions
  2894. if (Action == AA_Initializing || Action == AA_Assigning)
  2895. Diag(From->getLocStart(),
  2896. diag::ext_typecheck_convert_incompatible_pointer)
  2897. << ToType << From->getType() << Action
  2898. << From->getSourceRange() << 0;
  2899. else
  2900. Diag(From->getLocStart(),
  2901. diag::ext_typecheck_convert_incompatible_pointer)
  2902. << From->getType() << ToType << Action
  2903. << From->getSourceRange() << 0;
  2904. if (From->getType()->isObjCObjectPointerType() &&
  2905. ToType->isObjCObjectPointerType())
  2906. EmitRelatedResultTypeNote(From);
  2907. }
  2908. else if (getLangOpts().ObjCAutoRefCount &&
  2909. !CheckObjCARCUnavailableWeakConversion(ToType,
  2910. From->getType())) {
  2911. if (Action == AA_Initializing)
  2912. Diag(From->getLocStart(),
  2913. diag::err_arc_weak_unavailable_assign);
  2914. else
  2915. Diag(From->getLocStart(),
  2916. diag::err_arc_convesion_of_weak_unavailable)
  2917. << (Action == AA_Casting) << From->getType() << ToType
  2918. << From->getSourceRange();
  2919. }
  2920. CastKind Kind = CK_Invalid;
  2921. CXXCastPath BasePath;
  2922. if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
  2923. return ExprError();
  2924. // Make sure we extend blocks if necessary.
  2925. // FIXME: doing this here is really ugly.
  2926. if (Kind == CK_BlockPointerToObjCPointerCast) {
  2927. ExprResult E = From;
  2928. (void) PrepareCastToObjCObjectPointer(E);
  2929. From = E.get();
  2930. }
  2931. if (getLangOpts().ObjCAutoRefCount)
  2932. CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
  2933. From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
  2934. .get();
  2935. break;
  2936. }
  2937. case ICK_Pointer_Member: {
  2938. CastKind Kind = CK_Invalid;
  2939. CXXCastPath BasePath;
  2940. if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
  2941. return ExprError();
  2942. if (CheckExceptionSpecCompatibility(From, ToType))
  2943. return ExprError();
  2944. // We may not have been able to figure out what this member pointer resolved
  2945. // to up until this exact point. Attempt to lock-in it's inheritance model.
  2946. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2947. RequireCompleteType(From->getExprLoc(), From->getType(), 0);
  2948. RequireCompleteType(From->getExprLoc(), ToType, 0);
  2949. }
  2950. From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
  2951. .get();
  2952. break;
  2953. }
  2954. case ICK_Boolean_Conversion:
  2955. // Perform half-to-boolean conversion via float.
  2956. if (From->getType()->isHalfType()) {
  2957. From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
  2958. FromType = Context.FloatTy;
  2959. }
  2960. From = ImpCastExprToType(From, Context.BoolTy,
  2961. ScalarTypeToBooleanCastKind(FromType),
  2962. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2963. break;
  2964. case ICK_Derived_To_Base: {
  2965. CXXCastPath BasePath;
  2966. if (CheckDerivedToBaseConversion(From->getType(),
  2967. ToType.getNonReferenceType(),
  2968. From->getLocStart(),
  2969. From->getSourceRange(),
  2970. &BasePath,
  2971. CStyle))
  2972. return ExprError();
  2973. From = ImpCastExprToType(From, ToType.getNonReferenceType(),
  2974. CK_DerivedToBase, From->getValueKind(),
  2975. &BasePath, CCK).get();
  2976. break;
  2977. }
  2978. case ICK_Vector_Conversion:
  2979. From = ImpCastExprToType(From, ToType, CK_BitCast,
  2980. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2981. break;
  2982. case ICK_Vector_Splat:
  2983. // Vector splat from any arithmetic type to a vector.
  2984. // Cast to the element type.
  2985. {
  2986. QualType elType = ToType->getAs<ExtVectorType>()->getElementType();
  2987. if (elType != From->getType()) {
  2988. ExprResult E = From;
  2989. From = ImpCastExprToType(From, elType,
  2990. PrepareScalarCast(E, elType)).get();
  2991. }
  2992. From = ImpCastExprToType(From, ToType, CK_VectorSplat,
  2993. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  2994. }
  2995. break;
  2996. case ICK_Complex_Real:
  2997. // Case 1. x -> _Complex y
  2998. if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
  2999. QualType ElType = ToComplex->getElementType();
  3000. bool isFloatingComplex = ElType->isRealFloatingType();
  3001. // x -> y
  3002. if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
  3003. // do nothing
  3004. } else if (From->getType()->isRealFloatingType()) {
  3005. From = ImpCastExprToType(From, ElType,
  3006. isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
  3007. } else {
  3008. assert(From->getType()->isIntegerType());
  3009. From = ImpCastExprToType(From, ElType,
  3010. isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
  3011. }
  3012. // y -> _Complex y
  3013. From = ImpCastExprToType(From, ToType,
  3014. isFloatingComplex ? CK_FloatingRealToComplex
  3015. : CK_IntegralRealToComplex).get();
  3016. // Case 2. _Complex x -> y
  3017. } else {
  3018. const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
  3019. assert(FromComplex);
  3020. QualType ElType = FromComplex->getElementType();
  3021. bool isFloatingComplex = ElType->isRealFloatingType();
  3022. // _Complex x -> x
  3023. From = ImpCastExprToType(From, ElType,
  3024. isFloatingComplex ? CK_FloatingComplexToReal
  3025. : CK_IntegralComplexToReal,
  3026. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3027. // x -> y
  3028. if (Context.hasSameUnqualifiedType(ElType, ToType)) {
  3029. // do nothing
  3030. } else if (ToType->isRealFloatingType()) {
  3031. From = ImpCastExprToType(From, ToType,
  3032. isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
  3033. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3034. } else {
  3035. assert(ToType->isIntegerType());
  3036. From = ImpCastExprToType(From, ToType,
  3037. isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
  3038. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3039. }
  3040. }
  3041. break;
  3042. case ICK_Block_Pointer_Conversion: {
  3043. From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
  3044. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3045. break;
  3046. }
  3047. // HLSL Change Starts
  3048. case ICK_Flat_Conversion:
  3049. case ICK_HLSL_Derived_To_Base:
  3050. case ICK_HLSLVector_Splat:
  3051. case ICK_HLSLVector_Scalar:
  3052. case ICK_HLSLVector_Truncation:
  3053. case ICK_HLSLVector_Conversion:
  3054. From = hlsl::PerformHLSLConversion(this, From, ToType.getUnqualifiedType(), SCS, CCK).get();
  3055. break;
  3056. // HLSL Change Ends
  3057. case ICK_TransparentUnionConversion: {
  3058. ExprResult FromRes = From;
  3059. Sema::AssignConvertType ConvTy =
  3060. CheckTransparentUnionArgumentConstraints(ToType, FromRes);
  3061. if (FromRes.isInvalid())
  3062. return ExprError();
  3063. From = FromRes.get();
  3064. assert ((ConvTy == Sema::Compatible) &&
  3065. "Improper transparent union conversion");
  3066. (void)ConvTy;
  3067. break;
  3068. }
  3069. case ICK_Zero_Event_Conversion:
  3070. From = ImpCastExprToType(From, ToType,
  3071. CK_ZeroToOCLEvent,
  3072. From->getValueKind()).get();
  3073. break;
  3074. case ICK_Lvalue_To_Rvalue:
  3075. case ICK_Array_To_Pointer:
  3076. case ICK_Function_To_Pointer:
  3077. case ICK_Qualification:
  3078. case ICK_Num_Conversion_Kinds:
  3079. llvm_unreachable("Improper second standard conversion");
  3080. }
  3081. switch (SCS.Third) {
  3082. case ICK_Identity:
  3083. // Nothing to do.
  3084. break;
  3085. case ICK_Qualification: {
  3086. // The qualification keeps the category of the inner expression, unless the
  3087. // target type isn't a reference.
  3088. ExprValueKind VK = ToType->isReferenceType() ?
  3089. From->getValueKind() : VK_RValue;
  3090. From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
  3091. CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
  3092. if (SCS.DeprecatedStringLiteralToCharPtr &&
  3093. !getLangOpts().WritableStrings) {
  3094. Diag(From->getLocStart(), getLangOpts().CPlusPlus11
  3095. ? diag::ext_deprecated_string_literal_conversion
  3096. : diag::warn_deprecated_string_literal_conversion)
  3097. << ToType.getNonReferenceType();
  3098. }
  3099. break;
  3100. }
  3101. default:
  3102. llvm_unreachable("Improper third standard conversion");
  3103. }
  3104. // If this conversion sequence involved a scalar -> atomic conversion, perform
  3105. // that conversion now.
  3106. if (!ToAtomicType.isNull()) {
  3107. assert(Context.hasSameType(
  3108. ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
  3109. From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
  3110. VK_RValue, nullptr, CCK).get();
  3111. }
  3112. return From;
  3113. }
  3114. /// \brief Check the completeness of a type in a unary type trait.
  3115. ///
  3116. /// If the particular type trait requires a complete type, tries to complete
  3117. /// it. If completing the type fails, a diagnostic is emitted and false
  3118. /// returned. If completing the type succeeds or no completion was required,
  3119. /// returns true.
  3120. static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
  3121. SourceLocation Loc,
  3122. QualType ArgTy) {
  3123. // C++0x [meta.unary.prop]p3:
  3124. // For all of the class templates X declared in this Clause, instantiating
  3125. // that template with a template argument that is a class template
  3126. // specialization may result in the implicit instantiation of the template
  3127. // argument if and only if the semantics of X require that the argument
  3128. // must be a complete type.
  3129. // We apply this rule to all the type trait expressions used to implement
  3130. // these class templates. We also try to follow any GCC documented behavior
  3131. // in these expressions to ensure portability of standard libraries.
  3132. switch (UTT) {
  3133. default: llvm_unreachable("not a UTT");
  3134. // is_complete_type somewhat obviously cannot require a complete type.
  3135. case UTT_IsCompleteType:
  3136. // Fall-through
  3137. // These traits are modeled on the type predicates in C++0x
  3138. // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
  3139. // requiring a complete type, as whether or not they return true cannot be
  3140. // impacted by the completeness of the type.
  3141. case UTT_IsVoid:
  3142. case UTT_IsIntegral:
  3143. case UTT_IsFloatingPoint:
  3144. case UTT_IsArray:
  3145. case UTT_IsPointer:
  3146. case UTT_IsLvalueReference:
  3147. case UTT_IsRvalueReference:
  3148. case UTT_IsMemberFunctionPointer:
  3149. case UTT_IsMemberObjectPointer:
  3150. case UTT_IsEnum:
  3151. case UTT_IsUnion:
  3152. case UTT_IsClass:
  3153. case UTT_IsFunction:
  3154. case UTT_IsReference:
  3155. case UTT_IsArithmetic:
  3156. case UTT_IsFundamental:
  3157. case UTT_IsObject:
  3158. case UTT_IsScalar:
  3159. case UTT_IsCompound:
  3160. case UTT_IsMemberPointer:
  3161. // Fall-through
  3162. // These traits are modeled on type predicates in C++0x [meta.unary.prop]
  3163. // which requires some of its traits to have the complete type. However,
  3164. // the completeness of the type cannot impact these traits' semantics, and
  3165. // so they don't require it. This matches the comments on these traits in
  3166. // Table 49.
  3167. case UTT_IsConst:
  3168. case UTT_IsVolatile:
  3169. case UTT_IsSigned:
  3170. case UTT_IsUnsigned:
  3171. return true;
  3172. // C++0x [meta.unary.prop] Table 49 requires the following traits to be
  3173. // applied to a complete type.
  3174. case UTT_IsTrivial:
  3175. case UTT_IsTriviallyCopyable:
  3176. case UTT_IsStandardLayout:
  3177. case UTT_IsPOD:
  3178. case UTT_IsLiteral:
  3179. case UTT_IsEmpty:
  3180. case UTT_IsPolymorphic:
  3181. case UTT_IsAbstract:
  3182. case UTT_IsInterfaceClass:
  3183. case UTT_IsDestructible:
  3184. case UTT_IsNothrowDestructible:
  3185. // Fall-through
  3186. // These traits require a complete type.
  3187. case UTT_IsFinal:
  3188. case UTT_IsSealed:
  3189. // These trait expressions are designed to help implement predicates in
  3190. // [meta.unary.prop] despite not being named the same. They are specified
  3191. // by both GCC and the Embarcadero C++ compiler, and require the complete
  3192. // type due to the overarching C++0x type predicates being implemented
  3193. // requiring the complete type.
  3194. case UTT_HasNothrowAssign:
  3195. case UTT_HasNothrowMoveAssign:
  3196. case UTT_HasNothrowConstructor:
  3197. case UTT_HasNothrowCopy:
  3198. case UTT_HasTrivialAssign:
  3199. case UTT_HasTrivialMoveAssign:
  3200. case UTT_HasTrivialDefaultConstructor:
  3201. case UTT_HasTrivialMoveConstructor:
  3202. case UTT_HasTrivialCopy:
  3203. case UTT_HasTrivialDestructor:
  3204. case UTT_HasVirtualDestructor:
  3205. // Arrays of unknown bound are expressly allowed.
  3206. QualType ElTy = ArgTy;
  3207. if (ArgTy->isIncompleteArrayType())
  3208. ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
  3209. // The void type is expressly allowed.
  3210. if (ElTy->isVoidType())
  3211. return true;
  3212. return !S.RequireCompleteType(
  3213. Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
  3214. }
  3215. }
  3216. static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
  3217. Sema &Self, SourceLocation KeyLoc, ASTContext &C,
  3218. bool (CXXRecordDecl::*HasTrivial)() const,
  3219. bool (CXXRecordDecl::*HasNonTrivial)() const,
  3220. bool (CXXMethodDecl::*IsDesiredOp)() const)
  3221. {
  3222. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  3223. if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
  3224. return true;
  3225. DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
  3226. DeclarationNameInfo NameInfo(Name, KeyLoc);
  3227. LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
  3228. if (Self.LookupQualifiedName(Res, RD)) {
  3229. bool FoundOperator = false;
  3230. Res.suppressDiagnostics();
  3231. for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
  3232. Op != OpEnd; ++Op) {
  3233. if (isa<FunctionTemplateDecl>(*Op))
  3234. continue;
  3235. CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
  3236. if((Operator->*IsDesiredOp)()) {
  3237. FoundOperator = true;
  3238. const FunctionProtoType *CPT =
  3239. Operator->getType()->getAs<FunctionProtoType>();
  3240. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  3241. if (!CPT || !CPT->isNothrow(C))
  3242. return false;
  3243. }
  3244. }
  3245. return FoundOperator;
  3246. }
  3247. return false;
  3248. }
  3249. static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
  3250. SourceLocation KeyLoc, QualType T) {
  3251. assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
  3252. ASTContext &C = Self.Context;
  3253. switch(UTT) {
  3254. default: llvm_unreachable("not a UTT");
  3255. // Type trait expressions corresponding to the primary type category
  3256. // predicates in C++0x [meta.unary.cat].
  3257. case UTT_IsVoid:
  3258. return T->isVoidType();
  3259. case UTT_IsIntegral:
  3260. return T->isIntegralType(C);
  3261. case UTT_IsFloatingPoint:
  3262. return T->isFloatingType();
  3263. case UTT_IsArray:
  3264. return T->isArrayType();
  3265. case UTT_IsPointer:
  3266. return T->isPointerType();
  3267. case UTT_IsLvalueReference:
  3268. return T->isLValueReferenceType();
  3269. case UTT_IsRvalueReference:
  3270. return T->isRValueReferenceType();
  3271. case UTT_IsMemberFunctionPointer:
  3272. return T->isMemberFunctionPointerType();
  3273. case UTT_IsMemberObjectPointer:
  3274. return T->isMemberDataPointerType();
  3275. case UTT_IsEnum:
  3276. return T->isEnumeralType();
  3277. case UTT_IsUnion:
  3278. return T->isUnionType();
  3279. case UTT_IsClass:
  3280. return T->isClassType() || T->isStructureType() || T->isInterfaceType();
  3281. case UTT_IsFunction:
  3282. return T->isFunctionType();
  3283. // Type trait expressions which correspond to the convenient composition
  3284. // predicates in C++0x [meta.unary.comp].
  3285. case UTT_IsReference:
  3286. return T->isReferenceType();
  3287. case UTT_IsArithmetic:
  3288. return T->isArithmeticType() && !T->isEnumeralType();
  3289. case UTT_IsFundamental:
  3290. return T->isFundamentalType();
  3291. case UTT_IsObject:
  3292. return T->isObjectType();
  3293. case UTT_IsScalar:
  3294. // Note: semantic analysis depends on Objective-C lifetime types to be
  3295. // considered scalar types. However, such types do not actually behave
  3296. // like scalar types at run time (since they may require retain/release
  3297. // operations), so we report them as non-scalar.
  3298. if (T->isObjCLifetimeType()) {
  3299. switch (T.getObjCLifetime()) {
  3300. case Qualifiers::OCL_None:
  3301. case Qualifiers::OCL_ExplicitNone:
  3302. return true;
  3303. case Qualifiers::OCL_Strong:
  3304. case Qualifiers::OCL_Weak:
  3305. case Qualifiers::OCL_Autoreleasing:
  3306. return false;
  3307. }
  3308. }
  3309. return T->isScalarType();
  3310. case UTT_IsCompound:
  3311. return T->isCompoundType();
  3312. case UTT_IsMemberPointer:
  3313. return T->isMemberPointerType();
  3314. // Type trait expressions which correspond to the type property predicates
  3315. // in C++0x [meta.unary.prop].
  3316. case UTT_IsConst:
  3317. return T.isConstQualified();
  3318. case UTT_IsVolatile:
  3319. return T.isVolatileQualified();
  3320. case UTT_IsTrivial:
  3321. return T.isTrivialType(Self.Context);
  3322. case UTT_IsTriviallyCopyable:
  3323. return T.isTriviallyCopyableType(Self.Context);
  3324. case UTT_IsStandardLayout:
  3325. return T->isStandardLayoutType();
  3326. case UTT_IsPOD:
  3327. return T.isPODType(Self.Context);
  3328. case UTT_IsLiteral:
  3329. return T->isLiteralType(Self.Context);
  3330. case UTT_IsEmpty:
  3331. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3332. return !RD->isUnion() && RD->isEmpty();
  3333. return false;
  3334. case UTT_IsPolymorphic:
  3335. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3336. return RD->isPolymorphic();
  3337. return false;
  3338. case UTT_IsAbstract:
  3339. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3340. return RD->isAbstract();
  3341. return false;
  3342. case UTT_IsInterfaceClass:
  3343. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3344. return RD->isInterface();
  3345. return false;
  3346. case UTT_IsFinal:
  3347. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3348. return RD->hasAttr<FinalAttr>();
  3349. return false;
  3350. case UTT_IsSealed:
  3351. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3352. if (FinalAttr *FA = RD->getAttr<FinalAttr>())
  3353. return FA->isSpelledAsSealed();
  3354. return false;
  3355. case UTT_IsSigned:
  3356. return T->isSignedIntegerType();
  3357. case UTT_IsUnsigned:
  3358. return T->isUnsignedIntegerType();
  3359. // Type trait expressions which query classes regarding their construction,
  3360. // destruction, and copying. Rather than being based directly on the
  3361. // related type predicates in the standard, they are specified by both
  3362. // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
  3363. // specifications.
  3364. //
  3365. // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
  3366. // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
  3367. //
  3368. // Note that these builtins do not behave as documented in g++: if a class
  3369. // has both a trivial and a non-trivial special member of a particular kind,
  3370. // they return false! For now, we emulate this behavior.
  3371. // FIXME: This appears to be a g++ bug: more complex cases reveal that it
  3372. // does not correctly compute triviality in the presence of multiple special
  3373. // members of the same kind. Revisit this once the g++ bug is fixed.
  3374. case UTT_HasTrivialDefaultConstructor:
  3375. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3376. // If __is_pod (type) is true then the trait is true, else if type is
  3377. // a cv class or union type (or array thereof) with a trivial default
  3378. // constructor ([class.ctor]) then the trait is true, else it is false.
  3379. if (T.isPODType(Self.Context))
  3380. return true;
  3381. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  3382. return RD->hasTrivialDefaultConstructor() &&
  3383. !RD->hasNonTrivialDefaultConstructor();
  3384. return false;
  3385. case UTT_HasTrivialMoveConstructor:
  3386. // This trait is implemented by MSVC 2012 and needed to parse the
  3387. // standard library headers. Specifically this is used as the logic
  3388. // behind std::is_trivially_move_constructible (20.9.4.3).
  3389. if (T.isPODType(Self.Context))
  3390. return true;
  3391. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  3392. return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
  3393. return false;
  3394. case UTT_HasTrivialCopy:
  3395. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3396. // If __is_pod (type) is true or type is a reference type then
  3397. // the trait is true, else if type is a cv class or union type
  3398. // with a trivial copy constructor ([class.copy]) then the trait
  3399. // is true, else it is false.
  3400. if (T.isPODType(Self.Context) || T->isReferenceType())
  3401. return true;
  3402. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3403. return RD->hasTrivialCopyConstructor() &&
  3404. !RD->hasNonTrivialCopyConstructor();
  3405. return false;
  3406. case UTT_HasTrivialMoveAssign:
  3407. // This trait is implemented by MSVC 2012 and needed to parse the
  3408. // standard library headers. Specifically it is used as the logic
  3409. // behind std::is_trivially_move_assignable (20.9.4.3)
  3410. if (T.isPODType(Self.Context))
  3411. return true;
  3412. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  3413. return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
  3414. return false;
  3415. case UTT_HasTrivialAssign:
  3416. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3417. // If type is const qualified or is a reference type then the
  3418. // trait is false. Otherwise if __is_pod (type) is true then the
  3419. // trait is true, else if type is a cv class or union type with
  3420. // a trivial copy assignment ([class.copy]) then the trait is
  3421. // true, else it is false.
  3422. // Note: the const and reference restrictions are interesting,
  3423. // given that const and reference members don't prevent a class
  3424. // from having a trivial copy assignment operator (but do cause
  3425. // errors if the copy assignment operator is actually used, q.v.
  3426. // [class.copy]p12).
  3427. if (T.isConstQualified())
  3428. return false;
  3429. if (T.isPODType(Self.Context))
  3430. return true;
  3431. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3432. return RD->hasTrivialCopyAssignment() &&
  3433. !RD->hasNonTrivialCopyAssignment();
  3434. return false;
  3435. case UTT_IsDestructible:
  3436. case UTT_IsNothrowDestructible:
  3437. // FIXME: Implement UTT_IsDestructible and UTT_IsNothrowDestructible.
  3438. // For now, let's fall through.
  3439. case UTT_HasTrivialDestructor:
  3440. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
  3441. // If __is_pod (type) is true or type is a reference type
  3442. // then the trait is true, else if type is a cv class or union
  3443. // type (or array thereof) with a trivial destructor
  3444. // ([class.dtor]) then the trait is true, else it is
  3445. // false.
  3446. if (T.isPODType(Self.Context) || T->isReferenceType())
  3447. return true;
  3448. // Objective-C++ ARC: autorelease types don't require destruction.
  3449. if (T->isObjCLifetimeType() &&
  3450. T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
  3451. return true;
  3452. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  3453. return RD->hasTrivialDestructor();
  3454. return false;
  3455. // TODO: Propagate nothrowness for implicitly declared special members.
  3456. case UTT_HasNothrowAssign:
  3457. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3458. // If type is const qualified or is a reference type then the
  3459. // trait is false. Otherwise if __has_trivial_assign (type)
  3460. // is true then the trait is true, else if type is a cv class
  3461. // or union type with copy assignment operators that are known
  3462. // not to throw an exception then the trait is true, else it is
  3463. // false.
  3464. if (C.getBaseElementType(T).isConstQualified())
  3465. return false;
  3466. if (T->isReferenceType())
  3467. return false;
  3468. if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
  3469. return true;
  3470. if (const RecordType *RT = T->getAs<RecordType>())
  3471. return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
  3472. &CXXRecordDecl::hasTrivialCopyAssignment,
  3473. &CXXRecordDecl::hasNonTrivialCopyAssignment,
  3474. &CXXMethodDecl::isCopyAssignmentOperator);
  3475. return false;
  3476. case UTT_HasNothrowMoveAssign:
  3477. // This trait is implemented by MSVC 2012 and needed to parse the
  3478. // standard library headers. Specifically this is used as the logic
  3479. // behind std::is_nothrow_move_assignable (20.9.4.3).
  3480. if (T.isPODType(Self.Context))
  3481. return true;
  3482. if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
  3483. return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
  3484. &CXXRecordDecl::hasTrivialMoveAssignment,
  3485. &CXXRecordDecl::hasNonTrivialMoveAssignment,
  3486. &CXXMethodDecl::isMoveAssignmentOperator);
  3487. return false;
  3488. case UTT_HasNothrowCopy:
  3489. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3490. // If __has_trivial_copy (type) is true then the trait is true, else
  3491. // if type is a cv class or union type with copy constructors that are
  3492. // known not to throw an exception then the trait is true, else it is
  3493. // false.
  3494. if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
  3495. return true;
  3496. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  3497. if (RD->hasTrivialCopyConstructor() &&
  3498. !RD->hasNonTrivialCopyConstructor())
  3499. return true;
  3500. bool FoundConstructor = false;
  3501. unsigned FoundTQs;
  3502. DeclContext::lookup_result R = Self.LookupConstructors(RD);
  3503. for (DeclContext::lookup_iterator Con = R.begin(),
  3504. ConEnd = R.end(); Con != ConEnd; ++Con) {
  3505. // A template constructor is never a copy constructor.
  3506. // FIXME: However, it may actually be selected at the actual overload
  3507. // resolution point.
  3508. if (isa<FunctionTemplateDecl>(*Con))
  3509. continue;
  3510. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
  3511. if (Constructor->isCopyConstructor(FoundTQs)) {
  3512. FoundConstructor = true;
  3513. const FunctionProtoType *CPT
  3514. = Constructor->getType()->getAs<FunctionProtoType>();
  3515. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  3516. if (!CPT)
  3517. return false;
  3518. // TODO: check whether evaluating default arguments can throw.
  3519. // For now, we'll be conservative and assume that they can throw.
  3520. if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 1)
  3521. return false;
  3522. }
  3523. }
  3524. return FoundConstructor;
  3525. }
  3526. return false;
  3527. case UTT_HasNothrowConstructor:
  3528. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
  3529. // If __has_trivial_constructor (type) is true then the trait is
  3530. // true, else if type is a cv class or union type (or array
  3531. // thereof) with a default constructor that is known not to
  3532. // throw an exception then the trait is true, else it is false.
  3533. if (T.isPODType(C) || T->isObjCLifetimeType())
  3534. return true;
  3535. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
  3536. if (RD->hasTrivialDefaultConstructor() &&
  3537. !RD->hasNonTrivialDefaultConstructor())
  3538. return true;
  3539. bool FoundConstructor = false;
  3540. DeclContext::lookup_result R = Self.LookupConstructors(RD);
  3541. for (DeclContext::lookup_iterator Con = R.begin(),
  3542. ConEnd = R.end(); Con != ConEnd; ++Con) {
  3543. // FIXME: In C++0x, a constructor template can be a default constructor.
  3544. if (isa<FunctionTemplateDecl>(*Con))
  3545. continue;
  3546. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
  3547. if (Constructor->isDefaultConstructor()) {
  3548. FoundConstructor = true;
  3549. const FunctionProtoType *CPT
  3550. = Constructor->getType()->getAs<FunctionProtoType>();
  3551. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  3552. if (!CPT)
  3553. return false;
  3554. // FIXME: check whether evaluating default arguments can throw.
  3555. // For now, we'll be conservative and assume that they can throw.
  3556. if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 0)
  3557. return false;
  3558. }
  3559. }
  3560. return FoundConstructor;
  3561. }
  3562. return false;
  3563. case UTT_HasVirtualDestructor:
  3564. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  3565. // If type is a class type with a virtual destructor ([class.dtor])
  3566. // then the trait is true, else it is false.
  3567. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3568. if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
  3569. return Destructor->isVirtual();
  3570. return false;
  3571. // These type trait expressions are modeled on the specifications for the
  3572. // Embarcadero C++0x type trait functions:
  3573. // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
  3574. case UTT_IsCompleteType:
  3575. // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
  3576. // Returns True if and only if T is a complete type at the point of the
  3577. // function call.
  3578. return !T->isIncompleteType();
  3579. }
  3580. }
  3581. /// \brief Determine whether T has a non-trivial Objective-C lifetime in
  3582. /// ARC mode.
  3583. static bool hasNontrivialObjCLifetime(QualType T) {
  3584. switch (T.getObjCLifetime()) {
  3585. case Qualifiers::OCL_ExplicitNone:
  3586. return false;
  3587. case Qualifiers::OCL_Strong:
  3588. case Qualifiers::OCL_Weak:
  3589. case Qualifiers::OCL_Autoreleasing:
  3590. return true;
  3591. case Qualifiers::OCL_None:
  3592. return T->isObjCLifetimeType();
  3593. }
  3594. llvm_unreachable("Unknown ObjC lifetime qualifier");
  3595. }
  3596. static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
  3597. QualType RhsT, SourceLocation KeyLoc);
  3598. static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
  3599. ArrayRef<TypeSourceInfo *> Args,
  3600. SourceLocation RParenLoc) {
  3601. if (Kind <= UTT_Last)
  3602. return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
  3603. if (Kind <= BTT_Last)
  3604. return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
  3605. Args[1]->getType(), RParenLoc);
  3606. switch (Kind) {
  3607. case clang::TT_IsConstructible:
  3608. case clang::TT_IsNothrowConstructible:
  3609. case clang::TT_IsTriviallyConstructible: {
  3610. // C++11 [meta.unary.prop]:
  3611. // is_trivially_constructible is defined as:
  3612. //
  3613. // is_constructible<T, Args...>::value is true and the variable
  3614. // definition for is_constructible, as defined below, is known to call
  3615. // no operation that is not trivial.
  3616. //
  3617. // The predicate condition for a template specialization
  3618. // is_constructible<T, Args...> shall be satisfied if and only if the
  3619. // following variable definition would be well-formed for some invented
  3620. // variable t:
  3621. //
  3622. // T t(create<Args>()...);
  3623. assert(!Args.empty());
  3624. // Precondition: T and all types in the parameter pack Args shall be
  3625. // complete types, (possibly cv-qualified) void, or arrays of
  3626. // unknown bound.
  3627. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3628. QualType ArgTy = Args[I]->getType();
  3629. if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
  3630. continue;
  3631. if (S.RequireCompleteType(KWLoc, ArgTy,
  3632. diag::err_incomplete_type_used_in_type_trait_expr))
  3633. return false;
  3634. }
  3635. // Make sure the first argument is a complete type.
  3636. if (Args[0]->getType()->isIncompleteType())
  3637. return false;
  3638. // Make sure the first argument is not an abstract type.
  3639. CXXRecordDecl *RD = Args[0]->getType()->getAsCXXRecordDecl();
  3640. if (RD && RD->isAbstract())
  3641. return false;
  3642. SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
  3643. SmallVector<Expr *, 2> ArgExprs;
  3644. ArgExprs.reserve(Args.size() - 1);
  3645. for (unsigned I = 1, N = Args.size(); I != N; ++I) {
  3646. QualType T = Args[I]->getType();
  3647. if (T->isObjectType() || T->isFunctionType())
  3648. T = S.Context.getRValueReferenceType(T);
  3649. OpaqueArgExprs.push_back(
  3650. OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
  3651. T.getNonLValueExprType(S.Context),
  3652. Expr::getValueKindForType(T)));
  3653. }
  3654. for (Expr &E : OpaqueArgExprs)
  3655. ArgExprs.push_back(&E);
  3656. // Perform the initialization in an unevaluated context within a SFINAE
  3657. // trap at translation unit scope.
  3658. EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
  3659. Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
  3660. Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
  3661. InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
  3662. InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
  3663. RParenLoc));
  3664. InitializationSequence Init(S, To, InitKind, ArgExprs);
  3665. if (Init.Failed())
  3666. return false;
  3667. ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
  3668. if (Result.isInvalid() || SFINAE.hasErrorOccurred())
  3669. return false;
  3670. if (Kind == clang::TT_IsConstructible)
  3671. return true;
  3672. if (Kind == clang::TT_IsNothrowConstructible)
  3673. return S.canThrow(Result.get()) == CT_Cannot;
  3674. if (Kind == clang::TT_IsTriviallyConstructible) {
  3675. // Under Objective-C ARC, if the destination has non-trivial Objective-C
  3676. // lifetime, this is a non-trivial construction.
  3677. if (S.getLangOpts().ObjCAutoRefCount &&
  3678. hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
  3679. return false;
  3680. // The initialization succeeded; now make sure there are no non-trivial
  3681. // calls.
  3682. return !Result.get()->hasNonTrivialCall(S.Context);
  3683. }
  3684. llvm_unreachable("unhandled type trait");
  3685. return false;
  3686. }
  3687. default: llvm_unreachable("not a TT");
  3688. }
  3689. return false;
  3690. }
  3691. ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
  3692. ArrayRef<TypeSourceInfo *> Args,
  3693. SourceLocation RParenLoc) {
  3694. QualType ResultType = Context.getLogicalOperationType();
  3695. if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
  3696. *this, Kind, KWLoc, Args[0]->getType()))
  3697. return ExprError();
  3698. bool Dependent = false;
  3699. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3700. if (Args[I]->getType()->isDependentType()) {
  3701. Dependent = true;
  3702. break;
  3703. }
  3704. }
  3705. bool Result = false;
  3706. if (!Dependent)
  3707. Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
  3708. return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
  3709. RParenLoc, Result);
  3710. }
  3711. ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
  3712. ArrayRef<ParsedType> Args,
  3713. SourceLocation RParenLoc) {
  3714. SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
  3715. ConvertedArgs.reserve(Args.size());
  3716. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3717. TypeSourceInfo *TInfo;
  3718. QualType T = GetTypeFromParser(Args[I], &TInfo);
  3719. if (!TInfo)
  3720. TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
  3721. ConvertedArgs.push_back(TInfo);
  3722. }
  3723. return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
  3724. }
  3725. static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
  3726. QualType RhsT, SourceLocation KeyLoc) {
  3727. assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
  3728. "Cannot evaluate traits of dependent types");
  3729. switch(BTT) {
  3730. case BTT_IsBaseOf: {
  3731. // C++0x [meta.rel]p2
  3732. // Base is a base class of Derived without regard to cv-qualifiers or
  3733. // Base and Derived are not unions and name the same class type without
  3734. // regard to cv-qualifiers.
  3735. const RecordType *lhsRecord = LhsT->getAs<RecordType>();
  3736. if (!lhsRecord) return false;
  3737. const RecordType *rhsRecord = RhsT->getAs<RecordType>();
  3738. if (!rhsRecord) return false;
  3739. assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
  3740. == (lhsRecord == rhsRecord));
  3741. if (lhsRecord == rhsRecord)
  3742. return !lhsRecord->getDecl()->isUnion();
  3743. // C++0x [meta.rel]p2:
  3744. // If Base and Derived are class types and are different types
  3745. // (ignoring possible cv-qualifiers) then Derived shall be a
  3746. // complete type.
  3747. if (Self.RequireCompleteType(KeyLoc, RhsT,
  3748. diag::err_incomplete_type_used_in_type_trait_expr))
  3749. return false;
  3750. return cast<CXXRecordDecl>(rhsRecord->getDecl())
  3751. ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
  3752. }
  3753. case BTT_IsSame:
  3754. return Self.Context.hasSameType(LhsT, RhsT);
  3755. case BTT_TypeCompatible:
  3756. return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
  3757. RhsT.getUnqualifiedType());
  3758. case BTT_IsConvertible:
  3759. case BTT_IsConvertibleTo: {
  3760. // C++0x [meta.rel]p4:
  3761. // Given the following function prototype:
  3762. //
  3763. // template <class T>
  3764. // typename add_rvalue_reference<T>::type create();
  3765. //
  3766. // the predicate condition for a template specialization
  3767. // is_convertible<From, To> shall be satisfied if and only if
  3768. // the return expression in the following code would be
  3769. // well-formed, including any implicit conversions to the return
  3770. // type of the function:
  3771. //
  3772. // To test() {
  3773. // return create<From>();
  3774. // }
  3775. //
  3776. // Access checking is performed as if in a context unrelated to To and
  3777. // From. Only the validity of the immediate context of the expression
  3778. // of the return-statement (including conversions to the return type)
  3779. // is considered.
  3780. //
  3781. // We model the initialization as a copy-initialization of a temporary
  3782. // of the appropriate type, which for this expression is identical to the
  3783. // return statement (since NRVO doesn't apply).
  3784. // Functions aren't allowed to return function or array types.
  3785. if (RhsT->isFunctionType() || RhsT->isArrayType())
  3786. return false;
  3787. // A return statement in a void function must have void type.
  3788. if (RhsT->isVoidType())
  3789. return LhsT->isVoidType();
  3790. // A function definition requires a complete, non-abstract return type.
  3791. if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
  3792. Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
  3793. return false;
  3794. // Compute the result of add_rvalue_reference.
  3795. if (LhsT->isObjectType() || LhsT->isFunctionType())
  3796. LhsT = Self.Context.getRValueReferenceType(LhsT);
  3797. // Build a fake source and destination for initialization.
  3798. InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
  3799. OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
  3800. Expr::getValueKindForType(LhsT));
  3801. Expr *FromPtr = &From;
  3802. InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
  3803. SourceLocation()));
  3804. // Perform the initialization in an unevaluated context within a SFINAE
  3805. // trap at translation unit scope.
  3806. EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
  3807. Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
  3808. Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
  3809. InitializationSequence Init(Self, To, Kind, FromPtr);
  3810. if (Init.Failed())
  3811. return false;
  3812. ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
  3813. return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
  3814. }
  3815. case BTT_IsNothrowAssignable:
  3816. case BTT_IsTriviallyAssignable: {
  3817. // C++11 [meta.unary.prop]p3:
  3818. // is_trivially_assignable is defined as:
  3819. // is_assignable<T, U>::value is true and the assignment, as defined by
  3820. // is_assignable, is known to call no operation that is not trivial
  3821. //
  3822. // is_assignable is defined as:
  3823. // The expression declval<T>() = declval<U>() is well-formed when
  3824. // treated as an unevaluated operand (Clause 5).
  3825. //
  3826. // For both, T and U shall be complete types, (possibly cv-qualified)
  3827. // void, or arrays of unknown bound.
  3828. if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
  3829. Self.RequireCompleteType(KeyLoc, LhsT,
  3830. diag::err_incomplete_type_used_in_type_trait_expr))
  3831. return false;
  3832. if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
  3833. Self.RequireCompleteType(KeyLoc, RhsT,
  3834. diag::err_incomplete_type_used_in_type_trait_expr))
  3835. return false;
  3836. // cv void is never assignable.
  3837. if (LhsT->isVoidType() || RhsT->isVoidType())
  3838. return false;
  3839. // Build expressions that emulate the effect of declval<T>() and
  3840. // declval<U>().
  3841. if (LhsT->isObjectType() || LhsT->isFunctionType())
  3842. LhsT = Self.Context.getRValueReferenceType(LhsT);
  3843. if (RhsT->isObjectType() || RhsT->isFunctionType())
  3844. RhsT = Self.Context.getRValueReferenceType(RhsT);
  3845. OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
  3846. Expr::getValueKindForType(LhsT));
  3847. OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
  3848. Expr::getValueKindForType(RhsT));
  3849. // Attempt the assignment in an unevaluated context within a SFINAE
  3850. // trap at translation unit scope.
  3851. EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
  3852. Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
  3853. Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
  3854. ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
  3855. &Rhs);
  3856. if (Result.isInvalid() || SFINAE.hasErrorOccurred())
  3857. return false;
  3858. if (BTT == BTT_IsNothrowAssignable)
  3859. return Self.canThrow(Result.get()) == CT_Cannot;
  3860. if (BTT == BTT_IsTriviallyAssignable) {
  3861. // Under Objective-C ARC, if the destination has non-trivial Objective-C
  3862. // lifetime, this is a non-trivial assignment.
  3863. if (Self.getLangOpts().ObjCAutoRefCount &&
  3864. hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
  3865. return false;
  3866. return !Result.get()->hasNonTrivialCall(Self.Context);
  3867. }
  3868. llvm_unreachable("unhandled type trait");
  3869. return false;
  3870. }
  3871. default: llvm_unreachable("not a BTT");
  3872. }
  3873. llvm_unreachable("Unknown type trait or not implemented");
  3874. }
  3875. ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
  3876. SourceLocation KWLoc,
  3877. ParsedType Ty,
  3878. Expr* DimExpr,
  3879. SourceLocation RParen) {
  3880. TypeSourceInfo *TSInfo;
  3881. QualType T = GetTypeFromParser(Ty, &TSInfo);
  3882. if (!TSInfo)
  3883. TSInfo = Context.getTrivialTypeSourceInfo(T);
  3884. return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
  3885. }
  3886. static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
  3887. QualType T, Expr *DimExpr,
  3888. SourceLocation KeyLoc) {
  3889. assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
  3890. switch(ATT) {
  3891. case ATT_ArrayRank:
  3892. if (T->isArrayType()) {
  3893. unsigned Dim = 0;
  3894. while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
  3895. ++Dim;
  3896. T = AT->getElementType();
  3897. }
  3898. return Dim;
  3899. }
  3900. return 0;
  3901. case ATT_ArrayExtent: {
  3902. llvm::APSInt Value;
  3903. uint64_t Dim;
  3904. if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
  3905. diag::err_dimension_expr_not_constant_integer,
  3906. false).isInvalid())
  3907. return 0;
  3908. if (Value.isSigned() && Value.isNegative()) {
  3909. Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
  3910. << DimExpr->getSourceRange();
  3911. return 0;
  3912. }
  3913. Dim = Value.getLimitedValue();
  3914. if (T->isArrayType()) {
  3915. unsigned D = 0;
  3916. bool Matched = false;
  3917. while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
  3918. if (Dim == D) {
  3919. Matched = true;
  3920. break;
  3921. }
  3922. ++D;
  3923. T = AT->getElementType();
  3924. }
  3925. if (Matched && T->isArrayType()) {
  3926. if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
  3927. return CAT->getSize().getLimitedValue();
  3928. }
  3929. }
  3930. return 0;
  3931. }
  3932. }
  3933. llvm_unreachable("Unknown type trait or not implemented");
  3934. }
  3935. ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
  3936. SourceLocation KWLoc,
  3937. TypeSourceInfo *TSInfo,
  3938. Expr* DimExpr,
  3939. SourceLocation RParen) {
  3940. QualType T = TSInfo->getType();
  3941. // FIXME: This should likely be tracked as an APInt to remove any host
  3942. // assumptions about the width of size_t on the target.
  3943. uint64_t Value = 0;
  3944. if (!T->isDependentType())
  3945. Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
  3946. // While the specification for these traits from the Embarcadero C++
  3947. // compiler's documentation says the return type is 'unsigned int', Clang
  3948. // returns 'size_t'. On Windows, the primary platform for the Embarcadero
  3949. // compiler, there is no difference. On several other platforms this is an
  3950. // important distinction.
  3951. return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
  3952. RParen, Context.getSizeType());
  3953. }
  3954. ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
  3955. SourceLocation KWLoc,
  3956. Expr *Queried,
  3957. SourceLocation RParen) {
  3958. // If error parsing the expression, ignore.
  3959. if (!Queried)
  3960. return ExprError();
  3961. ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
  3962. return Result;
  3963. }
  3964. static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
  3965. switch (ET) {
  3966. case ET_IsLValueExpr: return E->isLValue();
  3967. case ET_IsRValueExpr: return E->isRValue();
  3968. }
  3969. llvm_unreachable("Expression trait not covered by switch");
  3970. }
  3971. ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
  3972. SourceLocation KWLoc,
  3973. Expr *Queried,
  3974. SourceLocation RParen) {
  3975. if (Queried->isTypeDependent()) {
  3976. // Delay type-checking for type-dependent expressions.
  3977. } else if (Queried->getType()->isPlaceholderType()) {
  3978. ExprResult PE = CheckPlaceholderExpr(Queried);
  3979. if (PE.isInvalid()) return ExprError();
  3980. return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
  3981. }
  3982. bool Value = EvaluateExpressionTrait(ET, Queried);
  3983. return new (Context)
  3984. ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
  3985. }
  3986. QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
  3987. ExprValueKind &VK,
  3988. SourceLocation Loc,
  3989. bool isIndirect) {
  3990. assert(!LHS.get()->getType()->isPlaceholderType() &&
  3991. !RHS.get()->getType()->isPlaceholderType() &&
  3992. "placeholders should have been weeded out by now");
  3993. // The LHS undergoes lvalue conversions if this is ->*.
  3994. if (isIndirect) {
  3995. LHS = DefaultLvalueConversion(LHS.get());
  3996. if (LHS.isInvalid()) return QualType();
  3997. }
  3998. // The RHS always undergoes lvalue conversions.
  3999. RHS = DefaultLvalueConversion(RHS.get());
  4000. if (RHS.isInvalid()) return QualType();
  4001. const char *OpSpelling = isIndirect ? "->*" : ".*";
  4002. // C++ 5.5p2
  4003. // The binary operator .* [p3: ->*] binds its second operand, which shall
  4004. // be of type "pointer to member of T" (where T is a completely-defined
  4005. // class type) [...]
  4006. QualType RHSType = RHS.get()->getType();
  4007. const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
  4008. if (!MemPtr) {
  4009. Diag(Loc, diag::err_bad_memptr_rhs)
  4010. << OpSpelling << RHSType << RHS.get()->getSourceRange();
  4011. return QualType();
  4012. }
  4013. QualType Class(MemPtr->getClass(), 0);
  4014. // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
  4015. // member pointer points must be completely-defined. However, there is no
  4016. // reason for this semantic distinction, and the rule is not enforced by
  4017. // other compilers. Therefore, we do not check this property, as it is
  4018. // likely to be considered a defect.
  4019. // C++ 5.5p2
  4020. // [...] to its first operand, which shall be of class T or of a class of
  4021. // which T is an unambiguous and accessible base class. [p3: a pointer to
  4022. // such a class]
  4023. QualType LHSType = LHS.get()->getType();
  4024. if (isIndirect) {
  4025. if (const PointerType *Ptr = LHSType->getAs<PointerType>())
  4026. LHSType = Ptr->getPointeeType();
  4027. else {
  4028. Diag(Loc, diag::err_bad_memptr_lhs)
  4029. << OpSpelling << 1 << LHSType
  4030. << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
  4031. return QualType();
  4032. }
  4033. }
  4034. if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
  4035. // If we want to check the hierarchy, we need a complete type.
  4036. if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
  4037. OpSpelling, (int)isIndirect)) {
  4038. return QualType();
  4039. }
  4040. if (!IsDerivedFrom(LHSType, Class)) {
  4041. Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
  4042. << (int)isIndirect << LHS.get()->getType();
  4043. return QualType();
  4044. }
  4045. CXXCastPath BasePath;
  4046. if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
  4047. SourceRange(LHS.get()->getLocStart(),
  4048. RHS.get()->getLocEnd()),
  4049. &BasePath))
  4050. return QualType();
  4051. // Cast LHS to type of use.
  4052. QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
  4053. ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
  4054. LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
  4055. &BasePath);
  4056. }
  4057. if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
  4058. // Diagnose use of pointer-to-member type which when used as
  4059. // the functional cast in a pointer-to-member expression.
  4060. Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
  4061. return QualType();
  4062. }
  4063. // C++ 5.5p2
  4064. // The result is an object or a function of the type specified by the
  4065. // second operand.
  4066. // The cv qualifiers are the union of those in the pointer and the left side,
  4067. // in accordance with 5.5p5 and 5.2.5.
  4068. QualType Result = MemPtr->getPointeeType();
  4069. Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
  4070. // C++0x [expr.mptr.oper]p6:
  4071. // In a .* expression whose object expression is an rvalue, the program is
  4072. // ill-formed if the second operand is a pointer to member function with
  4073. // ref-qualifier &. In a ->* expression or in a .* expression whose object
  4074. // expression is an lvalue, the program is ill-formed if the second operand
  4075. // is a pointer to member function with ref-qualifier &&.
  4076. if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
  4077. switch (Proto->getRefQualifier()) {
  4078. case RQ_None:
  4079. // Do nothing
  4080. break;
  4081. case RQ_LValue:
  4082. if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
  4083. Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
  4084. << RHSType << 1 << LHS.get()->getSourceRange();
  4085. break;
  4086. case RQ_RValue:
  4087. if (isIndirect || !LHS.get()->Classify(Context).isRValue())
  4088. Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
  4089. << RHSType << 0 << LHS.get()->getSourceRange();
  4090. break;
  4091. }
  4092. }
  4093. // C++ [expr.mptr.oper]p6:
  4094. // The result of a .* expression whose second operand is a pointer
  4095. // to a data member is of the same value category as its
  4096. // first operand. The result of a .* expression whose second
  4097. // operand is a pointer to a member function is a prvalue. The
  4098. // result of an ->* expression is an lvalue if its second operand
  4099. // is a pointer to data member and a prvalue otherwise.
  4100. if (Result->isFunctionType()) {
  4101. VK = VK_RValue;
  4102. return Context.BoundMemberTy;
  4103. } else if (isIndirect) {
  4104. VK = VK_LValue;
  4105. } else {
  4106. VK = LHS.get()->getValueKind();
  4107. }
  4108. return Result;
  4109. }
  4110. /// \brief Try to convert a type to another according to C++0x 5.16p3.
  4111. ///
  4112. /// This is part of the parameter validation for the ? operator. If either
  4113. /// value operand is a class type, the two operands are attempted to be
  4114. /// converted to each other. This function does the conversion in one direction.
  4115. /// It returns true if the program is ill-formed and has already been diagnosed
  4116. /// as such.
  4117. static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
  4118. SourceLocation QuestionLoc,
  4119. bool &HaveConversion,
  4120. QualType &ToType) {
  4121. HaveConversion = false;
  4122. ToType = To->getType();
  4123. InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
  4124. SourceLocation());
  4125. // C++0x 5.16p3
  4126. // The process for determining whether an operand expression E1 of type T1
  4127. // can be converted to match an operand expression E2 of type T2 is defined
  4128. // as follows:
  4129. // -- If E2 is an lvalue:
  4130. bool ToIsLvalue = To->isLValue();
  4131. if (ToIsLvalue) {
  4132. // E1 can be converted to match E2 if E1 can be implicitly converted to
  4133. // type "lvalue reference to T2", subject to the constraint that in the
  4134. // conversion the reference must bind directly to E1.
  4135. QualType T = Self.Context.getLValueReferenceType(ToType);
  4136. InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
  4137. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4138. if (InitSeq.isDirectReferenceBinding()) {
  4139. ToType = T;
  4140. HaveConversion = true;
  4141. return false;
  4142. }
  4143. if (InitSeq.isAmbiguous())
  4144. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4145. }
  4146. // -- If E2 is an rvalue, or if the conversion above cannot be done:
  4147. // -- if E1 and E2 have class type, and the underlying class types are
  4148. // the same or one is a base class of the other:
  4149. QualType FTy = From->getType();
  4150. QualType TTy = To->getType();
  4151. const RecordType *FRec = FTy->getAs<RecordType>();
  4152. const RecordType *TRec = TTy->getAs<RecordType>();
  4153. bool FDerivedFromT = FRec && TRec && FRec != TRec &&
  4154. Self.IsDerivedFrom(FTy, TTy);
  4155. if (FRec && TRec &&
  4156. (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
  4157. // E1 can be converted to match E2 if the class of T2 is the
  4158. // same type as, or a base class of, the class of T1, and
  4159. // [cv2 > cv1].
  4160. if (FRec == TRec || FDerivedFromT) {
  4161. if (TTy.isAtLeastAsQualifiedAs(FTy)) {
  4162. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
  4163. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4164. if (InitSeq) {
  4165. HaveConversion = true;
  4166. return false;
  4167. }
  4168. if (InitSeq.isAmbiguous())
  4169. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4170. }
  4171. }
  4172. return false;
  4173. }
  4174. // -- Otherwise: E1 can be converted to match E2 if E1 can be
  4175. // implicitly converted to the type that expression E2 would have
  4176. // if E2 were converted to an rvalue (or the type it has, if E2 is
  4177. // an rvalue).
  4178. //
  4179. // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
  4180. // to the array-to-pointer or function-to-pointer conversions.
  4181. if (!TTy->getAs<TagType>())
  4182. TTy = TTy.getUnqualifiedType();
  4183. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
  4184. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4185. HaveConversion = !InitSeq.Failed();
  4186. ToType = TTy;
  4187. if (InitSeq.isAmbiguous())
  4188. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4189. return false;
  4190. }
  4191. /// \brief Try to find a common type for two according to C++0x 5.16p5.
  4192. ///
  4193. /// This is part of the parameter validation for the ? operator. If either
  4194. /// value operand is a class type, overload resolution is used to find a
  4195. /// conversion to a common type.
  4196. static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
  4197. SourceLocation QuestionLoc) {
  4198. Expr *Args[2] = { LHS.get(), RHS.get() };
  4199. OverloadCandidateSet CandidateSet(QuestionLoc,
  4200. OverloadCandidateSet::CSK_Operator);
  4201. Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
  4202. CandidateSet);
  4203. OverloadCandidateSet::iterator Best;
  4204. switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
  4205. case OR_Success: {
  4206. // We found a match. Perform the conversions on the arguments and move on.
  4207. ExprResult LHSRes =
  4208. Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
  4209. Best->Conversions[0], Sema::AA_Converting);
  4210. if (LHSRes.isInvalid())
  4211. break;
  4212. LHS = LHSRes;
  4213. ExprResult RHSRes =
  4214. Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
  4215. Best->Conversions[1], Sema::AA_Converting);
  4216. if (RHSRes.isInvalid())
  4217. break;
  4218. RHS = RHSRes;
  4219. if (Best->Function)
  4220. Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
  4221. return false;
  4222. }
  4223. case OR_No_Viable_Function:
  4224. // Emit a better diagnostic if one of the expressions is a null pointer
  4225. // constant and the other is a pointer type. In this case, the user most
  4226. // likely forgot to take the address of the other expression.
  4227. if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  4228. return true;
  4229. Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  4230. << LHS.get()->getType() << RHS.get()->getType()
  4231. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4232. return true;
  4233. case OR_Ambiguous:
  4234. Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
  4235. << LHS.get()->getType() << RHS.get()->getType()
  4236. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4237. // FIXME: Print the possible common types by printing the return types of
  4238. // the viable candidates.
  4239. break;
  4240. case OR_Deleted:
  4241. llvm_unreachable("Conditional operator has only built-in overloads");
  4242. }
  4243. return true;
  4244. }
  4245. /// \brief Perform an "extended" implicit conversion as returned by
  4246. /// TryClassUnification.
  4247. static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
  4248. InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
  4249. InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
  4250. SourceLocation());
  4251. Expr *Arg = E.get();
  4252. InitializationSequence InitSeq(Self, Entity, Kind, Arg);
  4253. ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
  4254. if (Result.isInvalid())
  4255. return true;
  4256. E = Result;
  4257. return false;
  4258. }
  4259. /// \brief Check the operands of ?: under C++ semantics.
  4260. ///
  4261. /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
  4262. /// extension. In this case, LHS == Cond. (But they're not aliases.)
  4263. QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  4264. ExprResult &RHS, ExprValueKind &VK,
  4265. ExprObjectKind &OK,
  4266. SourceLocation QuestionLoc) {
  4267. // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
  4268. // interface pointers.
  4269. // C++11 [expr.cond]p1
  4270. // The first expression is contextually converted to bool.
  4271. if (!Cond.get()->isTypeDependent()) {
  4272. ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
  4273. if (CondRes.isInvalid())
  4274. return QualType();
  4275. Cond = CondRes;
  4276. }
  4277. // Assume r-value.
  4278. VK = VK_RValue;
  4279. OK = OK_Ordinary;
  4280. // Either of the arguments dependent?
  4281. if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
  4282. return Context.DependentTy;
  4283. // C++11 [expr.cond]p2
  4284. // If either the second or the third operand has type (cv) void, ...
  4285. QualType LTy = LHS.get()->getType();
  4286. QualType RTy = RHS.get()->getType();
  4287. bool LVoid = LTy->isVoidType();
  4288. bool RVoid = RTy->isVoidType();
  4289. if (LVoid || RVoid) {
  4290. // ... one of the following shall hold:
  4291. // -- The second or the third operand (but not both) is a (possibly
  4292. // parenthesized) throw-expression; the result is of the type
  4293. // and value category of the other.
  4294. bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
  4295. bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
  4296. if (LThrow != RThrow) {
  4297. Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
  4298. VK = NonThrow->getValueKind();
  4299. // DR (no number yet): the result is a bit-field if the
  4300. // non-throw-expression operand is a bit-field.
  4301. OK = NonThrow->getObjectKind();
  4302. return NonThrow->getType();
  4303. }
  4304. // -- Both the second and third operands have type void; the result is of
  4305. // type void and is a prvalue.
  4306. if (LVoid && RVoid)
  4307. return Context.VoidTy;
  4308. // Neither holds, error.
  4309. Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
  4310. << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
  4311. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4312. return QualType();
  4313. }
  4314. // Neither is void.
  4315. // C++11 [expr.cond]p3
  4316. // Otherwise, if the second and third operand have different types, and
  4317. // either has (cv) class type [...] an attempt is made to convert each of
  4318. // those operands to the type of the other.
  4319. if (!Context.hasSameType(LTy, RTy) &&
  4320. (LTy->isRecordType() || RTy->isRecordType())) {
  4321. // These return true if a single direction is already ambiguous.
  4322. QualType L2RType, R2LType;
  4323. bool HaveL2R, HaveR2L;
  4324. if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
  4325. return QualType();
  4326. if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
  4327. return QualType();
  4328. // If both can be converted, [...] the program is ill-formed.
  4329. if (HaveL2R && HaveR2L) {
  4330. Diag(QuestionLoc, diag::err_conditional_ambiguous)
  4331. << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4332. return QualType();
  4333. }
  4334. // If exactly one conversion is possible, that conversion is applied to
  4335. // the chosen operand and the converted operands are used in place of the
  4336. // original operands for the remainder of this section.
  4337. if (HaveL2R) {
  4338. if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
  4339. return QualType();
  4340. LTy = LHS.get()->getType();
  4341. } else if (HaveR2L) {
  4342. if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
  4343. return QualType();
  4344. RTy = RHS.get()->getType();
  4345. }
  4346. }
  4347. // C++11 [expr.cond]p3
  4348. // if both are glvalues of the same value category and the same type except
  4349. // for cv-qualification, an attempt is made to convert each of those
  4350. // operands to the type of the other.
  4351. ExprValueKind LVK = LHS.get()->getValueKind();
  4352. ExprValueKind RVK = RHS.get()->getValueKind();
  4353. if (!Context.hasSameType(LTy, RTy) &&
  4354. Context.hasSameUnqualifiedType(LTy, RTy) &&
  4355. LVK == RVK && LVK != VK_RValue) {
  4356. // Since the unqualified types are reference-related and we require the
  4357. // result to be as if a reference bound directly, the only conversion
  4358. // we can perform is to add cv-qualifiers.
  4359. Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
  4360. Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
  4361. if (RCVR.isStrictSupersetOf(LCVR)) {
  4362. LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
  4363. LTy = LHS.get()->getType();
  4364. }
  4365. else if (LCVR.isStrictSupersetOf(RCVR)) {
  4366. RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
  4367. RTy = RHS.get()->getType();
  4368. }
  4369. }
  4370. // C++11 [expr.cond]p4
  4371. // If the second and third operands are glvalues of the same value
  4372. // category and have the same type, the result is of that type and
  4373. // value category and it is a bit-field if the second or the third
  4374. // operand is a bit-field, or if both are bit-fields.
  4375. // We only extend this to bitfields, not to the crazy other kinds of
  4376. // l-values.
  4377. bool Same = Context.hasSameType(LTy, RTy);
  4378. if (Same && LVK == RVK && LVK != VK_RValue &&
  4379. LHS.get()->isOrdinaryOrBitFieldObject() &&
  4380. RHS.get()->isOrdinaryOrBitFieldObject()) {
  4381. VK = LHS.get()->getValueKind();
  4382. if (LHS.get()->getObjectKind() == OK_BitField ||
  4383. RHS.get()->getObjectKind() == OK_BitField)
  4384. OK = OK_BitField;
  4385. return LTy;
  4386. }
  4387. // C++11 [expr.cond]p5
  4388. // Otherwise, the result is a prvalue. If the second and third operands
  4389. // do not have the same type, and either has (cv) class type, ...
  4390. if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
  4391. // ... overload resolution is used to determine the conversions (if any)
  4392. // to be applied to the operands. If the overload resolution fails, the
  4393. // program is ill-formed.
  4394. if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
  4395. return QualType();
  4396. }
  4397. // C++11 [expr.cond]p6
  4398. // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
  4399. // conversions are performed on the second and third operands.
  4400. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  4401. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  4402. if (LHS.isInvalid() || RHS.isInvalid())
  4403. return QualType();
  4404. LTy = LHS.get()->getType();
  4405. RTy = RHS.get()->getType();
  4406. // After those conversions, one of the following shall hold:
  4407. // -- The second and third operands have the same type; the result
  4408. // is of that type. If the operands have class type, the result
  4409. // is a prvalue temporary of the result type, which is
  4410. // copy-initialized from either the second operand or the third
  4411. // operand depending on the value of the first operand.
  4412. if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
  4413. if (LTy->isRecordType()) {
  4414. // The operands have class type. Make a temporary copy.
  4415. if (RequireNonAbstractType(QuestionLoc, LTy,
  4416. diag::err_allocation_of_abstract_type))
  4417. return QualType();
  4418. InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
  4419. ExprResult LHSCopy = PerformCopyInitialization(Entity,
  4420. SourceLocation(),
  4421. LHS);
  4422. if (LHSCopy.isInvalid())
  4423. return QualType();
  4424. ExprResult RHSCopy = PerformCopyInitialization(Entity,
  4425. SourceLocation(),
  4426. RHS);
  4427. if (RHSCopy.isInvalid())
  4428. return QualType();
  4429. LHS = LHSCopy;
  4430. RHS = RHSCopy;
  4431. }
  4432. return LTy;
  4433. }
  4434. // Extension: conditional operator involving vector types.
  4435. if (LTy->isVectorType() || RTy->isVectorType())
  4436. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  4437. /*AllowBothBool*/true,
  4438. /*AllowBoolConversions*/false);
  4439. // -- The second and third operands have arithmetic or enumeration type;
  4440. // the usual arithmetic conversions are performed to bring them to a
  4441. // common type, and the result is of that type.
  4442. if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
  4443. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  4444. if (LHS.isInvalid() || RHS.isInvalid())
  4445. return QualType();
  4446. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  4447. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  4448. return ResTy;
  4449. }
  4450. // -- The second and third operands have pointer type, or one has pointer
  4451. // type and the other is a null pointer constant, or both are null
  4452. // pointer constants, at least one of which is non-integral; pointer
  4453. // conversions and qualification conversions are performed to bring them
  4454. // to their composite pointer type. The result is of the composite
  4455. // pointer type.
  4456. // -- The second and third operands have pointer to member type, or one has
  4457. // pointer to member type and the other is a null pointer constant;
  4458. // pointer to member conversions and qualification conversions are
  4459. // performed to bring them to a common type, whose cv-qualification
  4460. // shall match the cv-qualification of either the second or the third
  4461. // operand. The result is of the common type.
  4462. bool NonStandardCompositeType = false;
  4463. QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
  4464. isSFINAEContext() ? nullptr
  4465. : &NonStandardCompositeType);
  4466. if (!Composite.isNull()) {
  4467. if (NonStandardCompositeType)
  4468. Diag(QuestionLoc,
  4469. diag::ext_typecheck_cond_incompatible_operands_nonstandard)
  4470. << LTy << RTy << Composite
  4471. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4472. return Composite;
  4473. }
  4474. // Similarly, attempt to find composite type of two objective-c pointers.
  4475. Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
  4476. if (!Composite.isNull())
  4477. return Composite;
  4478. // Check if we are using a null with a non-pointer type.
  4479. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  4480. return QualType();
  4481. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  4482. << LHS.get()->getType() << RHS.get()->getType()
  4483. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4484. return QualType();
  4485. }
  4486. /// \brief Find a merged pointer type and convert the two expressions to it.
  4487. ///
  4488. /// This finds the composite pointer type (or member pointer type) for @p E1
  4489. /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
  4490. /// type and returns it.
  4491. /// It does not emit diagnostics.
  4492. ///
  4493. /// \param Loc The location of the operator requiring these two expressions to
  4494. /// be converted to the composite pointer type.
  4495. ///
  4496. /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
  4497. /// a non-standard (but still sane) composite type to which both expressions
  4498. /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
  4499. /// will be set true.
  4500. QualType Sema::FindCompositePointerType(SourceLocation Loc,
  4501. Expr *&E1, Expr *&E2,
  4502. bool *NonStandardCompositeType) {
  4503. if (NonStandardCompositeType)
  4504. *NonStandardCompositeType = false;
  4505. assert(getLangOpts().CPlusPlus && "This function assumes C++");
  4506. QualType T1 = E1->getType(), T2 = E2->getType();
  4507. // C++11 5.9p2
  4508. // Pointer conversions and qualification conversions are performed on
  4509. // pointer operands to bring them to their composite pointer type. If
  4510. // one operand is a null pointer constant, the composite pointer type is
  4511. // std::nullptr_t if the other operand is also a null pointer constant or,
  4512. // if the other operand is a pointer, the type of the other operand.
  4513. if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
  4514. !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
  4515. if (T1->isNullPtrType() &&
  4516. E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  4517. E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
  4518. return T1;
  4519. }
  4520. if (T2->isNullPtrType() &&
  4521. E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  4522. E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
  4523. return T2;
  4524. }
  4525. return QualType();
  4526. }
  4527. if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  4528. if (T2->isMemberPointerType())
  4529. E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
  4530. else
  4531. E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
  4532. return T2;
  4533. }
  4534. if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  4535. if (T1->isMemberPointerType())
  4536. E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
  4537. else
  4538. E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
  4539. return T1;
  4540. }
  4541. // Now both have to be pointers or member pointers.
  4542. if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
  4543. (!T2->isPointerType() && !T2->isMemberPointerType()))
  4544. return QualType();
  4545. // Otherwise, of one of the operands has type "pointer to cv1 void," then
  4546. // the other has type "pointer to cv2 T" and the composite pointer type is
  4547. // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
  4548. // Otherwise, the composite pointer type is a pointer type similar to the
  4549. // type of one of the operands, with a cv-qualification signature that is
  4550. // the union of the cv-qualification signatures of the operand types.
  4551. // In practice, the first part here is redundant; it's subsumed by the second.
  4552. // What we do here is, we build the two possible composite types, and try the
  4553. // conversions in both directions. If only one works, or if the two composite
  4554. // types are the same, we have succeeded.
  4555. // FIXME: extended qualifiers?
  4556. typedef SmallVector<unsigned, 4> QualifierVector;
  4557. QualifierVector QualifierUnion;
  4558. typedef SmallVector<std::pair<const Type *, const Type *>, 4>
  4559. ContainingClassVector;
  4560. ContainingClassVector MemberOfClass;
  4561. QualType Composite1 = Context.getCanonicalType(T1),
  4562. Composite2 = Context.getCanonicalType(T2);
  4563. unsigned NeedConstBefore = 0;
  4564. do {
  4565. const PointerType *Ptr1, *Ptr2;
  4566. if ((Ptr1 = Composite1->getAs<PointerType>()) &&
  4567. (Ptr2 = Composite2->getAs<PointerType>())) {
  4568. Composite1 = Ptr1->getPointeeType();
  4569. Composite2 = Ptr2->getPointeeType();
  4570. // If we're allowed to create a non-standard composite type, keep track
  4571. // of where we need to fill in additional 'const' qualifiers.
  4572. if (NonStandardCompositeType &&
  4573. Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
  4574. NeedConstBefore = QualifierUnion.size();
  4575. QualifierUnion.push_back(
  4576. Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
  4577. MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
  4578. continue;
  4579. }
  4580. const MemberPointerType *MemPtr1, *MemPtr2;
  4581. if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
  4582. (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
  4583. Composite1 = MemPtr1->getPointeeType();
  4584. Composite2 = MemPtr2->getPointeeType();
  4585. // If we're allowed to create a non-standard composite type, keep track
  4586. // of where we need to fill in additional 'const' qualifiers.
  4587. if (NonStandardCompositeType &&
  4588. Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
  4589. NeedConstBefore = QualifierUnion.size();
  4590. QualifierUnion.push_back(
  4591. Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
  4592. MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
  4593. MemPtr2->getClass()));
  4594. continue;
  4595. }
  4596. // FIXME: block pointer types?
  4597. // Cannot unwrap any more types.
  4598. break;
  4599. } while (true);
  4600. if (NeedConstBefore && NonStandardCompositeType) {
  4601. // Extension: Add 'const' to qualifiers that come before the first qualifier
  4602. // mismatch, so that our (non-standard!) composite type meets the
  4603. // requirements of C++ [conv.qual]p4 bullet 3.
  4604. for (unsigned I = 0; I != NeedConstBefore; ++I) {
  4605. if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
  4606. QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
  4607. *NonStandardCompositeType = true;
  4608. }
  4609. }
  4610. }
  4611. // Rewrap the composites as pointers or member pointers with the union CVRs.
  4612. ContainingClassVector::reverse_iterator MOC
  4613. = MemberOfClass.rbegin();
  4614. for (QualifierVector::reverse_iterator
  4615. I = QualifierUnion.rbegin(),
  4616. E = QualifierUnion.rend();
  4617. I != E; (void)++I, ++MOC) {
  4618. Qualifiers Quals = Qualifiers::fromCVRMask(*I);
  4619. if (MOC->first && MOC->second) {
  4620. // Rebuild member pointer type
  4621. Composite1 = Context.getMemberPointerType(
  4622. Context.getQualifiedType(Composite1, Quals),
  4623. MOC->first);
  4624. Composite2 = Context.getMemberPointerType(
  4625. Context.getQualifiedType(Composite2, Quals),
  4626. MOC->second);
  4627. } else {
  4628. // Rebuild pointer type
  4629. Composite1
  4630. = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
  4631. Composite2
  4632. = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
  4633. }
  4634. }
  4635. // Try to convert to the first composite pointer type.
  4636. InitializedEntity Entity1
  4637. = InitializedEntity::InitializeTemporary(Composite1);
  4638. InitializationKind Kind
  4639. = InitializationKind::CreateCopy(Loc, SourceLocation());
  4640. InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
  4641. InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
  4642. if (E1ToC1 && E2ToC1) {
  4643. // Conversion to Composite1 is viable.
  4644. if (!Context.hasSameType(Composite1, Composite2)) {
  4645. // Composite2 is a different type from Composite1. Check whether
  4646. // Composite2 is also viable.
  4647. InitializedEntity Entity2
  4648. = InitializedEntity::InitializeTemporary(Composite2);
  4649. InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
  4650. InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
  4651. if (E1ToC2 && E2ToC2) {
  4652. // Both Composite1 and Composite2 are viable and are different;
  4653. // this is an ambiguity.
  4654. return QualType();
  4655. }
  4656. }
  4657. // Convert E1 to Composite1
  4658. ExprResult E1Result
  4659. = E1ToC1.Perform(*this, Entity1, Kind, E1);
  4660. if (E1Result.isInvalid())
  4661. return QualType();
  4662. E1 = E1Result.getAs<Expr>();
  4663. // Convert E2 to Composite1
  4664. ExprResult E2Result
  4665. = E2ToC1.Perform(*this, Entity1, Kind, E2);
  4666. if (E2Result.isInvalid())
  4667. return QualType();
  4668. E2 = E2Result.getAs<Expr>();
  4669. return Composite1;
  4670. }
  4671. // Check whether Composite2 is viable.
  4672. InitializedEntity Entity2
  4673. = InitializedEntity::InitializeTemporary(Composite2);
  4674. InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
  4675. InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
  4676. if (!E1ToC2 || !E2ToC2)
  4677. return QualType();
  4678. // Convert E1 to Composite2
  4679. ExprResult E1Result
  4680. = E1ToC2.Perform(*this, Entity2, Kind, E1);
  4681. if (E1Result.isInvalid())
  4682. return QualType();
  4683. E1 = E1Result.getAs<Expr>();
  4684. // Convert E2 to Composite2
  4685. ExprResult E2Result
  4686. = E2ToC2.Perform(*this, Entity2, Kind, E2);
  4687. if (E2Result.isInvalid())
  4688. return QualType();
  4689. E2 = E2Result.getAs<Expr>();
  4690. return Composite2;
  4691. }
  4692. ExprResult Sema::MaybeBindToTemporary(Expr *E) {
  4693. if (!E)
  4694. return ExprError();
  4695. assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
  4696. // If the result is a glvalue, we shouldn't bind it.
  4697. if (!E->isRValue())
  4698. return E;
  4699. // In ARC, calls that return a retainable type can return retained,
  4700. // in which case we have to insert a consuming cast.
  4701. if (getLangOpts().ObjCAutoRefCount &&
  4702. E->getType()->isObjCRetainableType()) {
  4703. bool ReturnsRetained;
  4704. // For actual calls, we compute this by examining the type of the
  4705. // called value.
  4706. if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
  4707. Expr *Callee = Call->getCallee()->IgnoreParens();
  4708. QualType T = Callee->getType();
  4709. if (T == Context.BoundMemberTy) {
  4710. // Handle pointer-to-members.
  4711. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
  4712. T = BinOp->getRHS()->getType();
  4713. else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
  4714. T = Mem->getMemberDecl()->getType();
  4715. }
  4716. if (const PointerType *Ptr = T->getAs<PointerType>())
  4717. T = Ptr->getPointeeType();
  4718. else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
  4719. T = Ptr->getPointeeType();
  4720. else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
  4721. T = MemPtr->getPointeeType();
  4722. const FunctionType *FTy = T->getAs<FunctionType>();
  4723. assert(FTy && "call to value not of function type?");
  4724. ReturnsRetained = FTy->getExtInfo().getProducesResult();
  4725. // ActOnStmtExpr arranges things so that StmtExprs of retainable
  4726. // type always produce a +1 object.
  4727. } else if (isa<StmtExpr>(E)) {
  4728. ReturnsRetained = true;
  4729. // We hit this case with the lambda conversion-to-block optimization;
  4730. // we don't want any extra casts here.
  4731. } else if (isa<CastExpr>(E) &&
  4732. isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
  4733. return E;
  4734. // For message sends and property references, we try to find an
  4735. // actual method. FIXME: we should infer retention by selector in
  4736. // cases where we don't have an actual method.
  4737. } else {
  4738. ObjCMethodDecl *D = nullptr;
  4739. if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
  4740. D = Send->getMethodDecl();
  4741. } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
  4742. D = BoxedExpr->getBoxingMethod();
  4743. } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
  4744. D = ArrayLit->getArrayWithObjectsMethod();
  4745. } else if (ObjCDictionaryLiteral *DictLit
  4746. = dyn_cast<ObjCDictionaryLiteral>(E)) {
  4747. D = DictLit->getDictWithObjectsMethod();
  4748. }
  4749. ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
  4750. // Don't do reclaims on performSelector calls; despite their
  4751. // return type, the invoked method doesn't necessarily actually
  4752. // return an object.
  4753. if (!ReturnsRetained &&
  4754. D && D->getMethodFamily() == OMF_performSelector)
  4755. return E;
  4756. }
  4757. // Don't reclaim an object of Class type.
  4758. if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
  4759. return E;
  4760. ExprNeedsCleanups = true;
  4761. CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
  4762. : CK_ARCReclaimReturnedObject);
  4763. return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
  4764. VK_RValue);
  4765. }
  4766. if (!getLangOpts().CPlusPlus)
  4767. return E;
  4768. // Search for the base element type (cf. ASTContext::getBaseElementType) with
  4769. // a fast path for the common case that the type is directly a RecordType.
  4770. const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
  4771. const RecordType *RT = nullptr;
  4772. while (!RT) {
  4773. switch (T->getTypeClass()) {
  4774. case Type::Record:
  4775. RT = cast<RecordType>(T);
  4776. break;
  4777. case Type::ConstantArray:
  4778. case Type::IncompleteArray:
  4779. case Type::VariableArray:
  4780. case Type::DependentSizedArray:
  4781. T = cast<ArrayType>(T)->getElementType().getTypePtr();
  4782. break;
  4783. default:
  4784. return E;
  4785. }
  4786. }
  4787. // That should be enough to guarantee that this type is complete, if we're
  4788. // not processing a decltype expression.
  4789. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  4790. if (RD->isInvalidDecl() || RD->isDependentContext())
  4791. return E;
  4792. bool IsDecltype = ExprEvalContexts.back().IsDecltype;
  4793. CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
  4794. if (Destructor) {
  4795. MarkFunctionReferenced(E->getExprLoc(), Destructor);
  4796. CheckDestructorAccess(E->getExprLoc(), Destructor,
  4797. PDiag(diag::err_access_dtor_temp)
  4798. << E->getType());
  4799. if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
  4800. return ExprError();
  4801. // If destructor is trivial, we can avoid the extra copy.
  4802. if (Destructor->isTrivial())
  4803. return E;
  4804. // We need a cleanup, but we don't need to remember the temporary.
  4805. ExprNeedsCleanups = true;
  4806. }
  4807. CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
  4808. CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
  4809. if (IsDecltype)
  4810. ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
  4811. return Bind;
  4812. }
  4813. ExprResult
  4814. Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
  4815. if (SubExpr.isInvalid())
  4816. return ExprError();
  4817. return MaybeCreateExprWithCleanups(SubExpr.get());
  4818. }
  4819. Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
  4820. assert(SubExpr && "subexpression can't be null!");
  4821. CleanupVarDeclMarking();
  4822. unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
  4823. assert(ExprCleanupObjects.size() >= FirstCleanup);
  4824. assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
  4825. if (!ExprNeedsCleanups)
  4826. return SubExpr;
  4827. auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
  4828. ExprCleanupObjects.size() - FirstCleanup);
  4829. Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
  4830. DiscardCleanupsInEvaluationContext();
  4831. return E;
  4832. }
  4833. Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
  4834. assert(SubStmt && "sub-statement can't be null!");
  4835. CleanupVarDeclMarking();
  4836. if (!ExprNeedsCleanups)
  4837. return SubStmt;
  4838. // FIXME: In order to attach the temporaries, wrap the statement into
  4839. // a StmtExpr; currently this is only used for asm statements.
  4840. // This is hacky, either create a new CXXStmtWithTemporaries statement or
  4841. // a new AsmStmtWithTemporaries.
  4842. CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
  4843. SourceLocation(),
  4844. SourceLocation());
  4845. Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
  4846. SourceLocation());
  4847. return MaybeCreateExprWithCleanups(E);
  4848. }
  4849. /// Process the expression contained within a decltype. For such expressions,
  4850. /// certain semantic checks on temporaries are delayed until this point, and
  4851. /// are omitted for the 'topmost' call in the decltype expression. If the
  4852. /// topmost call bound a temporary, strip that temporary off the expression.
  4853. ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
  4854. assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
  4855. // C++11 [expr.call]p11:
  4856. // If a function call is a prvalue of object type,
  4857. // -- if the function call is either
  4858. // -- the operand of a decltype-specifier, or
  4859. // -- the right operand of a comma operator that is the operand of a
  4860. // decltype-specifier,
  4861. // a temporary object is not introduced for the prvalue.
  4862. // Recursively rebuild ParenExprs and comma expressions to strip out the
  4863. // outermost CXXBindTemporaryExpr, if any.
  4864. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  4865. ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
  4866. if (SubExpr.isInvalid())
  4867. return ExprError();
  4868. if (SubExpr.get() == PE->getSubExpr())
  4869. return E;
  4870. return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
  4871. }
  4872. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  4873. if (BO->getOpcode() == BO_Comma) {
  4874. ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
  4875. if (RHS.isInvalid())
  4876. return ExprError();
  4877. if (RHS.get() == BO->getRHS())
  4878. return E;
  4879. return new (Context) BinaryOperator(
  4880. BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
  4881. BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
  4882. }
  4883. }
  4884. CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
  4885. CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
  4886. : nullptr;
  4887. if (TopCall)
  4888. E = TopCall;
  4889. else
  4890. TopBind = nullptr;
  4891. // Disable the special decltype handling now.
  4892. ExprEvalContexts.back().IsDecltype = false;
  4893. // In MS mode, don't perform any extra checking of call return types within a
  4894. // decltype expression.
  4895. if (getLangOpts().MSVCCompat)
  4896. return E;
  4897. // Perform the semantic checks we delayed until this point.
  4898. for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
  4899. I != N; ++I) {
  4900. CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
  4901. if (Call == TopCall)
  4902. continue;
  4903. if (CheckCallReturnType(Call->getCallReturnType(Context),
  4904. Call->getLocStart(),
  4905. Call, Call->getDirectCallee()))
  4906. return ExprError();
  4907. }
  4908. // Now all relevant types are complete, check the destructors are accessible
  4909. // and non-deleted, and annotate them on the temporaries.
  4910. for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
  4911. I != N; ++I) {
  4912. CXXBindTemporaryExpr *Bind =
  4913. ExprEvalContexts.back().DelayedDecltypeBinds[I];
  4914. if (Bind == TopBind)
  4915. continue;
  4916. CXXTemporary *Temp = Bind->getTemporary();
  4917. CXXRecordDecl *RD =
  4918. Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  4919. CXXDestructorDecl *Destructor = LookupDestructor(RD);
  4920. Temp->setDestructor(Destructor);
  4921. MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
  4922. CheckDestructorAccess(Bind->getExprLoc(), Destructor,
  4923. PDiag(diag::err_access_dtor_temp)
  4924. << Bind->getType());
  4925. if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
  4926. return ExprError();
  4927. // We need a cleanup, but we don't need to remember the temporary.
  4928. ExprNeedsCleanups = true;
  4929. }
  4930. // Possibly strip off the top CXXBindTemporaryExpr.
  4931. return E;
  4932. }
  4933. /// Note a set of 'operator->' functions that were used for a member access.
  4934. static void noteOperatorArrows(Sema &S,
  4935. ArrayRef<FunctionDecl *> OperatorArrows) {
  4936. unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
  4937. // FIXME: Make this configurable?
  4938. unsigned Limit = 9;
  4939. if (OperatorArrows.size() > Limit) {
  4940. // Produce Limit-1 normal notes and one 'skipping' note.
  4941. SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
  4942. SkipCount = OperatorArrows.size() - (Limit - 1);
  4943. }
  4944. for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
  4945. if (I == SkipStart) {
  4946. S.Diag(OperatorArrows[I]->getLocation(),
  4947. diag::note_operator_arrows_suppressed)
  4948. << SkipCount;
  4949. I += SkipCount;
  4950. } else {
  4951. S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
  4952. << OperatorArrows[I]->getCallResultType();
  4953. ++I;
  4954. }
  4955. }
  4956. }
  4957. ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
  4958. SourceLocation OpLoc,
  4959. tok::TokenKind OpKind,
  4960. ParsedType &ObjectType,
  4961. bool &MayBePseudoDestructor) {
  4962. // Since this might be a postfix expression, get rid of ParenListExprs.
  4963. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
  4964. if (Result.isInvalid()) return ExprError();
  4965. Base = Result.get();
  4966. Result = CheckPlaceholderExpr(Base);
  4967. if (Result.isInvalid()) return ExprError();
  4968. Base = Result.get();
  4969. // HLSL Change Starts
  4970. assert(OpKind == tok::arrow || OpKind == tok::period);
  4971. if (getLangOpts().HLSL && OpKind != tok::period) {
  4972. // continue processing as if it was a period accessor
  4973. Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  4974. OpKind = tok::period;
  4975. }
  4976. // HLSL Change Ends
  4977. QualType BaseType = Base->getType();
  4978. MayBePseudoDestructor = false;
  4979. if (BaseType->isDependentType()) {
  4980. // If we have a pointer to a dependent type and are using the -> operator,
  4981. // the object type is the type that the pointer points to. We might still
  4982. // have enough information about that type to do something useful.
  4983. if (OpKind == tok::arrow)
  4984. if (const PointerType *Ptr = BaseType->getAs<PointerType>())
  4985. BaseType = Ptr->getPointeeType();
  4986. ObjectType = ParsedType::make(BaseType);
  4987. MayBePseudoDestructor = true;
  4988. return Base;
  4989. }
  4990. // C++ [over.match.oper]p8:
  4991. // [...] When operator->returns, the operator-> is applied to the value
  4992. // returned, with the original second operand.
  4993. if (OpKind == tok::arrow) {
  4994. QualType StartingType = BaseType;
  4995. bool NoArrowOperatorFound = false;
  4996. bool FirstIteration = true;
  4997. FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
  4998. // The set of types we've considered so far.
  4999. llvm::SmallPtrSet<CanQualType,8> CTypes;
  5000. SmallVector<FunctionDecl*, 8> OperatorArrows;
  5001. CTypes.insert(Context.getCanonicalType(BaseType));
  5002. while (BaseType->isRecordType()) {
  5003. if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
  5004. Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
  5005. << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
  5006. noteOperatorArrows(*this, OperatorArrows);
  5007. Diag(OpLoc, diag::note_operator_arrow_depth)
  5008. << getLangOpts().ArrowDepth;
  5009. return ExprError();
  5010. }
  5011. Result = BuildOverloadedArrowExpr(
  5012. S, Base, OpLoc,
  5013. // When in a template specialization and on the first loop iteration,
  5014. // potentially give the default diagnostic (with the fixit in a
  5015. // separate note) instead of having the error reported back to here
  5016. // and giving a diagnostic with a fixit attached to the error itself.
  5017. (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
  5018. ? nullptr
  5019. : &NoArrowOperatorFound);
  5020. if (Result.isInvalid()) {
  5021. if (NoArrowOperatorFound) {
  5022. if (FirstIteration) {
  5023. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  5024. << BaseType << 1 << Base->getSourceRange()
  5025. << FixItHint::CreateReplacement(OpLoc, ".");
  5026. OpKind = tok::period;
  5027. break;
  5028. }
  5029. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  5030. << BaseType << Base->getSourceRange();
  5031. CallExpr *CE = dyn_cast<CallExpr>(Base);
  5032. if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
  5033. Diag(CD->getLocStart(),
  5034. diag::note_member_reference_arrow_from_operator_arrow);
  5035. }
  5036. }
  5037. return ExprError();
  5038. }
  5039. Base = Result.get();
  5040. if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
  5041. OperatorArrows.push_back(OpCall->getDirectCallee());
  5042. BaseType = Base->getType();
  5043. CanQualType CBaseType = Context.getCanonicalType(BaseType);
  5044. if (!CTypes.insert(CBaseType).second) {
  5045. Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
  5046. noteOperatorArrows(*this, OperatorArrows);
  5047. return ExprError();
  5048. }
  5049. FirstIteration = false;
  5050. }
  5051. if (OpKind == tok::arrow &&
  5052. (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
  5053. BaseType = BaseType->getPointeeType();
  5054. }
  5055. // Objective-C properties allow "." access on Objective-C pointer types,
  5056. // so adjust the base type to the object type itself.
  5057. if (BaseType->isObjCObjectPointerType())
  5058. BaseType = BaseType->getPointeeType();
  5059. // C++ [basic.lookup.classref]p2:
  5060. // [...] If the type of the object expression is of pointer to scalar
  5061. // type, the unqualified-id is looked up in the context of the complete
  5062. // postfix-expression.
  5063. //
  5064. // This also indicates that we could be parsing a pseudo-destructor-name.
  5065. // Note that Objective-C class and object types can be pseudo-destructor
  5066. // expressions or normal member (ivar or property) access expressions.
  5067. if (BaseType->isObjCObjectOrInterfaceType()) {
  5068. MayBePseudoDestructor = true;
  5069. } else if (!BaseType->isRecordType()) {
  5070. ObjectType = ParsedType();
  5071. MayBePseudoDestructor = true;
  5072. return Base;
  5073. }
  5074. // The object type must be complete (or dependent), or
  5075. // C++11 [expr.prim.general]p3:
  5076. // Unlike the object expression in other contexts, *this is not required to
  5077. // be of complete type for purposes of class member access (5.2.5) outside
  5078. // the member function body.
  5079. if (!BaseType->isDependentType() &&
  5080. !isThisOutsideMemberFunctionBody(BaseType) &&
  5081. RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
  5082. return ExprError();
  5083. // C++ [basic.lookup.classref]p2:
  5084. // If the id-expression in a class member access (5.2.5) is an
  5085. // unqualified-id, and the type of the object expression is of a class
  5086. // type C (or of pointer to a class type C), the unqualified-id is looked
  5087. // up in the scope of class C. [...]
  5088. ObjectType = ParsedType::make(BaseType);
  5089. return Base;
  5090. }
  5091. static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
  5092. tok::TokenKind& OpKind, SourceLocation OpLoc) {
  5093. if (Base->hasPlaceholderType()) {
  5094. ExprResult result = S.CheckPlaceholderExpr(Base);
  5095. if (result.isInvalid()) return true;
  5096. Base = result.get();
  5097. }
  5098. ObjectType = Base->getType();
  5099. // C++ [expr.pseudo]p2:
  5100. // The left-hand side of the dot operator shall be of scalar type. The
  5101. // left-hand side of the arrow operator shall be of pointer to scalar type.
  5102. // This scalar type is the object type.
  5103. // Note that this is rather different from the normal handling for the
  5104. // arrow operator.
  5105. if (OpKind == tok::arrow) {
  5106. if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
  5107. ObjectType = Ptr->getPointeeType();
  5108. } else if (!Base->isTypeDependent()) {
  5109. // The user wrote "p->" when she probably meant "p."; fix it.
  5110. S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  5111. << ObjectType << true
  5112. << FixItHint::CreateReplacement(OpLoc, ".");
  5113. if (S.isSFINAEContext())
  5114. return true;
  5115. OpKind = tok::period;
  5116. }
  5117. }
  5118. return false;
  5119. }
  5120. ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
  5121. SourceLocation OpLoc,
  5122. tok::TokenKind OpKind,
  5123. const CXXScopeSpec &SS,
  5124. TypeSourceInfo *ScopeTypeInfo,
  5125. SourceLocation CCLoc,
  5126. SourceLocation TildeLoc,
  5127. PseudoDestructorTypeStorage Destructed) {
  5128. TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
  5129. QualType ObjectType;
  5130. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  5131. return ExprError();
  5132. if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
  5133. !ObjectType->isVectorType()) {
  5134. if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
  5135. Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
  5136. else {
  5137. Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
  5138. << ObjectType << Base->getSourceRange();
  5139. return ExprError();
  5140. }
  5141. }
  5142. // C++ [expr.pseudo]p2:
  5143. // [...] The cv-unqualified versions of the object type and of the type
  5144. // designated by the pseudo-destructor-name shall be the same type.
  5145. if (DestructedTypeInfo) {
  5146. QualType DestructedType = DestructedTypeInfo->getType();
  5147. SourceLocation DestructedTypeStart
  5148. = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
  5149. if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
  5150. if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
  5151. Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
  5152. << ObjectType << DestructedType << Base->getSourceRange()
  5153. << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
  5154. // Recover by setting the destructed type to the object type.
  5155. DestructedType = ObjectType;
  5156. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
  5157. DestructedTypeStart);
  5158. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  5159. } else if (DestructedType.getObjCLifetime() !=
  5160. ObjectType.getObjCLifetime()) {
  5161. if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
  5162. // Okay: just pretend that the user provided the correctly-qualified
  5163. // type.
  5164. } else {
  5165. Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
  5166. << ObjectType << DestructedType << Base->getSourceRange()
  5167. << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
  5168. }
  5169. // Recover by setting the destructed type to the object type.
  5170. DestructedType = ObjectType;
  5171. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
  5172. DestructedTypeStart);
  5173. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  5174. }
  5175. }
  5176. }
  5177. // C++ [expr.pseudo]p2:
  5178. // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
  5179. // form
  5180. //
  5181. // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
  5182. //
  5183. // shall designate the same scalar type.
  5184. if (ScopeTypeInfo) {
  5185. QualType ScopeType = ScopeTypeInfo->getType();
  5186. if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
  5187. !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
  5188. Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
  5189. diag::err_pseudo_dtor_type_mismatch)
  5190. << ObjectType << ScopeType << Base->getSourceRange()
  5191. << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
  5192. ScopeType = QualType();
  5193. ScopeTypeInfo = nullptr;
  5194. }
  5195. }
  5196. Expr *Result
  5197. = new (Context) CXXPseudoDestructorExpr(Context, Base,
  5198. OpKind == tok::arrow, OpLoc,
  5199. SS.getWithLocInContext(Context),
  5200. ScopeTypeInfo,
  5201. CCLoc,
  5202. TildeLoc,
  5203. Destructed);
  5204. return Result;
  5205. }
  5206. ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
  5207. SourceLocation OpLoc,
  5208. tok::TokenKind OpKind,
  5209. CXXScopeSpec &SS,
  5210. UnqualifiedId &FirstTypeName,
  5211. SourceLocation CCLoc,
  5212. SourceLocation TildeLoc,
  5213. UnqualifiedId &SecondTypeName) {
  5214. assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
  5215. FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
  5216. "Invalid first type name in pseudo-destructor");
  5217. assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
  5218. SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
  5219. "Invalid second type name in pseudo-destructor");
  5220. QualType ObjectType;
  5221. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  5222. return ExprError();
  5223. // Compute the object type that we should use for name lookup purposes. Only
  5224. // record types and dependent types matter.
  5225. ParsedType ObjectTypePtrForLookup;
  5226. if (!SS.isSet()) {
  5227. if (ObjectType->isRecordType())
  5228. ObjectTypePtrForLookup = ParsedType::make(ObjectType);
  5229. else if (ObjectType->isDependentType())
  5230. ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
  5231. }
  5232. // Convert the name of the type being destructed (following the ~) into a
  5233. // type (with source-location information).
  5234. QualType DestructedType;
  5235. TypeSourceInfo *DestructedTypeInfo = nullptr;
  5236. PseudoDestructorTypeStorage Destructed;
  5237. if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
  5238. ParsedType T = getTypeName(*SecondTypeName.Identifier,
  5239. SecondTypeName.StartLocation,
  5240. S, &SS, true, false, ObjectTypePtrForLookup);
  5241. if (!T &&
  5242. ((SS.isSet() && !computeDeclContext(SS, false)) ||
  5243. (!SS.isSet() && ObjectType->isDependentType()))) {
  5244. // The name of the type being destroyed is a dependent name, and we
  5245. // couldn't find anything useful in scope. Just store the identifier and
  5246. // it's location, and we'll perform (qualified) name lookup again at
  5247. // template instantiation time.
  5248. Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
  5249. SecondTypeName.StartLocation);
  5250. } else if (!T) {
  5251. Diag(SecondTypeName.StartLocation,
  5252. diag::err_pseudo_dtor_destructor_non_type)
  5253. << SecondTypeName.Identifier << ObjectType;
  5254. if (isSFINAEContext())
  5255. return ExprError();
  5256. // Recover by assuming we had the right type all along.
  5257. DestructedType = ObjectType;
  5258. } else
  5259. DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
  5260. } else {
  5261. // Resolve the template-id to a type.
  5262. TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
  5263. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  5264. TemplateId->NumArgs);
  5265. TypeResult T = ActOnTemplateIdType(TemplateId->SS,
  5266. TemplateId->TemplateKWLoc,
  5267. TemplateId->Template,
  5268. TemplateId->TemplateNameLoc,
  5269. TemplateId->LAngleLoc,
  5270. TemplateArgsPtr,
  5271. TemplateId->RAngleLoc);
  5272. if (T.isInvalid() || !T.get()) {
  5273. // Recover by assuming we had the right type all along.
  5274. DestructedType = ObjectType;
  5275. } else
  5276. DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
  5277. }
  5278. // If we've performed some kind of recovery, (re-)build the type source
  5279. // information.
  5280. if (!DestructedType.isNull()) {
  5281. if (!DestructedTypeInfo)
  5282. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
  5283. SecondTypeName.StartLocation);
  5284. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  5285. }
  5286. // Convert the name of the scope type (the type prior to '::') into a type.
  5287. TypeSourceInfo *ScopeTypeInfo = nullptr;
  5288. QualType ScopeType;
  5289. if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
  5290. FirstTypeName.Identifier) {
  5291. if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
  5292. ParsedType T = getTypeName(*FirstTypeName.Identifier,
  5293. FirstTypeName.StartLocation,
  5294. S, &SS, true, false, ObjectTypePtrForLookup);
  5295. if (!T) {
  5296. Diag(FirstTypeName.StartLocation,
  5297. diag::err_pseudo_dtor_destructor_non_type)
  5298. << FirstTypeName.Identifier << ObjectType;
  5299. if (isSFINAEContext())
  5300. return ExprError();
  5301. // Just drop this type. It's unnecessary anyway.
  5302. ScopeType = QualType();
  5303. } else
  5304. ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
  5305. } else {
  5306. // Resolve the template-id to a type.
  5307. TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
  5308. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  5309. TemplateId->NumArgs);
  5310. TypeResult T = ActOnTemplateIdType(TemplateId->SS,
  5311. TemplateId->TemplateKWLoc,
  5312. TemplateId->Template,
  5313. TemplateId->TemplateNameLoc,
  5314. TemplateId->LAngleLoc,
  5315. TemplateArgsPtr,
  5316. TemplateId->RAngleLoc);
  5317. if (T.isInvalid() || !T.get()) {
  5318. // Recover by dropping this type.
  5319. ScopeType = QualType();
  5320. } else
  5321. ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
  5322. }
  5323. }
  5324. if (!ScopeType.isNull() && !ScopeTypeInfo)
  5325. ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
  5326. FirstTypeName.StartLocation);
  5327. return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
  5328. ScopeTypeInfo, CCLoc, TildeLoc,
  5329. Destructed);
  5330. }
  5331. ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
  5332. SourceLocation OpLoc,
  5333. tok::TokenKind OpKind,
  5334. SourceLocation TildeLoc,
  5335. const DeclSpec& DS) {
  5336. QualType ObjectType;
  5337. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  5338. return ExprError();
  5339. QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
  5340. false);
  5341. TypeLocBuilder TLB;
  5342. DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
  5343. DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
  5344. TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
  5345. PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
  5346. return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
  5347. nullptr, SourceLocation(), TildeLoc,
  5348. Destructed);
  5349. }
  5350. ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
  5351. CXXConversionDecl *Method,
  5352. bool HadMultipleCandidates) {
  5353. if (Method->getParent()->isLambda() &&
  5354. Method->getConversionType()->isBlockPointerType()) {
  5355. // This is a lambda coversion to block pointer; check if the argument
  5356. // is a LambdaExpr.
  5357. Expr *SubE = E;
  5358. CastExpr *CE = dyn_cast<CastExpr>(SubE);
  5359. if (CE && CE->getCastKind() == CK_NoOp)
  5360. SubE = CE->getSubExpr();
  5361. SubE = SubE->IgnoreParens();
  5362. if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
  5363. SubE = BE->getSubExpr();
  5364. if (isa<LambdaExpr>(SubE)) {
  5365. // For the conversion to block pointer on a lambda expression, we
  5366. // construct a special BlockLiteral instead; this doesn't really make
  5367. // a difference in ARC, but outside of ARC the resulting block literal
  5368. // follows the normal lifetime rules for block literals instead of being
  5369. // autoreleased.
  5370. DiagnosticErrorTrap Trap(Diags);
  5371. ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
  5372. E->getExprLoc(),
  5373. Method, E);
  5374. if (Exp.isInvalid())
  5375. Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
  5376. return Exp;
  5377. }
  5378. }
  5379. ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
  5380. FoundDecl, Method);
  5381. if (Exp.isInvalid())
  5382. return true;
  5383. MemberExpr *ME = new (Context) MemberExpr(
  5384. Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
  5385. Context.BoundMemberTy, VK_RValue, OK_Ordinary);
  5386. if (HadMultipleCandidates)
  5387. ME->setHadMultipleCandidates(true);
  5388. MarkMemberReferenced(ME);
  5389. QualType ResultType = Method->getReturnType();
  5390. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  5391. ResultType = ResultType.getNonLValueExprType(Context);
  5392. CXXMemberCallExpr *CE =
  5393. new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
  5394. Exp.get()->getLocEnd());
  5395. return CE;
  5396. }
  5397. ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
  5398. SourceLocation RParen) {
  5399. // If the operand is an unresolved lookup expression, the expression is ill-
  5400. // formed per [over.over]p1, because overloaded function names cannot be used
  5401. // without arguments except in explicit contexts.
  5402. ExprResult R = CheckPlaceholderExpr(Operand);
  5403. if (R.isInvalid())
  5404. return R;
  5405. // The operand may have been modified when checking the placeholder type.
  5406. Operand = R.get();
  5407. if (ActiveTemplateInstantiations.empty() &&
  5408. Operand->HasSideEffects(Context, false)) {
  5409. // The expression operand for noexcept is in an unevaluated expression
  5410. // context, so side effects could result in unintended consequences.
  5411. Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  5412. }
  5413. CanThrowResult CanThrow = canThrow(Operand);
  5414. return new (Context)
  5415. CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
  5416. }
  5417. ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
  5418. Expr *Operand, SourceLocation RParen) {
  5419. return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
  5420. }
  5421. static bool IsSpecialDiscardedValue(Expr *E) {
  5422. // In C++11, discarded-value expressions of a certain form are special,
  5423. // according to [expr]p10:
  5424. // The lvalue-to-rvalue conversion (4.1) is applied only if the
  5425. // expression is an lvalue of volatile-qualified type and it has
  5426. // one of the following forms:
  5427. E = E->IgnoreParens();
  5428. // - id-expression (5.1.1),
  5429. if (isa<DeclRefExpr>(E))
  5430. return true;
  5431. // - subscripting (5.2.1),
  5432. if (isa<ArraySubscriptExpr>(E))
  5433. return true;
  5434. // - class member access (5.2.5),
  5435. if (isa<MemberExpr>(E))
  5436. return true;
  5437. // - indirection (5.3.1),
  5438. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
  5439. if (UO->getOpcode() == UO_Deref)
  5440. return true;
  5441. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  5442. // - pointer-to-member operation (5.5),
  5443. if (BO->isPtrMemOp())
  5444. return true;
  5445. // - comma expression (5.18) where the right operand is one of the above.
  5446. if (BO->getOpcode() == BO_Comma)
  5447. return IsSpecialDiscardedValue(BO->getRHS());
  5448. }
  5449. // - conditional expression (5.16) where both the second and the third
  5450. // operands are one of the above, or
  5451. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
  5452. return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
  5453. IsSpecialDiscardedValue(CO->getFalseExpr());
  5454. // The related edge case of "*x ?: *x".
  5455. if (BinaryConditionalOperator *BCO =
  5456. dyn_cast<BinaryConditionalOperator>(E)) {
  5457. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
  5458. return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
  5459. IsSpecialDiscardedValue(BCO->getFalseExpr());
  5460. }
  5461. // Objective-C++ extensions to the rule.
  5462. if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
  5463. return true;
  5464. return false;
  5465. }
  5466. /// Perform the conversions required for an expression used in a
  5467. /// context that ignores the result.
  5468. ExprResult Sema::IgnoredValueConversions(Expr *E) {
  5469. if (E->hasPlaceholderType()) {
  5470. ExprResult result = CheckPlaceholderExpr(E);
  5471. if (result.isInvalid()) return E;
  5472. E = result.get();
  5473. }
  5474. // C99 6.3.2.1:
  5475. // [Except in specific positions,] an lvalue that does not have
  5476. // array type is converted to the value stored in the
  5477. // designated object (and is no longer an lvalue).
  5478. if (E->isRValue()) {
  5479. // In C, function designators (i.e. expressions of function type)
  5480. // are r-values, but we still want to do function-to-pointer decay
  5481. // on them. This is both technically correct and convenient for
  5482. // some clients.
  5483. if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
  5484. return DefaultFunctionArrayConversion(E);
  5485. return E;
  5486. }
  5487. if (getLangOpts().CPlusPlus) {
  5488. // The C++11 standard defines the notion of a discarded-value expression;
  5489. // normally, we don't need to do anything to handle it, but if it is a
  5490. // volatile lvalue with a special form, we perform an lvalue-to-rvalue
  5491. // conversion.
  5492. if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
  5493. E->getType().isVolatileQualified() &&
  5494. IsSpecialDiscardedValue(E)) {
  5495. ExprResult Res = DefaultLvalueConversion(E);
  5496. if (Res.isInvalid())
  5497. return E;
  5498. E = Res.get();
  5499. }
  5500. return E;
  5501. }
  5502. // GCC seems to also exclude expressions of incomplete enum type.
  5503. if (const EnumType *T = E->getType()->getAs<EnumType>()) {
  5504. if (!T->getDecl()->isComplete()) {
  5505. // FIXME: stupid workaround for a codegen bug!
  5506. E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
  5507. return E;
  5508. }
  5509. }
  5510. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  5511. if (Res.isInvalid())
  5512. return E;
  5513. E = Res.get();
  5514. if (!E->getType()->isVoidType())
  5515. RequireCompleteType(E->getExprLoc(), E->getType(),
  5516. diag::err_incomplete_type);
  5517. return E;
  5518. }
  5519. // If we can unambiguously determine whether Var can never be used
  5520. // in a constant expression, return true.
  5521. // - if the variable and its initializer are non-dependent, then
  5522. // we can unambiguously check if the variable is a constant expression.
  5523. // - if the initializer is not value dependent - we can determine whether
  5524. // it can be used to initialize a constant expression. If Init can not
  5525. // be used to initialize a constant expression we conclude that Var can
  5526. // never be a constant expression.
  5527. // - FXIME: if the initializer is dependent, we can still do some analysis and
  5528. // identify certain cases unambiguously as non-const by using a Visitor:
  5529. // - such as those that involve odr-use of a ParmVarDecl, involve a new
  5530. // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
  5531. static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
  5532. ASTContext &Context) {
  5533. if (isa<ParmVarDecl>(Var)) return true;
  5534. const VarDecl *DefVD = nullptr;
  5535. // If there is no initializer - this can not be a constant expression.
  5536. if (!Var->getAnyInitializer(DefVD)) return true;
  5537. assert(DefVD);
  5538. if (DefVD->isWeak()) return false;
  5539. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  5540. Expr *Init = cast<Expr>(Eval->Value);
  5541. if (Var->getType()->isDependentType() || Init->isValueDependent()) {
  5542. // FIXME: Teach the constant evaluator to deal with the non-dependent parts
  5543. // of value-dependent expressions, and use it here to determine whether the
  5544. // initializer is a potential constant expression.
  5545. return false;
  5546. }
  5547. return !IsVariableAConstantExpression(Var, Context);
  5548. }
  5549. /// \brief Check if the current lambda has any potential captures
  5550. /// that must be captured by any of its enclosing lambdas that are ready to
  5551. /// capture. If there is a lambda that can capture a nested
  5552. /// potential-capture, go ahead and do so. Also, check to see if any
  5553. /// variables are uncaptureable or do not involve an odr-use so do not
  5554. /// need to be captured.
  5555. static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
  5556. Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
  5557. assert(!S.isUnevaluatedContext());
  5558. assert(S.CurContext->isDependentContext());
  5559. assert(CurrentLSI->CallOperator == S.CurContext &&
  5560. "The current call operator must be synchronized with Sema's CurContext");
  5561. const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
  5562. ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
  5563. S.FunctionScopes.data(), S.FunctionScopes.size());
  5564. // All the potentially captureable variables in the current nested
  5565. // lambda (within a generic outer lambda), must be captured by an
  5566. // outer lambda that is enclosed within a non-dependent context.
  5567. const unsigned NumPotentialCaptures =
  5568. CurrentLSI->getNumPotentialVariableCaptures();
  5569. for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
  5570. Expr *VarExpr = nullptr;
  5571. VarDecl *Var = nullptr;
  5572. CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
  5573. // If the variable is clearly identified as non-odr-used and the full
  5574. // expression is not instantiation dependent, only then do we not
  5575. // need to check enclosing lambda's for speculative captures.
  5576. // For e.g.:
  5577. // Even though 'x' is not odr-used, it should be captured.
  5578. // int test() {
  5579. // const int x = 10;
  5580. // auto L = [=](auto a) {
  5581. // (void) +x + a;
  5582. // };
  5583. // }
  5584. if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
  5585. !IsFullExprInstantiationDependent)
  5586. continue;
  5587. // If we have a capture-capable lambda for the variable, go ahead and
  5588. // capture the variable in that lambda (and all its enclosing lambdas).
  5589. if (const Optional<unsigned> Index =
  5590. getStackIndexOfNearestEnclosingCaptureCapableLambda(
  5591. FunctionScopesArrayRef, Var, S)) {
  5592. const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
  5593. MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
  5594. &FunctionScopeIndexOfCapturableLambda);
  5595. }
  5596. const bool IsVarNeverAConstantExpression =
  5597. VariableCanNeverBeAConstantExpression(Var, S.Context);
  5598. if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
  5599. // This full expression is not instantiation dependent or the variable
  5600. // can not be used in a constant expression - which means
  5601. // this variable must be odr-used here, so diagnose a
  5602. // capture violation early, if the variable is un-captureable.
  5603. // This is purely for diagnosing errors early. Otherwise, this
  5604. // error would get diagnosed when the lambda becomes capture ready.
  5605. QualType CaptureType, DeclRefType;
  5606. SourceLocation ExprLoc = VarExpr->getExprLoc();
  5607. if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
  5608. /*EllipsisLoc*/ SourceLocation(),
  5609. /*BuildAndDiagnose*/false, CaptureType,
  5610. DeclRefType, nullptr)) {
  5611. // We will never be able to capture this variable, and we need
  5612. // to be able to in any and all instantiations, so diagnose it.
  5613. S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
  5614. /*EllipsisLoc*/ SourceLocation(),
  5615. /*BuildAndDiagnose*/true, CaptureType,
  5616. DeclRefType, nullptr);
  5617. }
  5618. }
  5619. }
  5620. // Check if 'this' needs to be captured.
  5621. if (CurrentLSI->hasPotentialThisCapture()) {
  5622. // If we have a capture-capable lambda for 'this', go ahead and capture
  5623. // 'this' in that lambda (and all its enclosing lambdas).
  5624. if (const Optional<unsigned> Index =
  5625. getStackIndexOfNearestEnclosingCaptureCapableLambda(
  5626. FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
  5627. const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
  5628. S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
  5629. /*Explicit*/ false, /*BuildAndDiagnose*/ true,
  5630. &FunctionScopeIndexOfCapturableLambda);
  5631. }
  5632. }
  5633. // Reset all the potential captures at the end of each full-expression.
  5634. CurrentLSI->clearPotentialCaptures();
  5635. }
  5636. static ExprResult attemptRecovery(Sema &SemaRef,
  5637. const TypoCorrectionConsumer &Consumer,
  5638. TypoCorrection TC) {
  5639. LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
  5640. Consumer.getLookupResult().getLookupKind());
  5641. const CXXScopeSpec *SS = Consumer.getSS();
  5642. CXXScopeSpec NewSS;
  5643. // Use an approprate CXXScopeSpec for building the expr.
  5644. if (auto *NNS = TC.getCorrectionSpecifier())
  5645. NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
  5646. else if (SS && !TC.WillReplaceSpecifier())
  5647. NewSS = *SS;
  5648. if (auto *ND = TC.getCorrectionDecl()) {
  5649. R.setLookupName(ND->getDeclName());
  5650. R.addDecl(ND);
  5651. if (ND->isCXXClassMember()) {
  5652. // Figure out the correct naming class to add to the LookupResult.
  5653. CXXRecordDecl *Record = nullptr;
  5654. if (auto *NNS = TC.getCorrectionSpecifier())
  5655. Record = NNS->getAsType()->getAsCXXRecordDecl();
  5656. if (!Record)
  5657. Record =
  5658. dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
  5659. if (Record)
  5660. R.setNamingClass(Record);
  5661. // Detect and handle the case where the decl might be an implicit
  5662. // member.
  5663. bool MightBeImplicitMember;
  5664. if (!Consumer.isAddressOfOperand())
  5665. MightBeImplicitMember = true;
  5666. else if (!NewSS.isEmpty())
  5667. MightBeImplicitMember = false;
  5668. else if (R.isOverloadedResult())
  5669. MightBeImplicitMember = false;
  5670. else if (R.isUnresolvableResult())
  5671. MightBeImplicitMember = true;
  5672. else
  5673. MightBeImplicitMember = isa<FieldDecl>(ND) ||
  5674. isa<IndirectFieldDecl>(ND) ||
  5675. isa<MSPropertyDecl>(ND);
  5676. if (MightBeImplicitMember)
  5677. return SemaRef.BuildPossibleImplicitMemberExpr(
  5678. NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
  5679. /*TemplateArgs*/ nullptr);
  5680. } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
  5681. return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
  5682. Ivar->getIdentifier());
  5683. }
  5684. }
  5685. return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
  5686. /*AcceptInvalidDecl*/ true);
  5687. }
  5688. namespace {
  5689. class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
  5690. llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
  5691. public:
  5692. explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
  5693. : TypoExprs(TypoExprs) {}
  5694. bool VisitTypoExpr(TypoExpr *TE) {
  5695. TypoExprs.insert(TE);
  5696. return true;
  5697. }
  5698. };
  5699. class TransformTypos : public TreeTransform<TransformTypos> {
  5700. typedef TreeTransform<TransformTypos> BaseTransform;
  5701. VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
  5702. // process of being initialized.
  5703. llvm::function_ref<ExprResult(Expr *)> ExprFilter;
  5704. llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
  5705. llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
  5706. llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
  5707. /// \brief Emit diagnostics for all of the TypoExprs encountered.
  5708. /// If the TypoExprs were successfully corrected, then the diagnostics should
  5709. /// suggest the corrections. Otherwise the diagnostics will not suggest
  5710. /// anything (having been passed an empty TypoCorrection).
  5711. void EmitAllDiagnostics() {
  5712. for (auto E : TypoExprs) {
  5713. TypoExpr *TE = cast<TypoExpr>(E);
  5714. auto &State = SemaRef.getTypoExprState(TE);
  5715. if (State.DiagHandler) {
  5716. TypoCorrection TC = State.Consumer->getCurrentCorrection();
  5717. ExprResult Replacement = TransformCache[TE];
  5718. // Extract the NamedDecl from the transformed TypoExpr and add it to the
  5719. // TypoCorrection, replacing the existing decls. This ensures the right
  5720. // NamedDecl is used in diagnostics e.g. in the case where overload
  5721. // resolution was used to select one from several possible decls that
  5722. // had been stored in the TypoCorrection.
  5723. if (auto *ND = getDeclFromExpr(
  5724. Replacement.isInvalid() ? nullptr : Replacement.get()))
  5725. TC.setCorrectionDecl(ND);
  5726. State.DiagHandler(TC);
  5727. }
  5728. SemaRef.clearDelayedTypo(TE);
  5729. }
  5730. }
  5731. /// \brief If corrections for the first TypoExpr have been exhausted for a
  5732. /// given combination of the other TypoExprs, retry those corrections against
  5733. /// the next combination of substitutions for the other TypoExprs by advancing
  5734. /// to the next potential correction of the second TypoExpr. For the second
  5735. /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
  5736. /// the stream is reset and the next TypoExpr's stream is advanced by one (a
  5737. /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
  5738. /// TransformCache). Returns true if there is still any untried combinations
  5739. /// of corrections.
  5740. bool CheckAndAdvanceTypoExprCorrectionStreams() {
  5741. for (auto TE : TypoExprs) {
  5742. auto &State = SemaRef.getTypoExprState(TE);
  5743. TransformCache.erase(TE);
  5744. if (!State.Consumer->finished())
  5745. return true;
  5746. State.Consumer->resetCorrectionStream();
  5747. }
  5748. return false;
  5749. }
  5750. NamedDecl *getDeclFromExpr(Expr *E) {
  5751. if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
  5752. E = OverloadResolution[OE];
  5753. if (!E)
  5754. return nullptr;
  5755. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  5756. return DRE->getDecl();
  5757. if (auto *ME = dyn_cast<MemberExpr>(E))
  5758. return ME->getMemberDecl();
  5759. // FIXME: Add any other expr types that could be be seen by the delayed typo
  5760. // correction TreeTransform for which the corresponding TypoCorrection could
  5761. // contain multiple decls.
  5762. return nullptr;
  5763. }
  5764. ExprResult TryTransform(Expr *E) {
  5765. Sema::SFINAETrap Trap(SemaRef);
  5766. ExprResult Res = TransformExpr(E);
  5767. if (Trap.hasErrorOccurred() || Res.isInvalid())
  5768. return ExprError();
  5769. return ExprFilter(Res.get());
  5770. }
  5771. public:
  5772. TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
  5773. : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
  5774. ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
  5775. MultiExprArg Args,
  5776. SourceLocation RParenLoc,
  5777. Expr *ExecConfig = nullptr) {
  5778. auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
  5779. RParenLoc, ExecConfig);
  5780. if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
  5781. if (Result.isUsable()) {
  5782. Expr *ResultCall = Result.get();
  5783. if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
  5784. ResultCall = BE->getSubExpr();
  5785. if (auto *CE = dyn_cast<CallExpr>(ResultCall))
  5786. OverloadResolution[OE] = CE->getCallee();
  5787. }
  5788. }
  5789. return Result;
  5790. }
  5791. ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
  5792. ExprResult Transform(Expr *E) {
  5793. ExprResult Res;
  5794. while (true) {
  5795. Res = TryTransform(E);
  5796. // Exit if either the transform was valid or if there were no TypoExprs
  5797. // to transform that still have any untried correction candidates..
  5798. if (!Res.isInvalid() ||
  5799. !CheckAndAdvanceTypoExprCorrectionStreams())
  5800. break;
  5801. }
  5802. // Ensure none of the TypoExprs have multiple typo correction candidates
  5803. // with the same edit length that pass all the checks and filters.
  5804. // TODO: Properly handle various permutations of possible corrections when
  5805. // there is more than one potentially ambiguous typo correction.
  5806. // Also, disable typo correction while attempting the transform when
  5807. // handling potentially ambiguous typo corrections as any new TypoExprs will
  5808. // have been introduced by the application of one of the correction
  5809. // candidates and add little to no value if corrected.
  5810. SemaRef.DisableTypoCorrection = true;
  5811. while (!AmbiguousTypoExprs.empty()) {
  5812. auto TE = AmbiguousTypoExprs.back();
  5813. auto Cached = TransformCache[TE];
  5814. auto &State = SemaRef.getTypoExprState(TE);
  5815. State.Consumer->saveCurrentPosition();
  5816. TransformCache.erase(TE);
  5817. if (!TryTransform(E).isInvalid()) {
  5818. State.Consumer->resetCorrectionStream();
  5819. TransformCache.erase(TE);
  5820. Res = ExprError();
  5821. break;
  5822. }
  5823. AmbiguousTypoExprs.remove(TE);
  5824. State.Consumer->restoreSavedPosition();
  5825. TransformCache[TE] = Cached;
  5826. }
  5827. SemaRef.DisableTypoCorrection = false;
  5828. // Ensure that all of the TypoExprs within the current Expr have been found.
  5829. if (!Res.isUsable())
  5830. FindTypoExprs(TypoExprs).TraverseStmt(E);
  5831. EmitAllDiagnostics();
  5832. return Res;
  5833. }
  5834. ExprResult TransformTypoExpr(TypoExpr *E) {
  5835. // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
  5836. // cached transformation result if there is one and the TypoExpr isn't the
  5837. // first one that was encountered.
  5838. auto &CacheEntry = TransformCache[E];
  5839. if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
  5840. return CacheEntry;
  5841. }
  5842. auto &State = SemaRef.getTypoExprState(E);
  5843. assert(State.Consumer && "Cannot transform a cleared TypoExpr");
  5844. // For the first TypoExpr and an uncached TypoExpr, find the next likely
  5845. // typo correction and return it.
  5846. while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
  5847. if (InitDecl && TC.getCorrectionDecl() == InitDecl)
  5848. continue;
  5849. ExprResult NE = State.RecoveryHandler ?
  5850. State.RecoveryHandler(SemaRef, E, TC) :
  5851. attemptRecovery(SemaRef, *State.Consumer, TC);
  5852. if (!NE.isInvalid()) {
  5853. // Check whether there may be a second viable correction with the same
  5854. // edit distance; if so, remember this TypoExpr may have an ambiguous
  5855. // correction so it can be more thoroughly vetted later.
  5856. TypoCorrection Next;
  5857. if ((Next = State.Consumer->peekNextCorrection()) &&
  5858. Next.getEditDistance(false) == TC.getEditDistance(false)) {
  5859. AmbiguousTypoExprs.insert(E);
  5860. } else {
  5861. AmbiguousTypoExprs.remove(E);
  5862. }
  5863. assert(!NE.isUnset() &&
  5864. "Typo was transformed into a valid-but-null ExprResult");
  5865. return CacheEntry = NE;
  5866. }
  5867. }
  5868. return CacheEntry = ExprError();
  5869. }
  5870. };
  5871. }
  5872. ExprResult
  5873. Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
  5874. llvm::function_ref<ExprResult(Expr *)> Filter) {
  5875. // If the current evaluation context indicates there are uncorrected typos
  5876. // and the current expression isn't guaranteed to not have typos, try to
  5877. // resolve any TypoExpr nodes that might be in the expression.
  5878. if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
  5879. (E->isTypeDependent() || E->isValueDependent() ||
  5880. E->isInstantiationDependent())) {
  5881. auto TyposInContext = ExprEvalContexts.back().NumTypos;
  5882. assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
  5883. ExprEvalContexts.back().NumTypos = ~0U;
  5884. auto TyposResolved = DelayedTypos.size();
  5885. auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
  5886. ExprEvalContexts.back().NumTypos = TyposInContext;
  5887. TyposResolved -= DelayedTypos.size();
  5888. if (Result.isInvalid() || Result.get() != E) {
  5889. ExprEvalContexts.back().NumTypos -= TyposResolved;
  5890. return Result;
  5891. }
  5892. assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
  5893. }
  5894. return E;
  5895. }
  5896. ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
  5897. bool DiscardedValue,
  5898. bool IsConstexpr,
  5899. bool IsLambdaInitCaptureInitializer) {
  5900. ExprResult FullExpr = FE;
  5901. if (!FullExpr.get())
  5902. return ExprError();
  5903. // If we are an init-expression in a lambdas init-capture, we should not
  5904. // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
  5905. // containing full-expression is done).
  5906. // template<class ... Ts> void test(Ts ... t) {
  5907. // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
  5908. // return a;
  5909. // }() ...);
  5910. // }
  5911. // FIXME: This is a hack. It would be better if we pushed the lambda scope
  5912. // when we parse the lambda introducer, and teach capturing (but not
  5913. // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
  5914. // corresponding class yet (that is, have LambdaScopeInfo either represent a
  5915. // lambda where we've entered the introducer but not the body, or represent a
  5916. // lambda where we've entered the body, depending on where the
  5917. // parser/instantiation has got to).
  5918. if (!IsLambdaInitCaptureInitializer &&
  5919. DiagnoseUnexpandedParameterPack(FullExpr.get()))
  5920. return ExprError();
  5921. // Top-level expressions default to 'id' when we're in a debugger.
  5922. if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
  5923. FullExpr.get()->getType() == Context.UnknownAnyTy) {
  5924. FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
  5925. if (FullExpr.isInvalid())
  5926. return ExprError();
  5927. }
  5928. if (DiscardedValue) {
  5929. FullExpr = CheckPlaceholderExpr(FullExpr.get());
  5930. if (FullExpr.isInvalid())
  5931. return ExprError();
  5932. FullExpr = IgnoredValueConversions(FullExpr.get());
  5933. if (FullExpr.isInvalid())
  5934. return ExprError();
  5935. }
  5936. FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
  5937. if (FullExpr.isInvalid())
  5938. return ExprError();
  5939. CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
  5940. // At the end of this full expression (which could be a deeply nested
  5941. // lambda), if there is a potential capture within the nested lambda,
  5942. // have the outer capture-able lambda try and capture it.
  5943. // Consider the following code:
  5944. // void f(int, int);
  5945. // void f(const int&, double);
  5946. // void foo() {
  5947. // const int x = 10, y = 20;
  5948. // auto L = [=](auto a) {
  5949. // auto M = [=](auto b) {
  5950. // f(x, b); <-- requires x to be captured by L and M
  5951. // f(y, a); <-- requires y to be captured by L, but not all Ms
  5952. // };
  5953. // };
  5954. // }
  5955. // FIXME: Also consider what happens for something like this that involves
  5956. // the gnu-extension statement-expressions or even lambda-init-captures:
  5957. // void f() {
  5958. // const int n = 0;
  5959. // auto L = [&](auto a) {
  5960. // +n + ({ 0; a; });
  5961. // };
  5962. // }
  5963. //
  5964. // Here, we see +n, and then the full-expression 0; ends, so we don't
  5965. // capture n (and instead remove it from our list of potential captures),
  5966. // and then the full-expression +n + ({ 0; }); ends, but it's too late
  5967. // for us to see that we need to capture n after all.
  5968. LambdaScopeInfo *const CurrentLSI = getCurLambda();
  5969. // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
  5970. // even if CurContext is not a lambda call operator. Refer to that Bug Report
  5971. // for an example of the code that might cause this asynchrony.
  5972. // By ensuring we are in the context of a lambda's call operator
  5973. // we can fix the bug (we only need to check whether we need to capture
  5974. // if we are within a lambda's body); but per the comments in that
  5975. // PR, a proper fix would entail :
  5976. // "Alternative suggestion:
  5977. // - Add to Sema an integer holding the smallest (outermost) scope
  5978. // index that we are *lexically* within, and save/restore/set to
  5979. // FunctionScopes.size() in InstantiatingTemplate's
  5980. // constructor/destructor.
  5981. // - Teach the handful of places that iterate over FunctionScopes to
  5982. // stop at the outermost enclosing lexical scope."
  5983. const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
  5984. if (IsInLambdaDeclContext && CurrentLSI &&
  5985. CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
  5986. CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
  5987. *this);
  5988. return MaybeCreateExprWithCleanups(FullExpr);
  5989. }
  5990. StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
  5991. if (!FullStmt) return StmtError();
  5992. return MaybeCreateStmtWithCleanups(FullStmt);
  5993. }
  5994. Sema::IfExistsResult
  5995. Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
  5996. CXXScopeSpec &SS,
  5997. const DeclarationNameInfo &TargetNameInfo) {
  5998. DeclarationName TargetName = TargetNameInfo.getName();
  5999. if (!TargetName)
  6000. return IER_DoesNotExist;
  6001. // If the name itself is dependent, then the result is dependent.
  6002. if (TargetName.isDependentName())
  6003. return IER_Dependent;
  6004. // Do the redeclaration lookup in the current scope.
  6005. LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
  6006. Sema::NotForRedeclaration);
  6007. LookupParsedName(R, S, &SS);
  6008. R.suppressDiagnostics();
  6009. switch (R.getResultKind()) {
  6010. case LookupResult::Found:
  6011. case LookupResult::FoundOverloaded:
  6012. case LookupResult::FoundUnresolvedValue:
  6013. case LookupResult::Ambiguous:
  6014. return IER_Exists;
  6015. case LookupResult::NotFound:
  6016. return IER_DoesNotExist;
  6017. case LookupResult::NotFoundInCurrentInstantiation:
  6018. return IER_Dependent;
  6019. }
  6020. llvm_unreachable("Invalid LookupResult Kind!");
  6021. }
  6022. Sema::IfExistsResult
  6023. Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
  6024. bool IsIfExists, CXXScopeSpec &SS,
  6025. UnqualifiedId &Name) {
  6026. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  6027. // Check for unexpanded parameter packs.
  6028. SmallVector<UnexpandedParameterPack, 4> Unexpanded;
  6029. collectUnexpandedParameterPacks(SS, Unexpanded);
  6030. collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
  6031. if (!Unexpanded.empty()) {
  6032. DiagnoseUnexpandedParameterPacks(KeywordLoc,
  6033. IsIfExists? UPPC_IfExists
  6034. : UPPC_IfNotExists,
  6035. Unexpanded);
  6036. return IER_Error;
  6037. }
  6038. return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
  6039. }