SemaExpr.cpp 693 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TreeTransform.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/AST/ExprOpenMP.h"
  25. #include "clang/AST/RecursiveASTVisitor.h"
  26. #include "clang/AST/TypeLoc.h"
  27. #include "clang/Basic/FixedPoint.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/LiteralSupport.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/AnalysisBasedWarnings.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Designator.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/Overload.h"
  40. #include "clang/Sema/ParsedTemplate.h"
  41. #include "clang/Sema/Scope.h"
  42. #include "clang/Sema/ScopeInfo.h"
  43. #include "clang/Sema/SemaFixItUtils.h"
  44. #include "clang/Sema/SemaInternal.h"
  45. #include "clang/Sema/Template.h"
  46. #include "llvm/Support/ConvertUTF.h"
  47. using namespace clang;
  48. using namespace sema;
  49. /// Determine whether the use of this declaration is valid, without
  50. /// emitting diagnostics.
  51. bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
  52. // See if this is an auto-typed variable whose initializer we are parsing.
  53. if (ParsingInitForAutoVars.count(D))
  54. return false;
  55. // See if this is a deleted function.
  56. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  57. if (FD->isDeleted())
  58. return false;
  59. // If the function has a deduced return type, and we can't deduce it,
  60. // then we can't use it either.
  61. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  62. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  63. return false;
  64. // See if this is an aligned allocation/deallocation function that is
  65. // unavailable.
  66. if (TreatUnavailableAsInvalid &&
  67. isUnavailableAlignedAllocationFunction(*FD))
  68. return false;
  69. }
  70. // See if this function is unavailable.
  71. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  72. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  73. return false;
  74. return true;
  75. }
  76. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  77. // Warn if this is used but marked unused.
  78. if (const auto *A = D->getAttr<UnusedAttr>()) {
  79. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  80. // should diagnose them.
  81. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  82. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  83. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  84. if (DC && !DC->hasAttr<UnusedAttr>())
  85. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  86. }
  87. }
  88. }
  89. /// Emit a note explaining that this function is deleted.
  90. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  91. assert(Decl->isDeleted());
  92. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  93. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  94. // If the method was explicitly defaulted, point at that declaration.
  95. if (!Method->isImplicit())
  96. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  97. // Try to diagnose why this special member function was implicitly
  98. // deleted. This might fail, if that reason no longer applies.
  99. CXXSpecialMember CSM = getSpecialMember(Method);
  100. if (CSM != CXXInvalid)
  101. ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
  102. return;
  103. }
  104. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  105. if (Ctor && Ctor->isInheritingConstructor())
  106. return NoteDeletedInheritingConstructor(Ctor);
  107. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  108. << Decl << 1;
  109. }
  110. /// Determine whether a FunctionDecl was ever declared with an
  111. /// explicit storage class.
  112. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  113. for (auto I : D->redecls()) {
  114. if (I->getStorageClass() != SC_None)
  115. return true;
  116. }
  117. return false;
  118. }
  119. /// Check whether we're in an extern inline function and referring to a
  120. /// variable or function with internal linkage (C11 6.7.4p3).
  121. ///
  122. /// This is only a warning because we used to silently accept this code, but
  123. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  124. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  125. /// and so while there may still be user mistakes, most of the time we can't
  126. /// prove that there are errors.
  127. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  128. const NamedDecl *D,
  129. SourceLocation Loc) {
  130. // This is disabled under C++; there are too many ways for this to fire in
  131. // contexts where the warning is a false positive, or where it is technically
  132. // correct but benign.
  133. if (S.getLangOpts().CPlusPlus)
  134. return;
  135. // Check if this is an inlined function or method.
  136. FunctionDecl *Current = S.getCurFunctionDecl();
  137. if (!Current)
  138. return;
  139. if (!Current->isInlined())
  140. return;
  141. if (!Current->isExternallyVisible())
  142. return;
  143. // Check if the decl has internal linkage.
  144. if (D->getFormalLinkage() != InternalLinkage)
  145. return;
  146. // Downgrade from ExtWarn to Extension if
  147. // (1) the supposedly external inline function is in the main file,
  148. // and probably won't be included anywhere else.
  149. // (2) the thing we're referencing is a pure function.
  150. // (3) the thing we're referencing is another inline function.
  151. // This last can give us false negatives, but it's better than warning on
  152. // wrappers for simple C library functions.
  153. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  154. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  155. if (!DowngradeWarning && UsedFn)
  156. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  157. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  158. : diag::ext_internal_in_extern_inline)
  159. << /*IsVar=*/!UsedFn << D;
  160. S.MaybeSuggestAddingStaticToDecl(Current);
  161. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  162. << D;
  163. }
  164. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  165. const FunctionDecl *First = Cur->getFirstDecl();
  166. // Suggest "static" on the function, if possible.
  167. if (!hasAnyExplicitStorageClass(First)) {
  168. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  169. Diag(DeclBegin, diag::note_convert_inline_to_static)
  170. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  171. }
  172. }
  173. /// Determine whether the use of this declaration is valid, and
  174. /// emit any corresponding diagnostics.
  175. ///
  176. /// This routine diagnoses various problems with referencing
  177. /// declarations that can occur when using a declaration. For example,
  178. /// it might warn if a deprecated or unavailable declaration is being
  179. /// used, or produce an error (and return true) if a C++0x deleted
  180. /// function is being used.
  181. ///
  182. /// \returns true if there was an error (this declaration cannot be
  183. /// referenced), false otherwise.
  184. ///
  185. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
  186. const ObjCInterfaceDecl *UnknownObjCClass,
  187. bool ObjCPropertyAccess,
  188. bool AvoidPartialAvailabilityChecks,
  189. ObjCInterfaceDecl *ClassReceiver) {
  190. SourceLocation Loc = Locs.front();
  191. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  192. // If there were any diagnostics suppressed by template argument deduction,
  193. // emit them now.
  194. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  195. if (Pos != SuppressedDiagnostics.end()) {
  196. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  197. Diag(Suppressed.first, Suppressed.second);
  198. // Clear out the list of suppressed diagnostics, so that we don't emit
  199. // them again for this specialization. However, we don't obsolete this
  200. // entry from the table, because we want to avoid ever emitting these
  201. // diagnostics again.
  202. Pos->second.clear();
  203. }
  204. // C++ [basic.start.main]p3:
  205. // The function 'main' shall not be used within a program.
  206. if (cast<FunctionDecl>(D)->isMain())
  207. Diag(Loc, diag::ext_main_used);
  208. diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
  209. }
  210. // See if this is an auto-typed variable whose initializer we are parsing.
  211. if (ParsingInitForAutoVars.count(D)) {
  212. if (isa<BindingDecl>(D)) {
  213. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  214. << D->getDeclName();
  215. } else {
  216. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  217. << D->getDeclName() << cast<VarDecl>(D)->getType();
  218. }
  219. return true;
  220. }
  221. // See if this is a deleted function.
  222. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  223. if (FD->isDeleted()) {
  224. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  225. if (Ctor && Ctor->isInheritingConstructor())
  226. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  227. << Ctor->getParent()
  228. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  229. else
  230. Diag(Loc, diag::err_deleted_function_use);
  231. NoteDeletedFunction(FD);
  232. return true;
  233. }
  234. // If the function has a deduced return type, and we can't deduce it,
  235. // then we can't use it either.
  236. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  237. DeduceReturnType(FD, Loc))
  238. return true;
  239. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  240. return true;
  241. }
  242. if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  243. // Lambdas are only default-constructible or assignable in C++2a onwards.
  244. if (MD->getParent()->isLambda() &&
  245. ((isa<CXXConstructorDecl>(MD) &&
  246. cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
  247. MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
  248. Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
  249. << !isa<CXXConstructorDecl>(MD);
  250. }
  251. }
  252. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  253. const ObjCPropertyDecl * {
  254. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  255. return MD->findPropertyDecl();
  256. return nullptr;
  257. };
  258. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  259. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  260. return true;
  261. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  262. return true;
  263. }
  264. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  265. // Only the variables omp_in and omp_out are allowed in the combiner.
  266. // Only the variables omp_priv and omp_orig are allowed in the
  267. // initializer-clause.
  268. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  269. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  270. isa<VarDecl>(D)) {
  271. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  272. << getCurFunction()->HasOMPDeclareReductionCombiner;
  273. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  274. return true;
  275. }
  276. // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
  277. // List-items in map clauses on this construct may only refer to the declared
  278. // variable var and entities that could be referenced by a procedure defined
  279. // at the same location
  280. auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
  281. if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
  282. isa<VarDecl>(D)) {
  283. Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
  284. << DMD->getVarName().getAsString();
  285. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  286. return true;
  287. }
  288. DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
  289. AvoidPartialAvailabilityChecks, ClassReceiver);
  290. DiagnoseUnusedOfDecl(*this, D, Loc);
  291. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  292. return false;
  293. }
  294. /// DiagnoseSentinelCalls - This routine checks whether a call or
  295. /// message-send is to a declaration with the sentinel attribute, and
  296. /// if so, it checks that the requirements of the sentinel are
  297. /// satisfied.
  298. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  299. ArrayRef<Expr *> Args) {
  300. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  301. if (!attr)
  302. return;
  303. // The number of formal parameters of the declaration.
  304. unsigned numFormalParams;
  305. // The kind of declaration. This is also an index into a %select in
  306. // the diagnostic.
  307. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  308. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  309. numFormalParams = MD->param_size();
  310. calleeType = CT_Method;
  311. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  312. numFormalParams = FD->param_size();
  313. calleeType = CT_Function;
  314. } else if (isa<VarDecl>(D)) {
  315. QualType type = cast<ValueDecl>(D)->getType();
  316. const FunctionType *fn = nullptr;
  317. if (const PointerType *ptr = type->getAs<PointerType>()) {
  318. fn = ptr->getPointeeType()->getAs<FunctionType>();
  319. if (!fn) return;
  320. calleeType = CT_Function;
  321. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  322. fn = ptr->getPointeeType()->castAs<FunctionType>();
  323. calleeType = CT_Block;
  324. } else {
  325. return;
  326. }
  327. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  328. numFormalParams = proto->getNumParams();
  329. } else {
  330. numFormalParams = 0;
  331. }
  332. } else {
  333. return;
  334. }
  335. // "nullPos" is the number of formal parameters at the end which
  336. // effectively count as part of the variadic arguments. This is
  337. // useful if you would prefer to not have *any* formal parameters,
  338. // but the language forces you to have at least one.
  339. unsigned nullPos = attr->getNullPos();
  340. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  341. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  342. // The number of arguments which should follow the sentinel.
  343. unsigned numArgsAfterSentinel = attr->getSentinel();
  344. // If there aren't enough arguments for all the formal parameters,
  345. // the sentinel, and the args after the sentinel, complain.
  346. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  347. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  348. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  349. return;
  350. }
  351. // Otherwise, find the sentinel expression.
  352. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  353. if (!sentinelExpr) return;
  354. if (sentinelExpr->isValueDependent()) return;
  355. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  356. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  357. // or 'NULL' if those are actually defined in the context. Only use
  358. // 'nil' for ObjC methods, where it's much more likely that the
  359. // variadic arguments form a list of object pointers.
  360. SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
  361. std::string NullValue;
  362. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  363. NullValue = "nil";
  364. else if (getLangOpts().CPlusPlus11)
  365. NullValue = "nullptr";
  366. else if (PP.isMacroDefined("NULL"))
  367. NullValue = "NULL";
  368. else
  369. NullValue = "(void*) 0";
  370. if (MissingNilLoc.isInvalid())
  371. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  372. else
  373. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  374. << int(calleeType)
  375. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  376. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  377. }
  378. SourceRange Sema::getExprRange(Expr *E) const {
  379. return E ? E->getSourceRange() : SourceRange();
  380. }
  381. //===----------------------------------------------------------------------===//
  382. // Standard Promotions and Conversions
  383. //===----------------------------------------------------------------------===//
  384. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  385. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  386. // Handle any placeholder expressions which made it here.
  387. if (E->getType()->isPlaceholderType()) {
  388. ExprResult result = CheckPlaceholderExpr(E);
  389. if (result.isInvalid()) return ExprError();
  390. E = result.get();
  391. }
  392. QualType Ty = E->getType();
  393. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  394. if (Ty->isFunctionType()) {
  395. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  396. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  397. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  398. return ExprError();
  399. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  400. CK_FunctionToPointerDecay).get();
  401. } else if (Ty->isArrayType()) {
  402. // In C90 mode, arrays only promote to pointers if the array expression is
  403. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  404. // type 'array of type' is converted to an expression that has type 'pointer
  405. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  406. // that has type 'array of type' ...". The relevant change is "an lvalue"
  407. // (C90) to "an expression" (C99).
  408. //
  409. // C++ 4.2p1:
  410. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  411. // T" can be converted to an rvalue of type "pointer to T".
  412. //
  413. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  414. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  415. CK_ArrayToPointerDecay).get();
  416. }
  417. return E;
  418. }
  419. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  420. // Check to see if we are dereferencing a null pointer. If so,
  421. // and if not volatile-qualified, this is undefined behavior that the
  422. // optimizer will delete, so warn about it. People sometimes try to use this
  423. // to get a deterministic trap and are surprised by clang's behavior. This
  424. // only handles the pattern "*null", which is a very syntactic check.
  425. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  426. if (UO->getOpcode() == UO_Deref &&
  427. UO->getSubExpr()->IgnoreParenCasts()->
  428. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  429. !UO->getType().isVolatileQualified()) {
  430. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  431. S.PDiag(diag::warn_indirection_through_null)
  432. << UO->getSubExpr()->getSourceRange());
  433. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  434. S.PDiag(diag::note_indirection_through_null));
  435. }
  436. }
  437. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  438. SourceLocation AssignLoc,
  439. const Expr* RHS) {
  440. const ObjCIvarDecl *IV = OIRE->getDecl();
  441. if (!IV)
  442. return;
  443. DeclarationName MemberName = IV->getDeclName();
  444. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  445. if (!Member || !Member->isStr("isa"))
  446. return;
  447. const Expr *Base = OIRE->getBase();
  448. QualType BaseType = Base->getType();
  449. if (OIRE->isArrow())
  450. BaseType = BaseType->getPointeeType();
  451. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  452. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  453. ObjCInterfaceDecl *ClassDeclared = nullptr;
  454. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  455. if (!ClassDeclared->getSuperClass()
  456. && (*ClassDeclared->ivar_begin()) == IV) {
  457. if (RHS) {
  458. NamedDecl *ObjectSetClass =
  459. S.LookupSingleName(S.TUScope,
  460. &S.Context.Idents.get("object_setClass"),
  461. SourceLocation(), S.LookupOrdinaryName);
  462. if (ObjectSetClass) {
  463. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
  464. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
  465. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  466. "object_setClass(")
  467. << FixItHint::CreateReplacement(
  468. SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
  469. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  470. }
  471. else
  472. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  473. } else {
  474. NamedDecl *ObjectGetClass =
  475. S.LookupSingleName(S.TUScope,
  476. &S.Context.Idents.get("object_getClass"),
  477. SourceLocation(), S.LookupOrdinaryName);
  478. if (ObjectGetClass)
  479. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
  480. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  481. "object_getClass(")
  482. << FixItHint::CreateReplacement(
  483. SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
  484. else
  485. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  486. }
  487. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  488. }
  489. }
  490. }
  491. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  492. // Handle any placeholder expressions which made it here.
  493. if (E->getType()->isPlaceholderType()) {
  494. ExprResult result = CheckPlaceholderExpr(E);
  495. if (result.isInvalid()) return ExprError();
  496. E = result.get();
  497. }
  498. // C++ [conv.lval]p1:
  499. // A glvalue of a non-function, non-array type T can be
  500. // converted to a prvalue.
  501. if (!E->isGLValue()) return E;
  502. QualType T = E->getType();
  503. assert(!T.isNull() && "r-value conversion on typeless expression?");
  504. // We don't want to throw lvalue-to-rvalue casts on top of
  505. // expressions of certain types in C++.
  506. if (getLangOpts().CPlusPlus &&
  507. (E->getType() == Context.OverloadTy ||
  508. T->isDependentType() ||
  509. T->isRecordType()))
  510. return E;
  511. // The C standard is actually really unclear on this point, and
  512. // DR106 tells us what the result should be but not why. It's
  513. // generally best to say that void types just doesn't undergo
  514. // lvalue-to-rvalue at all. Note that expressions of unqualified
  515. // 'void' type are never l-values, but qualified void can be.
  516. if (T->isVoidType())
  517. return E;
  518. // OpenCL usually rejects direct accesses to values of 'half' type.
  519. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  520. T->isHalfType()) {
  521. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  522. << 0 << T;
  523. return ExprError();
  524. }
  525. CheckForNullPointerDereference(*this, E);
  526. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  527. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  528. &Context.Idents.get("object_getClass"),
  529. SourceLocation(), LookupOrdinaryName);
  530. if (ObjectGetClass)
  531. Diag(E->getExprLoc(), diag::warn_objc_isa_use)
  532. << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
  533. << FixItHint::CreateReplacement(
  534. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  535. else
  536. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  537. }
  538. else if (const ObjCIvarRefExpr *OIRE =
  539. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  540. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  541. // C++ [conv.lval]p1:
  542. // [...] If T is a non-class type, the type of the prvalue is the
  543. // cv-unqualified version of T. Otherwise, the type of the
  544. // rvalue is T.
  545. //
  546. // C99 6.3.2.1p2:
  547. // If the lvalue has qualified type, the value has the unqualified
  548. // version of the type of the lvalue; otherwise, the value has the
  549. // type of the lvalue.
  550. if (T.hasQualifiers())
  551. T = T.getUnqualifiedType();
  552. // Under the MS ABI, lock down the inheritance model now.
  553. if (T->isMemberPointerType() &&
  554. Context.getTargetInfo().getCXXABI().isMicrosoft())
  555. (void)isCompleteType(E->getExprLoc(), T);
  556. ExprResult Res = CheckLValueToRValueConversionOperand(E);
  557. if (Res.isInvalid())
  558. return Res;
  559. E = Res.get();
  560. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  561. // balance that.
  562. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  563. Cleanup.setExprNeedsCleanups(true);
  564. // C++ [conv.lval]p3:
  565. // If T is cv std::nullptr_t, the result is a null pointer constant.
  566. CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
  567. Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
  568. // C11 6.3.2.1p2:
  569. // ... if the lvalue has atomic type, the value has the non-atomic version
  570. // of the type of the lvalue ...
  571. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  572. T = Atomic->getValueType().getUnqualifiedType();
  573. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  574. nullptr, VK_RValue);
  575. }
  576. return Res;
  577. }
  578. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  579. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  580. if (Res.isInvalid())
  581. return ExprError();
  582. Res = DefaultLvalueConversion(Res.get());
  583. if (Res.isInvalid())
  584. return ExprError();
  585. return Res;
  586. }
  587. /// CallExprUnaryConversions - a special case of an unary conversion
  588. /// performed on a function designator of a call expression.
  589. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  590. QualType Ty = E->getType();
  591. ExprResult Res = E;
  592. // Only do implicit cast for a function type, but not for a pointer
  593. // to function type.
  594. if (Ty->isFunctionType()) {
  595. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  596. CK_FunctionToPointerDecay).get();
  597. if (Res.isInvalid())
  598. return ExprError();
  599. }
  600. Res = DefaultLvalueConversion(Res.get());
  601. if (Res.isInvalid())
  602. return ExprError();
  603. return Res.get();
  604. }
  605. /// UsualUnaryConversions - Performs various conversions that are common to most
  606. /// operators (C99 6.3). The conversions of array and function types are
  607. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  608. /// apply if the array is an argument to the sizeof or address (&) operators.
  609. /// In these instances, this routine should *not* be called.
  610. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  611. // First, convert to an r-value.
  612. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  613. if (Res.isInvalid())
  614. return ExprError();
  615. E = Res.get();
  616. QualType Ty = E->getType();
  617. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  618. // Half FP have to be promoted to float unless it is natively supported
  619. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  620. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  621. // Try to perform integral promotions if the object has a theoretically
  622. // promotable type.
  623. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  624. // C99 6.3.1.1p2:
  625. //
  626. // The following may be used in an expression wherever an int or
  627. // unsigned int may be used:
  628. // - an object or expression with an integer type whose integer
  629. // conversion rank is less than or equal to the rank of int
  630. // and unsigned int.
  631. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  632. //
  633. // If an int can represent all values of the original type, the
  634. // value is converted to an int; otherwise, it is converted to an
  635. // unsigned int. These are called the integer promotions. All
  636. // other types are unchanged by the integer promotions.
  637. QualType PTy = Context.isPromotableBitField(E);
  638. if (!PTy.isNull()) {
  639. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  640. return E;
  641. }
  642. if (Ty->isPromotableIntegerType()) {
  643. QualType PT = Context.getPromotedIntegerType(Ty);
  644. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  645. return E;
  646. }
  647. }
  648. return E;
  649. }
  650. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  651. /// do not have a prototype. Arguments that have type float or __fp16
  652. /// are promoted to double. All other argument types are converted by
  653. /// UsualUnaryConversions().
  654. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  655. QualType Ty = E->getType();
  656. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  657. ExprResult Res = UsualUnaryConversions(E);
  658. if (Res.isInvalid())
  659. return ExprError();
  660. E = Res.get();
  661. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  662. // promote to double.
  663. // Note that default argument promotion applies only to float (and
  664. // half/fp16); it does not apply to _Float16.
  665. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  666. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  667. BTy->getKind() == BuiltinType::Float)) {
  668. if (getLangOpts().OpenCL &&
  669. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  670. if (BTy->getKind() == BuiltinType::Half) {
  671. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  672. }
  673. } else {
  674. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  675. }
  676. }
  677. // C++ performs lvalue-to-rvalue conversion as a default argument
  678. // promotion, even on class types, but note:
  679. // C++11 [conv.lval]p2:
  680. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  681. // operand or a subexpression thereof the value contained in the
  682. // referenced object is not accessed. Otherwise, if the glvalue
  683. // has a class type, the conversion copy-initializes a temporary
  684. // of type T from the glvalue and the result of the conversion
  685. // is a prvalue for the temporary.
  686. // FIXME: add some way to gate this entire thing for correctness in
  687. // potentially potentially evaluated contexts.
  688. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  689. ExprResult Temp = PerformCopyInitialization(
  690. InitializedEntity::InitializeTemporary(E->getType()),
  691. E->getExprLoc(), E);
  692. if (Temp.isInvalid())
  693. return ExprError();
  694. E = Temp.get();
  695. }
  696. return E;
  697. }
  698. /// Determine the degree of POD-ness for an expression.
  699. /// Incomplete types are considered POD, since this check can be performed
  700. /// when we're in an unevaluated context.
  701. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  702. if (Ty->isIncompleteType()) {
  703. // C++11 [expr.call]p7:
  704. // After these conversions, if the argument does not have arithmetic,
  705. // enumeration, pointer, pointer to member, or class type, the program
  706. // is ill-formed.
  707. //
  708. // Since we've already performed array-to-pointer and function-to-pointer
  709. // decay, the only such type in C++ is cv void. This also handles
  710. // initializer lists as variadic arguments.
  711. if (Ty->isVoidType())
  712. return VAK_Invalid;
  713. if (Ty->isObjCObjectType())
  714. return VAK_Invalid;
  715. return VAK_Valid;
  716. }
  717. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  718. return VAK_Invalid;
  719. if (Ty.isCXX98PODType(Context))
  720. return VAK_Valid;
  721. // C++11 [expr.call]p7:
  722. // Passing a potentially-evaluated argument of class type (Clause 9)
  723. // having a non-trivial copy constructor, a non-trivial move constructor,
  724. // or a non-trivial destructor, with no corresponding parameter,
  725. // is conditionally-supported with implementation-defined semantics.
  726. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  727. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  728. if (!Record->hasNonTrivialCopyConstructor() &&
  729. !Record->hasNonTrivialMoveConstructor() &&
  730. !Record->hasNonTrivialDestructor())
  731. return VAK_ValidInCXX11;
  732. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  733. return VAK_Valid;
  734. if (Ty->isObjCObjectType())
  735. return VAK_Invalid;
  736. if (getLangOpts().MSVCCompat)
  737. return VAK_MSVCUndefined;
  738. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  739. // permitted to reject them. We should consider doing so.
  740. return VAK_Undefined;
  741. }
  742. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  743. // Don't allow one to pass an Objective-C interface to a vararg.
  744. const QualType &Ty = E->getType();
  745. VarArgKind VAK = isValidVarArgType(Ty);
  746. // Complain about passing non-POD types through varargs.
  747. switch (VAK) {
  748. case VAK_ValidInCXX11:
  749. DiagRuntimeBehavior(
  750. E->getBeginLoc(), nullptr,
  751. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
  752. LLVM_FALLTHROUGH;
  753. case VAK_Valid:
  754. if (Ty->isRecordType()) {
  755. // This is unlikely to be what the user intended. If the class has a
  756. // 'c_str' member function, the user probably meant to call that.
  757. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  758. PDiag(diag::warn_pass_class_arg_to_vararg)
  759. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  760. }
  761. break;
  762. case VAK_Undefined:
  763. case VAK_MSVCUndefined:
  764. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  765. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  766. << getLangOpts().CPlusPlus11 << Ty << CT);
  767. break;
  768. case VAK_Invalid:
  769. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  770. Diag(E->getBeginLoc(),
  771. diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
  772. << Ty << CT;
  773. else if (Ty->isObjCObjectType())
  774. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  775. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  776. << Ty << CT);
  777. else
  778. Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
  779. << isa<InitListExpr>(E) << Ty << CT;
  780. break;
  781. }
  782. }
  783. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  784. /// will create a trap if the resulting type is not a POD type.
  785. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  786. FunctionDecl *FDecl) {
  787. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  788. // Strip the unbridged-cast placeholder expression off, if applicable.
  789. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  790. (CT == VariadicMethod ||
  791. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  792. E = stripARCUnbridgedCast(E);
  793. // Otherwise, do normal placeholder checking.
  794. } else {
  795. ExprResult ExprRes = CheckPlaceholderExpr(E);
  796. if (ExprRes.isInvalid())
  797. return ExprError();
  798. E = ExprRes.get();
  799. }
  800. }
  801. ExprResult ExprRes = DefaultArgumentPromotion(E);
  802. if (ExprRes.isInvalid())
  803. return ExprError();
  804. E = ExprRes.get();
  805. // Diagnostics regarding non-POD argument types are
  806. // emitted along with format string checking in Sema::CheckFunctionCall().
  807. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  808. // Turn this into a trap.
  809. CXXScopeSpec SS;
  810. SourceLocation TemplateKWLoc;
  811. UnqualifiedId Name;
  812. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  813. E->getBeginLoc());
  814. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
  815. /*HasTrailingLParen=*/true,
  816. /*IsAddressOfOperand=*/false);
  817. if (TrapFn.isInvalid())
  818. return ExprError();
  819. ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
  820. None, E->getEndLoc());
  821. if (Call.isInvalid())
  822. return ExprError();
  823. ExprResult Comma =
  824. ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
  825. if (Comma.isInvalid())
  826. return ExprError();
  827. return Comma.get();
  828. }
  829. if (!getLangOpts().CPlusPlus &&
  830. RequireCompleteType(E->getExprLoc(), E->getType(),
  831. diag::err_call_incomplete_argument))
  832. return ExprError();
  833. return E;
  834. }
  835. /// Converts an integer to complex float type. Helper function of
  836. /// UsualArithmeticConversions()
  837. ///
  838. /// \return false if the integer expression is an integer type and is
  839. /// successfully converted to the complex type.
  840. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  841. ExprResult &ComplexExpr,
  842. QualType IntTy,
  843. QualType ComplexTy,
  844. bool SkipCast) {
  845. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  846. if (SkipCast) return false;
  847. if (IntTy->isIntegerType()) {
  848. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  849. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  850. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  851. CK_FloatingRealToComplex);
  852. } else {
  853. assert(IntTy->isComplexIntegerType());
  854. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  855. CK_IntegralComplexToFloatingComplex);
  856. }
  857. return false;
  858. }
  859. /// Handle arithmetic conversion with complex types. Helper function of
  860. /// UsualArithmeticConversions()
  861. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  862. ExprResult &RHS, QualType LHSType,
  863. QualType RHSType,
  864. bool IsCompAssign) {
  865. // if we have an integer operand, the result is the complex type.
  866. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  867. /*skipCast*/false))
  868. return LHSType;
  869. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  870. /*skipCast*/IsCompAssign))
  871. return RHSType;
  872. // This handles complex/complex, complex/float, or float/complex.
  873. // When both operands are complex, the shorter operand is converted to the
  874. // type of the longer, and that is the type of the result. This corresponds
  875. // to what is done when combining two real floating-point operands.
  876. // The fun begins when size promotion occur across type domains.
  877. // From H&S 6.3.4: When one operand is complex and the other is a real
  878. // floating-point type, the less precise type is converted, within it's
  879. // real or complex domain, to the precision of the other type. For example,
  880. // when combining a "long double" with a "double _Complex", the
  881. // "double _Complex" is promoted to "long double _Complex".
  882. // Compute the rank of the two types, regardless of whether they are complex.
  883. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  884. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  885. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  886. QualType LHSElementType =
  887. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  888. QualType RHSElementType =
  889. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  890. QualType ResultType = S.Context.getComplexType(LHSElementType);
  891. if (Order < 0) {
  892. // Promote the precision of the LHS if not an assignment.
  893. ResultType = S.Context.getComplexType(RHSElementType);
  894. if (!IsCompAssign) {
  895. if (LHSComplexType)
  896. LHS =
  897. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  898. else
  899. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  900. }
  901. } else if (Order > 0) {
  902. // Promote the precision of the RHS.
  903. if (RHSComplexType)
  904. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  905. else
  906. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  907. }
  908. return ResultType;
  909. }
  910. /// Handle arithmetic conversion from integer to float. Helper function
  911. /// of UsualArithmeticConversions()
  912. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  913. ExprResult &IntExpr,
  914. QualType FloatTy, QualType IntTy,
  915. bool ConvertFloat, bool ConvertInt) {
  916. if (IntTy->isIntegerType()) {
  917. if (ConvertInt)
  918. // Convert intExpr to the lhs floating point type.
  919. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  920. CK_IntegralToFloating);
  921. return FloatTy;
  922. }
  923. // Convert both sides to the appropriate complex float.
  924. assert(IntTy->isComplexIntegerType());
  925. QualType result = S.Context.getComplexType(FloatTy);
  926. // _Complex int -> _Complex float
  927. if (ConvertInt)
  928. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  929. CK_IntegralComplexToFloatingComplex);
  930. // float -> _Complex float
  931. if (ConvertFloat)
  932. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  933. CK_FloatingRealToComplex);
  934. return result;
  935. }
  936. /// Handle arithmethic conversion with floating point types. Helper
  937. /// function of UsualArithmeticConversions()
  938. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  939. ExprResult &RHS, QualType LHSType,
  940. QualType RHSType, bool IsCompAssign) {
  941. bool LHSFloat = LHSType->isRealFloatingType();
  942. bool RHSFloat = RHSType->isRealFloatingType();
  943. // If we have two real floating types, convert the smaller operand
  944. // to the bigger result.
  945. if (LHSFloat && RHSFloat) {
  946. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  947. if (order > 0) {
  948. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  949. return LHSType;
  950. }
  951. assert(order < 0 && "illegal float comparison");
  952. if (!IsCompAssign)
  953. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  954. return RHSType;
  955. }
  956. if (LHSFloat) {
  957. // Half FP has to be promoted to float unless it is natively supported
  958. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  959. LHSType = S.Context.FloatTy;
  960. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  961. /*ConvertFloat=*/!IsCompAssign,
  962. /*ConvertInt=*/ true);
  963. }
  964. assert(RHSFloat);
  965. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  966. /*convertInt=*/ true,
  967. /*convertFloat=*/!IsCompAssign);
  968. }
  969. /// Diagnose attempts to convert between __float128 and long double if
  970. /// there is no support for such conversion. Helper function of
  971. /// UsualArithmeticConversions().
  972. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  973. QualType RHSType) {
  974. /* No issue converting if at least one of the types is not a floating point
  975. type or the two types have the same rank.
  976. */
  977. if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
  978. S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
  979. return false;
  980. assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
  981. "The remaining types must be floating point types.");
  982. auto *LHSComplex = LHSType->getAs<ComplexType>();
  983. auto *RHSComplex = RHSType->getAs<ComplexType>();
  984. QualType LHSElemType = LHSComplex ?
  985. LHSComplex->getElementType() : LHSType;
  986. QualType RHSElemType = RHSComplex ?
  987. RHSComplex->getElementType() : RHSType;
  988. // No issue if the two types have the same representation
  989. if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
  990. &S.Context.getFloatTypeSemantics(RHSElemType))
  991. return false;
  992. bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
  993. RHSElemType == S.Context.LongDoubleTy);
  994. Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
  995. RHSElemType == S.Context.Float128Ty);
  996. // We've handled the situation where __float128 and long double have the same
  997. // representation. We allow all conversions for all possible long double types
  998. // except PPC's double double.
  999. return Float128AndLongDouble &&
  1000. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
  1001. &llvm::APFloat::PPCDoubleDouble());
  1002. }
  1003. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1004. namespace {
  1005. /// These helper callbacks are placed in an anonymous namespace to
  1006. /// permit their use as function template parameters.
  1007. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1008. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1009. }
  1010. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1011. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1012. CK_IntegralComplexCast);
  1013. }
  1014. }
  1015. /// Handle integer arithmetic conversions. Helper function of
  1016. /// UsualArithmeticConversions()
  1017. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1018. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1019. ExprResult &RHS, QualType LHSType,
  1020. QualType RHSType, bool IsCompAssign) {
  1021. // The rules for this case are in C99 6.3.1.8
  1022. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1023. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1024. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1025. if (LHSSigned == RHSSigned) {
  1026. // Same signedness; use the higher-ranked type
  1027. if (order >= 0) {
  1028. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1029. return LHSType;
  1030. } else if (!IsCompAssign)
  1031. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1032. return RHSType;
  1033. } else if (order != (LHSSigned ? 1 : -1)) {
  1034. // The unsigned type has greater than or equal rank to the
  1035. // signed type, so use the unsigned type
  1036. if (RHSSigned) {
  1037. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1038. return LHSType;
  1039. } else if (!IsCompAssign)
  1040. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1041. return RHSType;
  1042. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1043. // The two types are different widths; if we are here, that
  1044. // means the signed type is larger than the unsigned type, so
  1045. // use the signed type.
  1046. if (LHSSigned) {
  1047. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1048. return LHSType;
  1049. } else if (!IsCompAssign)
  1050. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1051. return RHSType;
  1052. } else {
  1053. // The signed type is higher-ranked than the unsigned type,
  1054. // but isn't actually any bigger (like unsigned int and long
  1055. // on most 32-bit systems). Use the unsigned type corresponding
  1056. // to the signed type.
  1057. QualType result =
  1058. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1059. RHS = (*doRHSCast)(S, RHS.get(), result);
  1060. if (!IsCompAssign)
  1061. LHS = (*doLHSCast)(S, LHS.get(), result);
  1062. return result;
  1063. }
  1064. }
  1065. /// Handle conversions with GCC complex int extension. Helper function
  1066. /// of UsualArithmeticConversions()
  1067. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1068. ExprResult &RHS, QualType LHSType,
  1069. QualType RHSType,
  1070. bool IsCompAssign) {
  1071. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1072. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1073. if (LHSComplexInt && RHSComplexInt) {
  1074. QualType LHSEltType = LHSComplexInt->getElementType();
  1075. QualType RHSEltType = RHSComplexInt->getElementType();
  1076. QualType ScalarType =
  1077. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1078. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1079. return S.Context.getComplexType(ScalarType);
  1080. }
  1081. if (LHSComplexInt) {
  1082. QualType LHSEltType = LHSComplexInt->getElementType();
  1083. QualType ScalarType =
  1084. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1085. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1086. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1087. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1088. CK_IntegralRealToComplex);
  1089. return ComplexType;
  1090. }
  1091. assert(RHSComplexInt);
  1092. QualType RHSEltType = RHSComplexInt->getElementType();
  1093. QualType ScalarType =
  1094. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1095. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1096. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1097. if (!IsCompAssign)
  1098. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1099. CK_IntegralRealToComplex);
  1100. return ComplexType;
  1101. }
  1102. /// Return the rank of a given fixed point or integer type. The value itself
  1103. /// doesn't matter, but the values must be increasing with proper increasing
  1104. /// rank as described in N1169 4.1.1.
  1105. static unsigned GetFixedPointRank(QualType Ty) {
  1106. const auto *BTy = Ty->getAs<BuiltinType>();
  1107. assert(BTy && "Expected a builtin type.");
  1108. switch (BTy->getKind()) {
  1109. case BuiltinType::ShortFract:
  1110. case BuiltinType::UShortFract:
  1111. case BuiltinType::SatShortFract:
  1112. case BuiltinType::SatUShortFract:
  1113. return 1;
  1114. case BuiltinType::Fract:
  1115. case BuiltinType::UFract:
  1116. case BuiltinType::SatFract:
  1117. case BuiltinType::SatUFract:
  1118. return 2;
  1119. case BuiltinType::LongFract:
  1120. case BuiltinType::ULongFract:
  1121. case BuiltinType::SatLongFract:
  1122. case BuiltinType::SatULongFract:
  1123. return 3;
  1124. case BuiltinType::ShortAccum:
  1125. case BuiltinType::UShortAccum:
  1126. case BuiltinType::SatShortAccum:
  1127. case BuiltinType::SatUShortAccum:
  1128. return 4;
  1129. case BuiltinType::Accum:
  1130. case BuiltinType::UAccum:
  1131. case BuiltinType::SatAccum:
  1132. case BuiltinType::SatUAccum:
  1133. return 5;
  1134. case BuiltinType::LongAccum:
  1135. case BuiltinType::ULongAccum:
  1136. case BuiltinType::SatLongAccum:
  1137. case BuiltinType::SatULongAccum:
  1138. return 6;
  1139. default:
  1140. if (BTy->isInteger())
  1141. return 0;
  1142. llvm_unreachable("Unexpected fixed point or integer type");
  1143. }
  1144. }
  1145. /// handleFixedPointConversion - Fixed point operations between fixed
  1146. /// point types and integers or other fixed point types do not fall under
  1147. /// usual arithmetic conversion since these conversions could result in loss
  1148. /// of precsision (N1169 4.1.4). These operations should be calculated with
  1149. /// the full precision of their result type (N1169 4.1.6.2.1).
  1150. static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
  1151. QualType RHSTy) {
  1152. assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
  1153. "Expected at least one of the operands to be a fixed point type");
  1154. assert((LHSTy->isFixedPointOrIntegerType() ||
  1155. RHSTy->isFixedPointOrIntegerType()) &&
  1156. "Special fixed point arithmetic operation conversions are only "
  1157. "applied to ints or other fixed point types");
  1158. // If one operand has signed fixed-point type and the other operand has
  1159. // unsigned fixed-point type, then the unsigned fixed-point operand is
  1160. // converted to its corresponding signed fixed-point type and the resulting
  1161. // type is the type of the converted operand.
  1162. if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
  1163. LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
  1164. else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
  1165. RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
  1166. // The result type is the type with the highest rank, whereby a fixed-point
  1167. // conversion rank is always greater than an integer conversion rank; if the
  1168. // type of either of the operands is a saturating fixedpoint type, the result
  1169. // type shall be the saturating fixed-point type corresponding to the type
  1170. // with the highest rank; the resulting value is converted (taking into
  1171. // account rounding and overflow) to the precision of the resulting type.
  1172. // Same ranks between signed and unsigned types are resolved earlier, so both
  1173. // types are either signed or both unsigned at this point.
  1174. unsigned LHSTyRank = GetFixedPointRank(LHSTy);
  1175. unsigned RHSTyRank = GetFixedPointRank(RHSTy);
  1176. QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
  1177. if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
  1178. ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
  1179. return ResultTy;
  1180. }
  1181. /// UsualArithmeticConversions - Performs various conversions that are common to
  1182. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1183. /// routine returns the first non-arithmetic type found. The client is
  1184. /// responsible for emitting appropriate error diagnostics.
  1185. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1186. bool IsCompAssign) {
  1187. if (!IsCompAssign) {
  1188. LHS = UsualUnaryConversions(LHS.get());
  1189. if (LHS.isInvalid())
  1190. return QualType();
  1191. }
  1192. RHS = UsualUnaryConversions(RHS.get());
  1193. if (RHS.isInvalid())
  1194. return QualType();
  1195. // For conversion purposes, we ignore any qualifiers.
  1196. // For example, "const float" and "float" are equivalent.
  1197. QualType LHSType =
  1198. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1199. QualType RHSType =
  1200. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1201. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1202. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1203. LHSType = AtomicLHS->getValueType();
  1204. // If both types are identical, no conversion is needed.
  1205. if (LHSType == RHSType)
  1206. return LHSType;
  1207. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1208. // The caller can deal with this (e.g. pointer + int).
  1209. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1210. return QualType();
  1211. // Apply unary and bitfield promotions to the LHS's type.
  1212. QualType LHSUnpromotedType = LHSType;
  1213. if (LHSType->isPromotableIntegerType())
  1214. LHSType = Context.getPromotedIntegerType(LHSType);
  1215. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1216. if (!LHSBitfieldPromoteTy.isNull())
  1217. LHSType = LHSBitfieldPromoteTy;
  1218. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1219. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1220. // If both types are identical, no conversion is needed.
  1221. if (LHSType == RHSType)
  1222. return LHSType;
  1223. // At this point, we have two different arithmetic types.
  1224. // Diagnose attempts to convert between __float128 and long double where
  1225. // such conversions currently can't be handled.
  1226. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1227. return QualType();
  1228. // Handle complex types first (C99 6.3.1.8p1).
  1229. if (LHSType->isComplexType() || RHSType->isComplexType())
  1230. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1231. IsCompAssign);
  1232. // Now handle "real" floating types (i.e. float, double, long double).
  1233. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1234. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1235. IsCompAssign);
  1236. // Handle GCC complex int extension.
  1237. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1238. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1239. IsCompAssign);
  1240. if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
  1241. return handleFixedPointConversion(*this, LHSType, RHSType);
  1242. // Finally, we have two differing integer types.
  1243. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1244. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1245. }
  1246. //===----------------------------------------------------------------------===//
  1247. // Semantic Analysis for various Expression Types
  1248. //===----------------------------------------------------------------------===//
  1249. ExprResult
  1250. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1251. SourceLocation DefaultLoc,
  1252. SourceLocation RParenLoc,
  1253. Expr *ControllingExpr,
  1254. ArrayRef<ParsedType> ArgTypes,
  1255. ArrayRef<Expr *> ArgExprs) {
  1256. unsigned NumAssocs = ArgTypes.size();
  1257. assert(NumAssocs == ArgExprs.size());
  1258. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1259. for (unsigned i = 0; i < NumAssocs; ++i) {
  1260. if (ArgTypes[i])
  1261. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1262. else
  1263. Types[i] = nullptr;
  1264. }
  1265. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1266. ControllingExpr,
  1267. llvm::makeArrayRef(Types, NumAssocs),
  1268. ArgExprs);
  1269. delete [] Types;
  1270. return ER;
  1271. }
  1272. ExprResult
  1273. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1274. SourceLocation DefaultLoc,
  1275. SourceLocation RParenLoc,
  1276. Expr *ControllingExpr,
  1277. ArrayRef<TypeSourceInfo *> Types,
  1278. ArrayRef<Expr *> Exprs) {
  1279. unsigned NumAssocs = Types.size();
  1280. assert(NumAssocs == Exprs.size());
  1281. // Decay and strip qualifiers for the controlling expression type, and handle
  1282. // placeholder type replacement. See committee discussion from WG14 DR423.
  1283. {
  1284. EnterExpressionEvaluationContext Unevaluated(
  1285. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1286. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1287. if (R.isInvalid())
  1288. return ExprError();
  1289. ControllingExpr = R.get();
  1290. }
  1291. // The controlling expression is an unevaluated operand, so side effects are
  1292. // likely unintended.
  1293. if (!inTemplateInstantiation() &&
  1294. ControllingExpr->HasSideEffects(Context, false))
  1295. Diag(ControllingExpr->getExprLoc(),
  1296. diag::warn_side_effects_unevaluated_context);
  1297. bool TypeErrorFound = false,
  1298. IsResultDependent = ControllingExpr->isTypeDependent(),
  1299. ContainsUnexpandedParameterPack
  1300. = ControllingExpr->containsUnexpandedParameterPack();
  1301. for (unsigned i = 0; i < NumAssocs; ++i) {
  1302. if (Exprs[i]->containsUnexpandedParameterPack())
  1303. ContainsUnexpandedParameterPack = true;
  1304. if (Types[i]) {
  1305. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1306. ContainsUnexpandedParameterPack = true;
  1307. if (Types[i]->getType()->isDependentType()) {
  1308. IsResultDependent = true;
  1309. } else {
  1310. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1311. // complete object type other than a variably modified type."
  1312. unsigned D = 0;
  1313. if (Types[i]->getType()->isIncompleteType())
  1314. D = diag::err_assoc_type_incomplete;
  1315. else if (!Types[i]->getType()->isObjectType())
  1316. D = diag::err_assoc_type_nonobject;
  1317. else if (Types[i]->getType()->isVariablyModifiedType())
  1318. D = diag::err_assoc_type_variably_modified;
  1319. if (D != 0) {
  1320. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1321. << Types[i]->getTypeLoc().getSourceRange()
  1322. << Types[i]->getType();
  1323. TypeErrorFound = true;
  1324. }
  1325. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1326. // selection shall specify compatible types."
  1327. for (unsigned j = i+1; j < NumAssocs; ++j)
  1328. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1329. Context.typesAreCompatible(Types[i]->getType(),
  1330. Types[j]->getType())) {
  1331. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1332. diag::err_assoc_compatible_types)
  1333. << Types[j]->getTypeLoc().getSourceRange()
  1334. << Types[j]->getType()
  1335. << Types[i]->getType();
  1336. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1337. diag::note_compat_assoc)
  1338. << Types[i]->getTypeLoc().getSourceRange()
  1339. << Types[i]->getType();
  1340. TypeErrorFound = true;
  1341. }
  1342. }
  1343. }
  1344. }
  1345. if (TypeErrorFound)
  1346. return ExprError();
  1347. // If we determined that the generic selection is result-dependent, don't
  1348. // try to compute the result expression.
  1349. if (IsResultDependent)
  1350. return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
  1351. Exprs, DefaultLoc, RParenLoc,
  1352. ContainsUnexpandedParameterPack);
  1353. SmallVector<unsigned, 1> CompatIndices;
  1354. unsigned DefaultIndex = -1U;
  1355. for (unsigned i = 0; i < NumAssocs; ++i) {
  1356. if (!Types[i])
  1357. DefaultIndex = i;
  1358. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1359. Types[i]->getType()))
  1360. CompatIndices.push_back(i);
  1361. }
  1362. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1363. // type compatible with at most one of the types named in its generic
  1364. // association list."
  1365. if (CompatIndices.size() > 1) {
  1366. // We strip parens here because the controlling expression is typically
  1367. // parenthesized in macro definitions.
  1368. ControllingExpr = ControllingExpr->IgnoreParens();
  1369. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
  1370. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1371. << (unsigned)CompatIndices.size();
  1372. for (unsigned I : CompatIndices) {
  1373. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1374. diag::note_compat_assoc)
  1375. << Types[I]->getTypeLoc().getSourceRange()
  1376. << Types[I]->getType();
  1377. }
  1378. return ExprError();
  1379. }
  1380. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1381. // its controlling expression shall have type compatible with exactly one of
  1382. // the types named in its generic association list."
  1383. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1384. // We strip parens here because the controlling expression is typically
  1385. // parenthesized in macro definitions.
  1386. ControllingExpr = ControllingExpr->IgnoreParens();
  1387. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
  1388. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1389. return ExprError();
  1390. }
  1391. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1392. // type name that is compatible with the type of the controlling expression,
  1393. // then the result expression of the generic selection is the expression
  1394. // in that generic association. Otherwise, the result expression of the
  1395. // generic selection is the expression in the default generic association."
  1396. unsigned ResultIndex =
  1397. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1398. return GenericSelectionExpr::Create(
  1399. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1400. ContainsUnexpandedParameterPack, ResultIndex);
  1401. }
  1402. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1403. /// location of the token and the offset of the ud-suffix within it.
  1404. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1405. unsigned Offset) {
  1406. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1407. S.getLangOpts());
  1408. }
  1409. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1410. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1411. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1412. IdentifierInfo *UDSuffix,
  1413. SourceLocation UDSuffixLoc,
  1414. ArrayRef<Expr*> Args,
  1415. SourceLocation LitEndLoc) {
  1416. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1417. QualType ArgTy[2];
  1418. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1419. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1420. if (ArgTy[ArgIdx]->isArrayType())
  1421. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1422. }
  1423. DeclarationName OpName =
  1424. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1425. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1426. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1427. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1428. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1429. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1430. /*AllowStringTemplate*/ false,
  1431. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1432. return ExprError();
  1433. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1434. }
  1435. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1436. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1437. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1438. /// multiple tokens. However, the common case is that StringToks points to one
  1439. /// string.
  1440. ///
  1441. ExprResult
  1442. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1443. assert(!StringToks.empty() && "Must have at least one string!");
  1444. StringLiteralParser Literal(StringToks, PP);
  1445. if (Literal.hadError)
  1446. return ExprError();
  1447. SmallVector<SourceLocation, 4> StringTokLocs;
  1448. for (const Token &Tok : StringToks)
  1449. StringTokLocs.push_back(Tok.getLocation());
  1450. QualType CharTy = Context.CharTy;
  1451. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1452. if (Literal.isWide()) {
  1453. CharTy = Context.getWideCharType();
  1454. Kind = StringLiteral::Wide;
  1455. } else if (Literal.isUTF8()) {
  1456. if (getLangOpts().Char8)
  1457. CharTy = Context.Char8Ty;
  1458. Kind = StringLiteral::UTF8;
  1459. } else if (Literal.isUTF16()) {
  1460. CharTy = Context.Char16Ty;
  1461. Kind = StringLiteral::UTF16;
  1462. } else if (Literal.isUTF32()) {
  1463. CharTy = Context.Char32Ty;
  1464. Kind = StringLiteral::UTF32;
  1465. } else if (Literal.isPascal()) {
  1466. CharTy = Context.UnsignedCharTy;
  1467. }
  1468. // Warn on initializing an array of char from a u8 string literal; this
  1469. // becomes ill-formed in C++2a.
  1470. if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
  1471. !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
  1472. Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
  1473. // Create removals for all 'u8' prefixes in the string literal(s). This
  1474. // ensures C++2a compatibility (but may change the program behavior when
  1475. // built by non-Clang compilers for which the execution character set is
  1476. // not always UTF-8).
  1477. auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
  1478. SourceLocation RemovalDiagLoc;
  1479. for (const Token &Tok : StringToks) {
  1480. if (Tok.getKind() == tok::utf8_string_literal) {
  1481. if (RemovalDiagLoc.isInvalid())
  1482. RemovalDiagLoc = Tok.getLocation();
  1483. RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
  1484. Tok.getLocation(),
  1485. Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
  1486. getSourceManager(), getLangOpts())));
  1487. }
  1488. }
  1489. Diag(RemovalDiagLoc, RemovalDiag);
  1490. }
  1491. QualType StrTy =
  1492. Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
  1493. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1494. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1495. Kind, Literal.Pascal, StrTy,
  1496. &StringTokLocs[0],
  1497. StringTokLocs.size());
  1498. if (Literal.getUDSuffix().empty())
  1499. return Lit;
  1500. // We're building a user-defined literal.
  1501. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1502. SourceLocation UDSuffixLoc =
  1503. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1504. Literal.getUDSuffixOffset());
  1505. // Make sure we're allowed user-defined literals here.
  1506. if (!UDLScope)
  1507. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1508. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1509. // operator "" X (str, len)
  1510. QualType SizeType = Context.getSizeType();
  1511. DeclarationName OpName =
  1512. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1513. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1514. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1515. QualType ArgTy[] = {
  1516. Context.getArrayDecayedType(StrTy), SizeType
  1517. };
  1518. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1519. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1520. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1521. /*AllowStringTemplate*/ true,
  1522. /*DiagnoseMissing*/ true)) {
  1523. case LOLR_Cooked: {
  1524. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1525. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1526. StringTokLocs[0]);
  1527. Expr *Args[] = { Lit, LenArg };
  1528. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1529. }
  1530. case LOLR_StringTemplate: {
  1531. TemplateArgumentListInfo ExplicitArgs;
  1532. unsigned CharBits = Context.getIntWidth(CharTy);
  1533. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1534. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1535. TemplateArgument TypeArg(CharTy);
  1536. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1537. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1538. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1539. Value = Lit->getCodeUnit(I);
  1540. TemplateArgument Arg(Context, Value, CharTy);
  1541. TemplateArgumentLocInfo ArgInfo;
  1542. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1543. }
  1544. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1545. &ExplicitArgs);
  1546. }
  1547. case LOLR_Raw:
  1548. case LOLR_Template:
  1549. case LOLR_ErrorNoDiagnostic:
  1550. llvm_unreachable("unexpected literal operator lookup result");
  1551. case LOLR_Error:
  1552. return ExprError();
  1553. }
  1554. llvm_unreachable("unexpected literal operator lookup result");
  1555. }
  1556. DeclRefExpr *
  1557. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1558. SourceLocation Loc,
  1559. const CXXScopeSpec *SS) {
  1560. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1561. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1562. }
  1563. DeclRefExpr *
  1564. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1565. const DeclarationNameInfo &NameInfo,
  1566. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1567. SourceLocation TemplateKWLoc,
  1568. const TemplateArgumentListInfo *TemplateArgs) {
  1569. NestedNameSpecifierLoc NNS =
  1570. SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
  1571. return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
  1572. TemplateArgs);
  1573. }
  1574. NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
  1575. // A declaration named in an unevaluated operand never constitutes an odr-use.
  1576. if (isUnevaluatedContext())
  1577. return NOUR_Unevaluated;
  1578. // C++2a [basic.def.odr]p4:
  1579. // A variable x whose name appears as a potentially-evaluated expression e
  1580. // is odr-used by e unless [...] x is a reference that is usable in
  1581. // constant expressions.
  1582. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1583. if (VD->getType()->isReferenceType() &&
  1584. !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
  1585. VD->isUsableInConstantExpressions(Context))
  1586. return NOUR_Constant;
  1587. }
  1588. // All remaining non-variable cases constitute an odr-use. For variables, we
  1589. // need to wait and see how the expression is used.
  1590. return NOUR_None;
  1591. }
  1592. /// BuildDeclRefExpr - Build an expression that references a
  1593. /// declaration that does not require a closure capture.
  1594. DeclRefExpr *
  1595. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1596. const DeclarationNameInfo &NameInfo,
  1597. NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
  1598. SourceLocation TemplateKWLoc,
  1599. const TemplateArgumentListInfo *TemplateArgs) {
  1600. bool RefersToCapturedVariable =
  1601. isa<VarDecl>(D) &&
  1602. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1603. DeclRefExpr *E = DeclRefExpr::Create(
  1604. Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
  1605. VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
  1606. MarkDeclRefReferenced(E);
  1607. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1608. Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
  1609. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
  1610. getCurFunction()->recordUseOfWeak(E);
  1611. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1612. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1613. FD = IFD->getAnonField();
  1614. if (FD) {
  1615. UnusedPrivateFields.remove(FD);
  1616. // Just in case we're building an illegal pointer-to-member.
  1617. if (FD->isBitField())
  1618. E->setObjectKind(OK_BitField);
  1619. }
  1620. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1621. // designates a bit-field.
  1622. if (auto *BD = dyn_cast<BindingDecl>(D))
  1623. if (auto *BE = BD->getBinding())
  1624. E->setObjectKind(BE->getObjectKind());
  1625. return E;
  1626. }
  1627. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1628. /// possibly a list of template arguments.
  1629. ///
  1630. /// If this produces template arguments, it is permitted to call
  1631. /// DecomposeTemplateName.
  1632. ///
  1633. /// This actually loses a lot of source location information for
  1634. /// non-standard name kinds; we should consider preserving that in
  1635. /// some way.
  1636. void
  1637. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1638. TemplateArgumentListInfo &Buffer,
  1639. DeclarationNameInfo &NameInfo,
  1640. const TemplateArgumentListInfo *&TemplateArgs) {
  1641. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
  1642. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1643. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1644. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1645. Id.TemplateId->NumArgs);
  1646. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1647. TemplateName TName = Id.TemplateId->Template.get();
  1648. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1649. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1650. TemplateArgs = &Buffer;
  1651. } else {
  1652. NameInfo = GetNameFromUnqualifiedId(Id);
  1653. TemplateArgs = nullptr;
  1654. }
  1655. }
  1656. static void emitEmptyLookupTypoDiagnostic(
  1657. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1658. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1659. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1660. DeclContext *Ctx =
  1661. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1662. if (!TC) {
  1663. // Emit a special diagnostic for failed member lookups.
  1664. // FIXME: computing the declaration context might fail here (?)
  1665. if (Ctx)
  1666. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1667. << SS.getRange();
  1668. else
  1669. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1670. return;
  1671. }
  1672. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1673. bool DroppedSpecifier =
  1674. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1675. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1676. ? diag::note_implicit_param_decl
  1677. : diag::note_previous_decl;
  1678. if (!Ctx)
  1679. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1680. SemaRef.PDiag(NoteID));
  1681. else
  1682. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1683. << Typo << Ctx << DroppedSpecifier
  1684. << SS.getRange(),
  1685. SemaRef.PDiag(NoteID));
  1686. }
  1687. /// Diagnose an empty lookup.
  1688. ///
  1689. /// \return false if new lookup candidates were found
  1690. bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1691. CorrectionCandidateCallback &CCC,
  1692. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1693. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1694. DeclarationName Name = R.getLookupName();
  1695. unsigned diagnostic = diag::err_undeclared_var_use;
  1696. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1697. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1698. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1699. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1700. diagnostic = diag::err_undeclared_use;
  1701. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1702. }
  1703. // If the original lookup was an unqualified lookup, fake an
  1704. // unqualified lookup. This is useful when (for example) the
  1705. // original lookup would not have found something because it was a
  1706. // dependent name.
  1707. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1708. while (DC) {
  1709. if (isa<CXXRecordDecl>(DC)) {
  1710. LookupQualifiedName(R, DC);
  1711. if (!R.empty()) {
  1712. // Don't give errors about ambiguities in this lookup.
  1713. R.suppressDiagnostics();
  1714. // During a default argument instantiation the CurContext points
  1715. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1716. // function parameter list, hence add an explicit check.
  1717. bool isDefaultArgument =
  1718. !CodeSynthesisContexts.empty() &&
  1719. CodeSynthesisContexts.back().Kind ==
  1720. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1721. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1722. bool isInstance = CurMethod &&
  1723. CurMethod->isInstance() &&
  1724. DC == CurMethod->getParent() && !isDefaultArgument;
  1725. // Give a code modification hint to insert 'this->'.
  1726. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1727. // Actually quite difficult!
  1728. if (getLangOpts().MSVCCompat)
  1729. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1730. if (isInstance) {
  1731. Diag(R.getNameLoc(), diagnostic) << Name
  1732. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1733. CheckCXXThisCapture(R.getNameLoc());
  1734. } else {
  1735. Diag(R.getNameLoc(), diagnostic) << Name;
  1736. }
  1737. // Do we really want to note all of these?
  1738. for (NamedDecl *D : R)
  1739. Diag(D->getLocation(), diag::note_dependent_var_use);
  1740. // Return true if we are inside a default argument instantiation
  1741. // and the found name refers to an instance member function, otherwise
  1742. // the function calling DiagnoseEmptyLookup will try to create an
  1743. // implicit member call and this is wrong for default argument.
  1744. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1745. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1746. return true;
  1747. }
  1748. // Tell the callee to try to recover.
  1749. return false;
  1750. }
  1751. R.clear();
  1752. }
  1753. DC = DC->getLookupParent();
  1754. }
  1755. // We didn't find anything, so try to correct for a typo.
  1756. TypoCorrection Corrected;
  1757. if (S && Out) {
  1758. SourceLocation TypoLoc = R.getNameLoc();
  1759. assert(!ExplicitTemplateArgs &&
  1760. "Diagnosing an empty lookup with explicit template args!");
  1761. *Out = CorrectTypoDelayed(
  1762. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  1763. [=](const TypoCorrection &TC) {
  1764. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1765. diagnostic, diagnostic_suggest);
  1766. },
  1767. nullptr, CTK_ErrorRecovery);
  1768. if (*Out)
  1769. return true;
  1770. } else if (S &&
  1771. (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
  1772. S, &SS, CCC, CTK_ErrorRecovery))) {
  1773. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1774. bool DroppedSpecifier =
  1775. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1776. R.setLookupName(Corrected.getCorrection());
  1777. bool AcceptableWithRecovery = false;
  1778. bool AcceptableWithoutRecovery = false;
  1779. NamedDecl *ND = Corrected.getFoundDecl();
  1780. if (ND) {
  1781. if (Corrected.isOverloaded()) {
  1782. OverloadCandidateSet OCS(R.getNameLoc(),
  1783. OverloadCandidateSet::CSK_Normal);
  1784. OverloadCandidateSet::iterator Best;
  1785. for (NamedDecl *CD : Corrected) {
  1786. if (FunctionTemplateDecl *FTD =
  1787. dyn_cast<FunctionTemplateDecl>(CD))
  1788. AddTemplateOverloadCandidate(
  1789. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1790. Args, OCS);
  1791. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  1792. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1793. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1794. Args, OCS);
  1795. }
  1796. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1797. case OR_Success:
  1798. ND = Best->FoundDecl;
  1799. Corrected.setCorrectionDecl(ND);
  1800. break;
  1801. default:
  1802. // FIXME: Arbitrarily pick the first declaration for the note.
  1803. Corrected.setCorrectionDecl(ND);
  1804. break;
  1805. }
  1806. }
  1807. R.addDecl(ND);
  1808. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1809. CXXRecordDecl *Record = nullptr;
  1810. if (Corrected.getCorrectionSpecifier()) {
  1811. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1812. Record = Ty->getAsCXXRecordDecl();
  1813. }
  1814. if (!Record)
  1815. Record = cast<CXXRecordDecl>(
  1816. ND->getDeclContext()->getRedeclContext());
  1817. R.setNamingClass(Record);
  1818. }
  1819. auto *UnderlyingND = ND->getUnderlyingDecl();
  1820. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  1821. isa<FunctionTemplateDecl>(UnderlyingND);
  1822. // FIXME: If we ended up with a typo for a type name or
  1823. // Objective-C class name, we're in trouble because the parser
  1824. // is in the wrong place to recover. Suggest the typo
  1825. // correction, but don't make it a fix-it since we're not going
  1826. // to recover well anyway.
  1827. AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
  1828. getAsTypeTemplateDecl(UnderlyingND) ||
  1829. isa<ObjCInterfaceDecl>(UnderlyingND);
  1830. } else {
  1831. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1832. // because we aren't able to recover.
  1833. AcceptableWithoutRecovery = true;
  1834. }
  1835. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1836. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  1837. ? diag::note_implicit_param_decl
  1838. : diag::note_previous_decl;
  1839. if (SS.isEmpty())
  1840. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1841. PDiag(NoteID), AcceptableWithRecovery);
  1842. else
  1843. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1844. << Name << computeDeclContext(SS, false)
  1845. << DroppedSpecifier << SS.getRange(),
  1846. PDiag(NoteID), AcceptableWithRecovery);
  1847. // Tell the callee whether to try to recover.
  1848. return !AcceptableWithRecovery;
  1849. }
  1850. }
  1851. R.clear();
  1852. // Emit a special diagnostic for failed member lookups.
  1853. // FIXME: computing the declaration context might fail here (?)
  1854. if (!SS.isEmpty()) {
  1855. Diag(R.getNameLoc(), diag::err_no_member)
  1856. << Name << computeDeclContext(SS, false)
  1857. << SS.getRange();
  1858. return true;
  1859. }
  1860. // Give up, we can't recover.
  1861. Diag(R.getNameLoc(), diagnostic) << Name;
  1862. return true;
  1863. }
  1864. /// In Microsoft mode, if we are inside a template class whose parent class has
  1865. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1866. /// assume the identifier is a member of a dependent base class. We can only
  1867. /// recover successfully in static methods, instance methods, and other contexts
  1868. /// where 'this' is available. This doesn't precisely match MSVC's
  1869. /// instantiation model, but it's close enough.
  1870. static Expr *
  1871. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1872. DeclarationNameInfo &NameInfo,
  1873. SourceLocation TemplateKWLoc,
  1874. const TemplateArgumentListInfo *TemplateArgs) {
  1875. // Only try to recover from lookup into dependent bases in static methods or
  1876. // contexts where 'this' is available.
  1877. QualType ThisType = S.getCurrentThisType();
  1878. const CXXRecordDecl *RD = nullptr;
  1879. if (!ThisType.isNull())
  1880. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1881. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1882. RD = MD->getParent();
  1883. if (!RD || !RD->hasAnyDependentBases())
  1884. return nullptr;
  1885. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1886. // is available, suggest inserting 'this->' as a fixit.
  1887. SourceLocation Loc = NameInfo.getLoc();
  1888. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1889. DB << NameInfo.getName() << RD;
  1890. if (!ThisType.isNull()) {
  1891. DB << FixItHint::CreateInsertion(Loc, "this->");
  1892. return CXXDependentScopeMemberExpr::Create(
  1893. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1894. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1895. /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
  1896. }
  1897. // Synthesize a fake NNS that points to the derived class. This will
  1898. // perform name lookup during template instantiation.
  1899. CXXScopeSpec SS;
  1900. auto *NNS =
  1901. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1902. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1903. return DependentScopeDeclRefExpr::Create(
  1904. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1905. TemplateArgs);
  1906. }
  1907. ExprResult
  1908. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1909. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1910. bool HasTrailingLParen, bool IsAddressOfOperand,
  1911. CorrectionCandidateCallback *CCC,
  1912. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1913. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1914. "cannot be direct & operand and have a trailing lparen");
  1915. if (SS.isInvalid())
  1916. return ExprError();
  1917. TemplateArgumentListInfo TemplateArgsBuffer;
  1918. // Decompose the UnqualifiedId into the following data.
  1919. DeclarationNameInfo NameInfo;
  1920. const TemplateArgumentListInfo *TemplateArgs;
  1921. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1922. DeclarationName Name = NameInfo.getName();
  1923. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1924. SourceLocation NameLoc = NameInfo.getLoc();
  1925. if (II && II->isEditorPlaceholder()) {
  1926. // FIXME: When typed placeholders are supported we can create a typed
  1927. // placeholder expression node.
  1928. return ExprError();
  1929. }
  1930. // C++ [temp.dep.expr]p3:
  1931. // An id-expression is type-dependent if it contains:
  1932. // -- an identifier that was declared with a dependent type,
  1933. // (note: handled after lookup)
  1934. // -- a template-id that is dependent,
  1935. // (note: handled in BuildTemplateIdExpr)
  1936. // -- a conversion-function-id that specifies a dependent type,
  1937. // -- a nested-name-specifier that contains a class-name that
  1938. // names a dependent type.
  1939. // Determine whether this is a member of an unknown specialization;
  1940. // we need to handle these differently.
  1941. bool DependentID = false;
  1942. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1943. Name.getCXXNameType()->isDependentType()) {
  1944. DependentID = true;
  1945. } else if (SS.isSet()) {
  1946. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1947. if (RequireCompleteDeclContext(SS, DC))
  1948. return ExprError();
  1949. } else {
  1950. DependentID = true;
  1951. }
  1952. }
  1953. if (DependentID)
  1954. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1955. IsAddressOfOperand, TemplateArgs);
  1956. // Perform the required lookup.
  1957. LookupResult R(*this, NameInfo,
  1958. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  1959. ? LookupObjCImplicitSelfParam
  1960. : LookupOrdinaryName);
  1961. if (TemplateKWLoc.isValid() || TemplateArgs) {
  1962. // Lookup the template name again to correctly establish the context in
  1963. // which it was found. This is really unfortunate as we already did the
  1964. // lookup to determine that it was a template name in the first place. If
  1965. // this becomes a performance hit, we can work harder to preserve those
  1966. // results until we get here but it's likely not worth it.
  1967. bool MemberOfUnknownSpecialization;
  1968. AssumedTemplateKind AssumedTemplate;
  1969. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1970. MemberOfUnknownSpecialization, TemplateKWLoc,
  1971. &AssumedTemplate))
  1972. return ExprError();
  1973. if (MemberOfUnknownSpecialization ||
  1974. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1975. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1976. IsAddressOfOperand, TemplateArgs);
  1977. } else {
  1978. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1979. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1980. // If the result might be in a dependent base class, this is a dependent
  1981. // id-expression.
  1982. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1983. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1984. IsAddressOfOperand, TemplateArgs);
  1985. // If this reference is in an Objective-C method, then we need to do
  1986. // some special Objective-C lookup, too.
  1987. if (IvarLookupFollowUp) {
  1988. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1989. if (E.isInvalid())
  1990. return ExprError();
  1991. if (Expr *Ex = E.getAs<Expr>())
  1992. return Ex;
  1993. }
  1994. }
  1995. if (R.isAmbiguous())
  1996. return ExprError();
  1997. // This could be an implicitly declared function reference (legal in C90,
  1998. // extension in C99, forbidden in C++).
  1999. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  2000. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  2001. if (D) R.addDecl(D);
  2002. }
  2003. // Determine whether this name might be a candidate for
  2004. // argument-dependent lookup.
  2005. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  2006. if (R.empty() && !ADL) {
  2007. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  2008. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  2009. TemplateKWLoc, TemplateArgs))
  2010. return E;
  2011. }
  2012. // Don't diagnose an empty lookup for inline assembly.
  2013. if (IsInlineAsmIdentifier)
  2014. return ExprError();
  2015. // If this name wasn't predeclared and if this is not a function
  2016. // call, diagnose the problem.
  2017. TypoExpr *TE = nullptr;
  2018. DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
  2019. : nullptr);
  2020. DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
  2021. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  2022. "Typo correction callback misconfigured");
  2023. if (CCC) {
  2024. // Make sure the callback knows what the typo being diagnosed is.
  2025. CCC->setTypoName(II);
  2026. if (SS.isValid())
  2027. CCC->setTypoNNS(SS.getScopeRep());
  2028. }
  2029. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  2030. // a template name, but we happen to have always already looked up the name
  2031. // before we get here if it must be a template name.
  2032. if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
  2033. None, &TE)) {
  2034. if (TE && KeywordReplacement) {
  2035. auto &State = getTypoExprState(TE);
  2036. auto BestTC = State.Consumer->getNextCorrection();
  2037. if (BestTC.isKeyword()) {
  2038. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  2039. if (State.DiagHandler)
  2040. State.DiagHandler(BestTC);
  2041. KeywordReplacement->startToken();
  2042. KeywordReplacement->setKind(II->getTokenID());
  2043. KeywordReplacement->setIdentifierInfo(II);
  2044. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  2045. // Clean up the state associated with the TypoExpr, since it has
  2046. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  2047. clearDelayedTypo(TE);
  2048. // Signal that a correction to a keyword was performed by returning a
  2049. // valid-but-null ExprResult.
  2050. return (Expr*)nullptr;
  2051. }
  2052. State.Consumer->resetCorrectionStream();
  2053. }
  2054. return TE ? TE : ExprError();
  2055. }
  2056. assert(!R.empty() &&
  2057. "DiagnoseEmptyLookup returned false but added no results");
  2058. // If we found an Objective-C instance variable, let
  2059. // LookupInObjCMethod build the appropriate expression to
  2060. // reference the ivar.
  2061. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  2062. R.clear();
  2063. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  2064. // In a hopelessly buggy code, Objective-C instance variable
  2065. // lookup fails and no expression will be built to reference it.
  2066. if (!E.isInvalid() && !E.get())
  2067. return ExprError();
  2068. return E;
  2069. }
  2070. }
  2071. // This is guaranteed from this point on.
  2072. assert(!R.empty() || ADL);
  2073. // Check whether this might be a C++ implicit instance member access.
  2074. // C++ [class.mfct.non-static]p3:
  2075. // When an id-expression that is not part of a class member access
  2076. // syntax and not used to form a pointer to member is used in the
  2077. // body of a non-static member function of class X, if name lookup
  2078. // resolves the name in the id-expression to a non-static non-type
  2079. // member of some class C, the id-expression is transformed into a
  2080. // class member access expression using (*this) as the
  2081. // postfix-expression to the left of the . operator.
  2082. //
  2083. // But we don't actually need to do this for '&' operands if R
  2084. // resolved to a function or overloaded function set, because the
  2085. // expression is ill-formed if it actually works out to be a
  2086. // non-static member function:
  2087. //
  2088. // C++ [expr.ref]p4:
  2089. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2090. // [t]he expression can be used only as the left-hand operand of a
  2091. // member function call.
  2092. //
  2093. // There are other safeguards against such uses, but it's important
  2094. // to get this right here so that we don't end up making a
  2095. // spuriously dependent expression if we're inside a dependent
  2096. // instance method.
  2097. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2098. bool MightBeImplicitMember;
  2099. if (!IsAddressOfOperand)
  2100. MightBeImplicitMember = true;
  2101. else if (!SS.isEmpty())
  2102. MightBeImplicitMember = false;
  2103. else if (R.isOverloadedResult())
  2104. MightBeImplicitMember = false;
  2105. else if (R.isUnresolvableResult())
  2106. MightBeImplicitMember = true;
  2107. else
  2108. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2109. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2110. isa<MSPropertyDecl>(R.getFoundDecl());
  2111. if (MightBeImplicitMember)
  2112. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2113. R, TemplateArgs, S);
  2114. }
  2115. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2116. // In C++1y, if this is a variable template id, then check it
  2117. // in BuildTemplateIdExpr().
  2118. // The single lookup result must be a variable template declaration.
  2119. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  2120. Id.TemplateId->Kind == TNK_Var_template) {
  2121. assert(R.getAsSingle<VarTemplateDecl>() &&
  2122. "There should only be one declaration found.");
  2123. }
  2124. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2125. }
  2126. return BuildDeclarationNameExpr(SS, R, ADL);
  2127. }
  2128. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2129. /// declaration name, generally during template instantiation.
  2130. /// There's a large number of things which don't need to be done along
  2131. /// this path.
  2132. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2133. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2134. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2135. DeclContext *DC = computeDeclContext(SS, false);
  2136. if (!DC)
  2137. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2138. NameInfo, /*TemplateArgs=*/nullptr);
  2139. if (RequireCompleteDeclContext(SS, DC))
  2140. return ExprError();
  2141. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2142. LookupQualifiedName(R, DC);
  2143. if (R.isAmbiguous())
  2144. return ExprError();
  2145. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2146. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2147. NameInfo, /*TemplateArgs=*/nullptr);
  2148. if (R.empty()) {
  2149. Diag(NameInfo.getLoc(), diag::err_no_member)
  2150. << NameInfo.getName() << DC << SS.getRange();
  2151. return ExprError();
  2152. }
  2153. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2154. // Diagnose a missing typename if this resolved unambiguously to a type in
  2155. // a dependent context. If we can recover with a type, downgrade this to
  2156. // a warning in Microsoft compatibility mode.
  2157. unsigned DiagID = diag::err_typename_missing;
  2158. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2159. DiagID = diag::ext_typename_missing;
  2160. SourceLocation Loc = SS.getBeginLoc();
  2161. auto D = Diag(Loc, DiagID);
  2162. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2163. << SourceRange(Loc, NameInfo.getEndLoc());
  2164. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2165. // context.
  2166. if (!RecoveryTSI)
  2167. return ExprError();
  2168. // Only issue the fixit if we're prepared to recover.
  2169. D << FixItHint::CreateInsertion(Loc, "typename ");
  2170. // Recover by pretending this was an elaborated type.
  2171. QualType Ty = Context.getTypeDeclType(TD);
  2172. TypeLocBuilder TLB;
  2173. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2174. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2175. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2176. QTL.setElaboratedKeywordLoc(SourceLocation());
  2177. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2178. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2179. return ExprEmpty();
  2180. }
  2181. // Defend against this resolving to an implicit member access. We usually
  2182. // won't get here if this might be a legitimate a class member (we end up in
  2183. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2184. // a pointer-to-member or in an unevaluated context in C++11.
  2185. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2186. return BuildPossibleImplicitMemberExpr(SS,
  2187. /*TemplateKWLoc=*/SourceLocation(),
  2188. R, /*TemplateArgs=*/nullptr, S);
  2189. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2190. }
  2191. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2192. /// detected that we're currently inside an ObjC method. Perform some
  2193. /// additional lookup.
  2194. ///
  2195. /// Ideally, most of this would be done by lookup, but there's
  2196. /// actually quite a lot of extra work involved.
  2197. ///
  2198. /// Returns a null sentinel to indicate trivial success.
  2199. ExprResult
  2200. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2201. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2202. SourceLocation Loc = Lookup.getNameLoc();
  2203. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2204. // Check for error condition which is already reported.
  2205. if (!CurMethod)
  2206. return ExprError();
  2207. // There are two cases to handle here. 1) scoped lookup could have failed,
  2208. // in which case we should look for an ivar. 2) scoped lookup could have
  2209. // found a decl, but that decl is outside the current instance method (i.e.
  2210. // a global variable). In these two cases, we do a lookup for an ivar with
  2211. // this name, if the lookup sucedes, we replace it our current decl.
  2212. // If we're in a class method, we don't normally want to look for
  2213. // ivars. But if we don't find anything else, and there's an
  2214. // ivar, that's an error.
  2215. bool IsClassMethod = CurMethod->isClassMethod();
  2216. bool LookForIvars;
  2217. if (Lookup.empty())
  2218. LookForIvars = true;
  2219. else if (IsClassMethod)
  2220. LookForIvars = false;
  2221. else
  2222. LookForIvars = (Lookup.isSingleResult() &&
  2223. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2224. ObjCInterfaceDecl *IFace = nullptr;
  2225. if (LookForIvars) {
  2226. IFace = CurMethod->getClassInterface();
  2227. ObjCInterfaceDecl *ClassDeclared;
  2228. ObjCIvarDecl *IV = nullptr;
  2229. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2230. // Diagnose using an ivar in a class method.
  2231. if (IsClassMethod)
  2232. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2233. << IV->getDeclName());
  2234. // If we're referencing an invalid decl, just return this as a silent
  2235. // error node. The error diagnostic was already emitted on the decl.
  2236. if (IV->isInvalidDecl())
  2237. return ExprError();
  2238. // Check if referencing a field with __attribute__((deprecated)).
  2239. if (DiagnoseUseOfDecl(IV, Loc))
  2240. return ExprError();
  2241. // Diagnose the use of an ivar outside of the declaring class.
  2242. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2243. !declaresSameEntity(ClassDeclared, IFace) &&
  2244. !getLangOpts().DebuggerSupport)
  2245. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2246. // FIXME: This should use a new expr for a direct reference, don't
  2247. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2248. IdentifierInfo &II = Context.Idents.get("self");
  2249. UnqualifiedId SelfName;
  2250. SelfName.setIdentifier(&II, SourceLocation());
  2251. SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
  2252. CXXScopeSpec SelfScopeSpec;
  2253. SourceLocation TemplateKWLoc;
  2254. ExprResult SelfExpr =
  2255. ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
  2256. /*HasTrailingLParen=*/false,
  2257. /*IsAddressOfOperand=*/false);
  2258. if (SelfExpr.isInvalid())
  2259. return ExprError();
  2260. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2261. if (SelfExpr.isInvalid())
  2262. return ExprError();
  2263. MarkAnyDeclReferenced(Loc, IV, true);
  2264. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2265. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2266. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2267. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2268. ObjCIvarRefExpr *Result = new (Context)
  2269. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2270. IV->getLocation(), SelfExpr.get(), true, true);
  2271. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2272. if (!isUnevaluatedContext() &&
  2273. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2274. getCurFunction()->recordUseOfWeak(Result);
  2275. }
  2276. if (getLangOpts().ObjCAutoRefCount)
  2277. if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
  2278. ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
  2279. return Result;
  2280. }
  2281. } else if (CurMethod->isInstanceMethod()) {
  2282. // We should warn if a local variable hides an ivar.
  2283. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2284. ObjCInterfaceDecl *ClassDeclared;
  2285. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2286. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2287. declaresSameEntity(IFace, ClassDeclared))
  2288. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2289. }
  2290. }
  2291. } else if (Lookup.isSingleResult() &&
  2292. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2293. // If accessing a stand-alone ivar in a class method, this is an error.
  2294. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2295. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2296. << IV->getDeclName());
  2297. }
  2298. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2299. // FIXME. Consolidate this with similar code in LookupName.
  2300. if (unsigned BuiltinID = II->getBuiltinID()) {
  2301. if (!(getLangOpts().CPlusPlus &&
  2302. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2303. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2304. S, Lookup.isForRedeclaration(),
  2305. Lookup.getNameLoc());
  2306. if (D) Lookup.addDecl(D);
  2307. }
  2308. }
  2309. }
  2310. // Sentinel value saying that we didn't do anything special.
  2311. return ExprResult((Expr *)nullptr);
  2312. }
  2313. /// Cast a base object to a member's actual type.
  2314. ///
  2315. /// Logically this happens in three phases:
  2316. ///
  2317. /// * First we cast from the base type to the naming class.
  2318. /// The naming class is the class into which we were looking
  2319. /// when we found the member; it's the qualifier type if a
  2320. /// qualifier was provided, and otherwise it's the base type.
  2321. ///
  2322. /// * Next we cast from the naming class to the declaring class.
  2323. /// If the member we found was brought into a class's scope by
  2324. /// a using declaration, this is that class; otherwise it's
  2325. /// the class declaring the member.
  2326. ///
  2327. /// * Finally we cast from the declaring class to the "true"
  2328. /// declaring class of the member. This conversion does not
  2329. /// obey access control.
  2330. ExprResult
  2331. Sema::PerformObjectMemberConversion(Expr *From,
  2332. NestedNameSpecifier *Qualifier,
  2333. NamedDecl *FoundDecl,
  2334. NamedDecl *Member) {
  2335. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2336. if (!RD)
  2337. return From;
  2338. QualType DestRecordType;
  2339. QualType DestType;
  2340. QualType FromRecordType;
  2341. QualType FromType = From->getType();
  2342. bool PointerConversions = false;
  2343. if (isa<FieldDecl>(Member)) {
  2344. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2345. auto FromPtrType = FromType->getAs<PointerType>();
  2346. DestRecordType = Context.getAddrSpaceQualType(
  2347. DestRecordType, FromPtrType
  2348. ? FromType->getPointeeType().getAddressSpace()
  2349. : FromType.getAddressSpace());
  2350. if (FromPtrType) {
  2351. DestType = Context.getPointerType(DestRecordType);
  2352. FromRecordType = FromPtrType->getPointeeType();
  2353. PointerConversions = true;
  2354. } else {
  2355. DestType = DestRecordType;
  2356. FromRecordType = FromType;
  2357. }
  2358. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2359. if (Method->isStatic())
  2360. return From;
  2361. DestType = Method->getThisType();
  2362. DestRecordType = DestType->getPointeeType();
  2363. if (FromType->getAs<PointerType>()) {
  2364. FromRecordType = FromType->getPointeeType();
  2365. PointerConversions = true;
  2366. } else {
  2367. FromRecordType = FromType;
  2368. DestType = DestRecordType;
  2369. }
  2370. } else {
  2371. // No conversion necessary.
  2372. return From;
  2373. }
  2374. if (DestType->isDependentType() || FromType->isDependentType())
  2375. return From;
  2376. // If the unqualified types are the same, no conversion is necessary.
  2377. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2378. return From;
  2379. SourceRange FromRange = From->getSourceRange();
  2380. SourceLocation FromLoc = FromRange.getBegin();
  2381. ExprValueKind VK = From->getValueKind();
  2382. // C++ [class.member.lookup]p8:
  2383. // [...] Ambiguities can often be resolved by qualifying a name with its
  2384. // class name.
  2385. //
  2386. // If the member was a qualified name and the qualified referred to a
  2387. // specific base subobject type, we'll cast to that intermediate type
  2388. // first and then to the object in which the member is declared. That allows
  2389. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2390. //
  2391. // class Base { public: int x; };
  2392. // class Derived1 : public Base { };
  2393. // class Derived2 : public Base { };
  2394. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2395. //
  2396. // void VeryDerived::f() {
  2397. // x = 17; // error: ambiguous base subobjects
  2398. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2399. // }
  2400. if (Qualifier && Qualifier->getAsType()) {
  2401. QualType QType = QualType(Qualifier->getAsType(), 0);
  2402. assert(QType->isRecordType() && "lookup done with non-record type");
  2403. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2404. // In C++98, the qualifier type doesn't actually have to be a base
  2405. // type of the object type, in which case we just ignore it.
  2406. // Otherwise build the appropriate casts.
  2407. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2408. CXXCastPath BasePath;
  2409. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2410. FromLoc, FromRange, &BasePath))
  2411. return ExprError();
  2412. if (PointerConversions)
  2413. QType = Context.getPointerType(QType);
  2414. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2415. VK, &BasePath).get();
  2416. FromType = QType;
  2417. FromRecordType = QRecordType;
  2418. // If the qualifier type was the same as the destination type,
  2419. // we're done.
  2420. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2421. return From;
  2422. }
  2423. }
  2424. bool IgnoreAccess = false;
  2425. // If we actually found the member through a using declaration, cast
  2426. // down to the using declaration's type.
  2427. //
  2428. // Pointer equality is fine here because only one declaration of a
  2429. // class ever has member declarations.
  2430. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2431. assert(isa<UsingShadowDecl>(FoundDecl));
  2432. QualType URecordType = Context.getTypeDeclType(
  2433. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2434. // We only need to do this if the naming-class to declaring-class
  2435. // conversion is non-trivial.
  2436. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2437. assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
  2438. CXXCastPath BasePath;
  2439. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2440. FromLoc, FromRange, &BasePath))
  2441. return ExprError();
  2442. QualType UType = URecordType;
  2443. if (PointerConversions)
  2444. UType = Context.getPointerType(UType);
  2445. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2446. VK, &BasePath).get();
  2447. FromType = UType;
  2448. FromRecordType = URecordType;
  2449. }
  2450. // We don't do access control for the conversion from the
  2451. // declaring class to the true declaring class.
  2452. IgnoreAccess = true;
  2453. }
  2454. CXXCastPath BasePath;
  2455. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2456. FromLoc, FromRange, &BasePath,
  2457. IgnoreAccess))
  2458. return ExprError();
  2459. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2460. VK, &BasePath);
  2461. }
  2462. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2463. const LookupResult &R,
  2464. bool HasTrailingLParen) {
  2465. // Only when used directly as the postfix-expression of a call.
  2466. if (!HasTrailingLParen)
  2467. return false;
  2468. // Never if a scope specifier was provided.
  2469. if (SS.isSet())
  2470. return false;
  2471. // Only in C++ or ObjC++.
  2472. if (!getLangOpts().CPlusPlus)
  2473. return false;
  2474. // Turn off ADL when we find certain kinds of declarations during
  2475. // normal lookup:
  2476. for (NamedDecl *D : R) {
  2477. // C++0x [basic.lookup.argdep]p3:
  2478. // -- a declaration of a class member
  2479. // Since using decls preserve this property, we check this on the
  2480. // original decl.
  2481. if (D->isCXXClassMember())
  2482. return false;
  2483. // C++0x [basic.lookup.argdep]p3:
  2484. // -- a block-scope function declaration that is not a
  2485. // using-declaration
  2486. // NOTE: we also trigger this for function templates (in fact, we
  2487. // don't check the decl type at all, since all other decl types
  2488. // turn off ADL anyway).
  2489. if (isa<UsingShadowDecl>(D))
  2490. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2491. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2492. return false;
  2493. // C++0x [basic.lookup.argdep]p3:
  2494. // -- a declaration that is neither a function or a function
  2495. // template
  2496. // And also for builtin functions.
  2497. if (isa<FunctionDecl>(D)) {
  2498. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2499. // But also builtin functions.
  2500. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2501. return false;
  2502. } else if (!isa<FunctionTemplateDecl>(D))
  2503. return false;
  2504. }
  2505. return true;
  2506. }
  2507. /// Diagnoses obvious problems with the use of the given declaration
  2508. /// as an expression. This is only actually called for lookups that
  2509. /// were not overloaded, and it doesn't promise that the declaration
  2510. /// will in fact be used.
  2511. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2512. if (D->isInvalidDecl())
  2513. return true;
  2514. if (isa<TypedefNameDecl>(D)) {
  2515. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2516. return true;
  2517. }
  2518. if (isa<ObjCInterfaceDecl>(D)) {
  2519. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2520. return true;
  2521. }
  2522. if (isa<NamespaceDecl>(D)) {
  2523. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2524. return true;
  2525. }
  2526. return false;
  2527. }
  2528. // Certain multiversion types should be treated as overloaded even when there is
  2529. // only one result.
  2530. static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
  2531. assert(R.isSingleResult() && "Expected only a single result");
  2532. const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  2533. return FD &&
  2534. (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
  2535. }
  2536. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2537. LookupResult &R, bool NeedsADL,
  2538. bool AcceptInvalidDecl) {
  2539. // If this is a single, fully-resolved result and we don't need ADL,
  2540. // just build an ordinary singleton decl ref.
  2541. if (!NeedsADL && R.isSingleResult() &&
  2542. !R.getAsSingle<FunctionTemplateDecl>() &&
  2543. !ShouldLookupResultBeMultiVersionOverload(R))
  2544. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2545. R.getRepresentativeDecl(), nullptr,
  2546. AcceptInvalidDecl);
  2547. // We only need to check the declaration if there's exactly one
  2548. // result, because in the overloaded case the results can only be
  2549. // functions and function templates.
  2550. if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
  2551. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2552. return ExprError();
  2553. // Otherwise, just build an unresolved lookup expression. Suppress
  2554. // any lookup-related diagnostics; we'll hash these out later, when
  2555. // we've picked a target.
  2556. R.suppressDiagnostics();
  2557. UnresolvedLookupExpr *ULE
  2558. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2559. SS.getWithLocInContext(Context),
  2560. R.getLookupNameInfo(),
  2561. NeedsADL, R.isOverloadedResult(),
  2562. R.begin(), R.end());
  2563. return ULE;
  2564. }
  2565. static void
  2566. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2567. ValueDecl *var, DeclContext *DC);
  2568. /// Complete semantic analysis for a reference to the given declaration.
  2569. ExprResult Sema::BuildDeclarationNameExpr(
  2570. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2571. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2572. bool AcceptInvalidDecl) {
  2573. assert(D && "Cannot refer to a NULL declaration");
  2574. assert(!isa<FunctionTemplateDecl>(D) &&
  2575. "Cannot refer unambiguously to a function template");
  2576. SourceLocation Loc = NameInfo.getLoc();
  2577. if (CheckDeclInExpr(*this, Loc, D))
  2578. return ExprError();
  2579. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2580. // Specifically diagnose references to class templates that are missing
  2581. // a template argument list.
  2582. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2583. return ExprError();
  2584. }
  2585. // Make sure that we're referring to a value.
  2586. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2587. if (!VD) {
  2588. Diag(Loc, diag::err_ref_non_value)
  2589. << D << SS.getRange();
  2590. Diag(D->getLocation(), diag::note_declared_at);
  2591. return ExprError();
  2592. }
  2593. // Check whether this declaration can be used. Note that we suppress
  2594. // this check when we're going to perform argument-dependent lookup
  2595. // on this function name, because this might not be the function
  2596. // that overload resolution actually selects.
  2597. if (DiagnoseUseOfDecl(VD, Loc))
  2598. return ExprError();
  2599. // Only create DeclRefExpr's for valid Decl's.
  2600. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2601. return ExprError();
  2602. // Handle members of anonymous structs and unions. If we got here,
  2603. // and the reference is to a class member indirect field, then this
  2604. // must be the subject of a pointer-to-member expression.
  2605. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2606. if (!indirectField->isCXXClassMember())
  2607. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2608. indirectField);
  2609. {
  2610. QualType type = VD->getType();
  2611. if (type.isNull())
  2612. return ExprError();
  2613. if (auto *FPT = type->getAs<FunctionProtoType>()) {
  2614. // C++ [except.spec]p17:
  2615. // An exception-specification is considered to be needed when:
  2616. // - in an expression, the function is the unique lookup result or
  2617. // the selected member of a set of overloaded functions.
  2618. ResolveExceptionSpec(Loc, FPT);
  2619. type = VD->getType();
  2620. }
  2621. ExprValueKind valueKind = VK_RValue;
  2622. switch (D->getKind()) {
  2623. // Ignore all the non-ValueDecl kinds.
  2624. #define ABSTRACT_DECL(kind)
  2625. #define VALUE(type, base)
  2626. #define DECL(type, base) \
  2627. case Decl::type:
  2628. #include "clang/AST/DeclNodes.inc"
  2629. llvm_unreachable("invalid value decl kind");
  2630. // These shouldn't make it here.
  2631. case Decl::ObjCAtDefsField:
  2632. llvm_unreachable("forming non-member reference to ivar?");
  2633. // Enum constants are always r-values and never references.
  2634. // Unresolved using declarations are dependent.
  2635. case Decl::EnumConstant:
  2636. case Decl::UnresolvedUsingValue:
  2637. case Decl::OMPDeclareReduction:
  2638. case Decl::OMPDeclareMapper:
  2639. valueKind = VK_RValue;
  2640. break;
  2641. // Fields and indirect fields that got here must be for
  2642. // pointer-to-member expressions; we just call them l-values for
  2643. // internal consistency, because this subexpression doesn't really
  2644. // exist in the high-level semantics.
  2645. case Decl::Field:
  2646. case Decl::IndirectField:
  2647. case Decl::ObjCIvar:
  2648. assert(getLangOpts().CPlusPlus &&
  2649. "building reference to field in C?");
  2650. // These can't have reference type in well-formed programs, but
  2651. // for internal consistency we do this anyway.
  2652. type = type.getNonReferenceType();
  2653. valueKind = VK_LValue;
  2654. break;
  2655. // Non-type template parameters are either l-values or r-values
  2656. // depending on the type.
  2657. case Decl::NonTypeTemplateParm: {
  2658. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2659. type = reftype->getPointeeType();
  2660. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2661. break;
  2662. }
  2663. // For non-references, we need to strip qualifiers just in case
  2664. // the template parameter was declared as 'const int' or whatever.
  2665. valueKind = VK_RValue;
  2666. type = type.getUnqualifiedType();
  2667. break;
  2668. }
  2669. case Decl::Var:
  2670. case Decl::VarTemplateSpecialization:
  2671. case Decl::VarTemplatePartialSpecialization:
  2672. case Decl::Decomposition:
  2673. case Decl::OMPCapturedExpr:
  2674. // In C, "extern void blah;" is valid and is an r-value.
  2675. if (!getLangOpts().CPlusPlus &&
  2676. !type.hasQualifiers() &&
  2677. type->isVoidType()) {
  2678. valueKind = VK_RValue;
  2679. break;
  2680. }
  2681. LLVM_FALLTHROUGH;
  2682. case Decl::ImplicitParam:
  2683. case Decl::ParmVar: {
  2684. // These are always l-values.
  2685. valueKind = VK_LValue;
  2686. type = type.getNonReferenceType();
  2687. // FIXME: Does the addition of const really only apply in
  2688. // potentially-evaluated contexts? Since the variable isn't actually
  2689. // captured in an unevaluated context, it seems that the answer is no.
  2690. if (!isUnevaluatedContext()) {
  2691. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2692. if (!CapturedType.isNull())
  2693. type = CapturedType;
  2694. }
  2695. break;
  2696. }
  2697. case Decl::Binding: {
  2698. // These are always lvalues.
  2699. valueKind = VK_LValue;
  2700. type = type.getNonReferenceType();
  2701. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2702. // decides how that's supposed to work.
  2703. auto *BD = cast<BindingDecl>(VD);
  2704. if (BD->getDeclContext() != CurContext) {
  2705. auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
  2706. if (DD && DD->hasLocalStorage())
  2707. diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
  2708. }
  2709. break;
  2710. }
  2711. case Decl::Function: {
  2712. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2713. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2714. type = Context.BuiltinFnTy;
  2715. valueKind = VK_RValue;
  2716. break;
  2717. }
  2718. }
  2719. const FunctionType *fty = type->castAs<FunctionType>();
  2720. // If we're referring to a function with an __unknown_anytype
  2721. // result type, make the entire expression __unknown_anytype.
  2722. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2723. type = Context.UnknownAnyTy;
  2724. valueKind = VK_RValue;
  2725. break;
  2726. }
  2727. // Functions are l-values in C++.
  2728. if (getLangOpts().CPlusPlus) {
  2729. valueKind = VK_LValue;
  2730. break;
  2731. }
  2732. // C99 DR 316 says that, if a function type comes from a
  2733. // function definition (without a prototype), that type is only
  2734. // used for checking compatibility. Therefore, when referencing
  2735. // the function, we pretend that we don't have the full function
  2736. // type.
  2737. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2738. isa<FunctionProtoType>(fty))
  2739. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2740. fty->getExtInfo());
  2741. // Functions are r-values in C.
  2742. valueKind = VK_RValue;
  2743. break;
  2744. }
  2745. case Decl::CXXDeductionGuide:
  2746. llvm_unreachable("building reference to deduction guide");
  2747. case Decl::MSProperty:
  2748. valueKind = VK_LValue;
  2749. break;
  2750. case Decl::CXXMethod:
  2751. // If we're referring to a method with an __unknown_anytype
  2752. // result type, make the entire expression __unknown_anytype.
  2753. // This should only be possible with a type written directly.
  2754. if (const FunctionProtoType *proto
  2755. = dyn_cast<FunctionProtoType>(VD->getType()))
  2756. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2757. type = Context.UnknownAnyTy;
  2758. valueKind = VK_RValue;
  2759. break;
  2760. }
  2761. // C++ methods are l-values if static, r-values if non-static.
  2762. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2763. valueKind = VK_LValue;
  2764. break;
  2765. }
  2766. LLVM_FALLTHROUGH;
  2767. case Decl::CXXConversion:
  2768. case Decl::CXXDestructor:
  2769. case Decl::CXXConstructor:
  2770. valueKind = VK_RValue;
  2771. break;
  2772. }
  2773. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2774. /*FIXME: TemplateKWLoc*/ SourceLocation(),
  2775. TemplateArgs);
  2776. }
  2777. }
  2778. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2779. SmallString<32> &Target) {
  2780. Target.resize(CharByteWidth * (Source.size() + 1));
  2781. char *ResultPtr = &Target[0];
  2782. const llvm::UTF8 *ErrorPtr;
  2783. bool success =
  2784. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2785. (void)success;
  2786. assert(success);
  2787. Target.resize(ResultPtr - &Target[0]);
  2788. }
  2789. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2790. PredefinedExpr::IdentKind IK) {
  2791. // Pick the current block, lambda, captured statement or function.
  2792. Decl *currentDecl = nullptr;
  2793. if (const BlockScopeInfo *BSI = getCurBlock())
  2794. currentDecl = BSI->TheDecl;
  2795. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2796. currentDecl = LSI->CallOperator;
  2797. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2798. currentDecl = CSI->TheCapturedDecl;
  2799. else
  2800. currentDecl = getCurFunctionOrMethodDecl();
  2801. if (!currentDecl) {
  2802. Diag(Loc, diag::ext_predef_outside_function);
  2803. currentDecl = Context.getTranslationUnitDecl();
  2804. }
  2805. QualType ResTy;
  2806. StringLiteral *SL = nullptr;
  2807. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2808. ResTy = Context.DependentTy;
  2809. else {
  2810. // Pre-defined identifiers are of type char[x], where x is the length of
  2811. // the string.
  2812. auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
  2813. unsigned Length = Str.length();
  2814. llvm::APInt LengthI(32, Length + 1);
  2815. if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
  2816. ResTy =
  2817. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  2818. SmallString<32> RawChars;
  2819. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2820. Str, RawChars);
  2821. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2822. /*IndexTypeQuals*/ 0);
  2823. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2824. /*Pascal*/ false, ResTy, Loc);
  2825. } else {
  2826. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  2827. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2828. /*IndexTypeQuals*/ 0);
  2829. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2830. /*Pascal*/ false, ResTy, Loc);
  2831. }
  2832. }
  2833. return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
  2834. }
  2835. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2836. PredefinedExpr::IdentKind IK;
  2837. switch (Kind) {
  2838. default: llvm_unreachable("Unknown simple primary expr!");
  2839. case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2840. case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
  2841. case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
  2842. case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
  2843. case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
  2844. case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
  2845. case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
  2846. }
  2847. return BuildPredefinedExpr(Loc, IK);
  2848. }
  2849. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2850. SmallString<16> CharBuffer;
  2851. bool Invalid = false;
  2852. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2853. if (Invalid)
  2854. return ExprError();
  2855. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2856. PP, Tok.getKind());
  2857. if (Literal.hadError())
  2858. return ExprError();
  2859. QualType Ty;
  2860. if (Literal.isWide())
  2861. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2862. else if (Literal.isUTF8() && getLangOpts().Char8)
  2863. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  2864. else if (Literal.isUTF16())
  2865. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2866. else if (Literal.isUTF32())
  2867. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2868. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2869. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2870. else
  2871. Ty = Context.CharTy; // 'x' -> char in C++
  2872. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2873. if (Literal.isWide())
  2874. Kind = CharacterLiteral::Wide;
  2875. else if (Literal.isUTF16())
  2876. Kind = CharacterLiteral::UTF16;
  2877. else if (Literal.isUTF32())
  2878. Kind = CharacterLiteral::UTF32;
  2879. else if (Literal.isUTF8())
  2880. Kind = CharacterLiteral::UTF8;
  2881. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2882. Tok.getLocation());
  2883. if (Literal.getUDSuffix().empty())
  2884. return Lit;
  2885. // We're building a user-defined literal.
  2886. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2887. SourceLocation UDSuffixLoc =
  2888. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2889. // Make sure we're allowed user-defined literals here.
  2890. if (!UDLScope)
  2891. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2892. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2893. // operator "" X (ch)
  2894. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2895. Lit, Tok.getLocation());
  2896. }
  2897. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2898. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2899. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2900. Context.IntTy, Loc);
  2901. }
  2902. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2903. QualType Ty, SourceLocation Loc) {
  2904. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2905. using llvm::APFloat;
  2906. APFloat Val(Format);
  2907. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2908. // Overflow is always an error, but underflow is only an error if
  2909. // we underflowed to zero (APFloat reports denormals as underflow).
  2910. if ((result & APFloat::opOverflow) ||
  2911. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2912. unsigned diagnostic;
  2913. SmallString<20> buffer;
  2914. if (result & APFloat::opOverflow) {
  2915. diagnostic = diag::warn_float_overflow;
  2916. APFloat::getLargest(Format).toString(buffer);
  2917. } else {
  2918. diagnostic = diag::warn_float_underflow;
  2919. APFloat::getSmallest(Format).toString(buffer);
  2920. }
  2921. S.Diag(Loc, diagnostic)
  2922. << Ty
  2923. << StringRef(buffer.data(), buffer.size());
  2924. }
  2925. bool isExact = (result == APFloat::opOK);
  2926. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2927. }
  2928. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2929. assert(E && "Invalid expression");
  2930. if (E->isValueDependent())
  2931. return false;
  2932. QualType QT = E->getType();
  2933. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2934. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2935. return true;
  2936. }
  2937. llvm::APSInt ValueAPS;
  2938. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2939. if (R.isInvalid())
  2940. return true;
  2941. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2942. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2943. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2944. << ValueAPS.toString(10) << ValueIsPositive;
  2945. return true;
  2946. }
  2947. return false;
  2948. }
  2949. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2950. // Fast path for a single digit (which is quite common). A single digit
  2951. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2952. if (Tok.getLength() == 1) {
  2953. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2954. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2955. }
  2956. SmallString<128> SpellingBuffer;
  2957. // NumericLiteralParser wants to overread by one character. Add padding to
  2958. // the buffer in case the token is copied to the buffer. If getSpelling()
  2959. // returns a StringRef to the memory buffer, it should have a null char at
  2960. // the EOF, so it is also safe.
  2961. SpellingBuffer.resize(Tok.getLength() + 1);
  2962. // Get the spelling of the token, which eliminates trigraphs, etc.
  2963. bool Invalid = false;
  2964. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2965. if (Invalid)
  2966. return ExprError();
  2967. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2968. if (Literal.hadError)
  2969. return ExprError();
  2970. if (Literal.hasUDSuffix()) {
  2971. // We're building a user-defined literal.
  2972. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2973. SourceLocation UDSuffixLoc =
  2974. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2975. // Make sure we're allowed user-defined literals here.
  2976. if (!UDLScope)
  2977. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2978. QualType CookedTy;
  2979. if (Literal.isFloatingLiteral()) {
  2980. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2981. // long double, the literal is treated as a call of the form
  2982. // operator "" X (f L)
  2983. CookedTy = Context.LongDoubleTy;
  2984. } else {
  2985. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2986. // unsigned long long, the literal is treated as a call of the form
  2987. // operator "" X (n ULL)
  2988. CookedTy = Context.UnsignedLongLongTy;
  2989. }
  2990. DeclarationName OpName =
  2991. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2992. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2993. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2994. SourceLocation TokLoc = Tok.getLocation();
  2995. // Perform literal operator lookup to determine if we're building a raw
  2996. // literal or a cooked one.
  2997. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2998. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2999. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  3000. /*AllowStringTemplate*/ false,
  3001. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  3002. case LOLR_ErrorNoDiagnostic:
  3003. // Lookup failure for imaginary constants isn't fatal, there's still the
  3004. // GNU extension producing _Complex types.
  3005. break;
  3006. case LOLR_Error:
  3007. return ExprError();
  3008. case LOLR_Cooked: {
  3009. Expr *Lit;
  3010. if (Literal.isFloatingLiteral()) {
  3011. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  3012. } else {
  3013. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  3014. if (Literal.GetIntegerValue(ResultVal))
  3015. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3016. << /* Unsigned */ 1;
  3017. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  3018. Tok.getLocation());
  3019. }
  3020. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3021. }
  3022. case LOLR_Raw: {
  3023. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  3024. // literal is treated as a call of the form
  3025. // operator "" X ("n")
  3026. unsigned Length = Literal.getUDSuffixOffset();
  3027. QualType StrTy = Context.getConstantArrayType(
  3028. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  3029. llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
  3030. Expr *Lit = StringLiteral::Create(
  3031. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  3032. /*Pascal*/false, StrTy, &TokLoc, 1);
  3033. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3034. }
  3035. case LOLR_Template: {
  3036. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  3037. // template), L is treated as a call fo the form
  3038. // operator "" X <'c1', 'c2', ... 'ck'>()
  3039. // where n is the source character sequence c1 c2 ... ck.
  3040. TemplateArgumentListInfo ExplicitArgs;
  3041. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  3042. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  3043. llvm::APSInt Value(CharBits, CharIsUnsigned);
  3044. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  3045. Value = TokSpelling[I];
  3046. TemplateArgument Arg(Context, Value, Context.CharTy);
  3047. TemplateArgumentLocInfo ArgInfo;
  3048. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  3049. }
  3050. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  3051. &ExplicitArgs);
  3052. }
  3053. case LOLR_StringTemplate:
  3054. llvm_unreachable("unexpected literal operator lookup result");
  3055. }
  3056. }
  3057. Expr *Res;
  3058. if (Literal.isFixedPointLiteral()) {
  3059. QualType Ty;
  3060. if (Literal.isAccum) {
  3061. if (Literal.isHalf) {
  3062. Ty = Context.ShortAccumTy;
  3063. } else if (Literal.isLong) {
  3064. Ty = Context.LongAccumTy;
  3065. } else {
  3066. Ty = Context.AccumTy;
  3067. }
  3068. } else if (Literal.isFract) {
  3069. if (Literal.isHalf) {
  3070. Ty = Context.ShortFractTy;
  3071. } else if (Literal.isLong) {
  3072. Ty = Context.LongFractTy;
  3073. } else {
  3074. Ty = Context.FractTy;
  3075. }
  3076. }
  3077. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  3078. bool isSigned = !Literal.isUnsigned;
  3079. unsigned scale = Context.getFixedPointScale(Ty);
  3080. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  3081. llvm::APInt Val(bit_width, 0, isSigned);
  3082. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  3083. bool ValIsZero = Val.isNullValue() && !Overflowed;
  3084. auto MaxVal = Context.getFixedPointMax(Ty).getValue();
  3085. if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
  3086. // Clause 6.4.4 - The value of a constant shall be in the range of
  3087. // representable values for its type, with exception for constants of a
  3088. // fract type with a value of exactly 1; such a constant shall denote
  3089. // the maximal value for the type.
  3090. --Val;
  3091. else if (Val.ugt(MaxVal) || Overflowed)
  3092. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  3093. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  3094. Tok.getLocation(), scale);
  3095. } else if (Literal.isFloatingLiteral()) {
  3096. QualType Ty;
  3097. if (Literal.isHalf){
  3098. if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
  3099. Ty = Context.HalfTy;
  3100. else {
  3101. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  3102. return ExprError();
  3103. }
  3104. } else if (Literal.isFloat)
  3105. Ty = Context.FloatTy;
  3106. else if (Literal.isLong)
  3107. Ty = Context.LongDoubleTy;
  3108. else if (Literal.isFloat16)
  3109. Ty = Context.Float16Ty;
  3110. else if (Literal.isFloat128)
  3111. Ty = Context.Float128Ty;
  3112. else
  3113. Ty = Context.DoubleTy;
  3114. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  3115. if (Ty == Context.DoubleTy) {
  3116. if (getLangOpts().SinglePrecisionConstants) {
  3117. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  3118. if (BTy->getKind() != BuiltinType::Float) {
  3119. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3120. }
  3121. } else if (getLangOpts().OpenCL &&
  3122. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  3123. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  3124. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  3125. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3126. }
  3127. }
  3128. } else if (!Literal.isIntegerLiteral()) {
  3129. return ExprError();
  3130. } else {
  3131. QualType Ty;
  3132. // 'long long' is a C99 or C++11 feature.
  3133. if (!getLangOpts().C99 && Literal.isLongLong) {
  3134. if (getLangOpts().CPlusPlus)
  3135. Diag(Tok.getLocation(),
  3136. getLangOpts().CPlusPlus11 ?
  3137. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3138. else
  3139. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3140. }
  3141. // Get the value in the widest-possible width.
  3142. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3143. llvm::APInt ResultVal(MaxWidth, 0);
  3144. if (Literal.GetIntegerValue(ResultVal)) {
  3145. // If this value didn't fit into uintmax_t, error and force to ull.
  3146. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3147. << /* Unsigned */ 1;
  3148. Ty = Context.UnsignedLongLongTy;
  3149. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3150. "long long is not intmax_t?");
  3151. } else {
  3152. // If this value fits into a ULL, try to figure out what else it fits into
  3153. // according to the rules of C99 6.4.4.1p5.
  3154. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3155. // be an unsigned int.
  3156. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3157. // Check from smallest to largest, picking the smallest type we can.
  3158. unsigned Width = 0;
  3159. // Microsoft specific integer suffixes are explicitly sized.
  3160. if (Literal.MicrosoftInteger) {
  3161. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3162. Width = 8;
  3163. Ty = Context.CharTy;
  3164. } else {
  3165. Width = Literal.MicrosoftInteger;
  3166. Ty = Context.getIntTypeForBitwidth(Width,
  3167. /*Signed=*/!Literal.isUnsigned);
  3168. }
  3169. }
  3170. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3171. // Are int/unsigned possibilities?
  3172. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3173. // Does it fit in a unsigned int?
  3174. if (ResultVal.isIntN(IntSize)) {
  3175. // Does it fit in a signed int?
  3176. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3177. Ty = Context.IntTy;
  3178. else if (AllowUnsigned)
  3179. Ty = Context.UnsignedIntTy;
  3180. Width = IntSize;
  3181. }
  3182. }
  3183. // Are long/unsigned long possibilities?
  3184. if (Ty.isNull() && !Literal.isLongLong) {
  3185. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3186. // Does it fit in a unsigned long?
  3187. if (ResultVal.isIntN(LongSize)) {
  3188. // Does it fit in a signed long?
  3189. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3190. Ty = Context.LongTy;
  3191. else if (AllowUnsigned)
  3192. Ty = Context.UnsignedLongTy;
  3193. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3194. // is compatible.
  3195. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3196. const unsigned LongLongSize =
  3197. Context.getTargetInfo().getLongLongWidth();
  3198. Diag(Tok.getLocation(),
  3199. getLangOpts().CPlusPlus
  3200. ? Literal.isLong
  3201. ? diag::warn_old_implicitly_unsigned_long_cxx
  3202. : /*C++98 UB*/ diag::
  3203. ext_old_implicitly_unsigned_long_cxx
  3204. : diag::warn_old_implicitly_unsigned_long)
  3205. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3206. : /*will be ill-formed*/ 1);
  3207. Ty = Context.UnsignedLongTy;
  3208. }
  3209. Width = LongSize;
  3210. }
  3211. }
  3212. // Check long long if needed.
  3213. if (Ty.isNull()) {
  3214. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3215. // Does it fit in a unsigned long long?
  3216. if (ResultVal.isIntN(LongLongSize)) {
  3217. // Does it fit in a signed long long?
  3218. // To be compatible with MSVC, hex integer literals ending with the
  3219. // LL or i64 suffix are always signed in Microsoft mode.
  3220. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3221. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3222. Ty = Context.LongLongTy;
  3223. else if (AllowUnsigned)
  3224. Ty = Context.UnsignedLongLongTy;
  3225. Width = LongLongSize;
  3226. }
  3227. }
  3228. // If we still couldn't decide a type, we probably have something that
  3229. // does not fit in a signed long long, but has no U suffix.
  3230. if (Ty.isNull()) {
  3231. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3232. Ty = Context.UnsignedLongLongTy;
  3233. Width = Context.getTargetInfo().getLongLongWidth();
  3234. }
  3235. if (ResultVal.getBitWidth() != Width)
  3236. ResultVal = ResultVal.trunc(Width);
  3237. }
  3238. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3239. }
  3240. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3241. if (Literal.isImaginary) {
  3242. Res = new (Context) ImaginaryLiteral(Res,
  3243. Context.getComplexType(Res->getType()));
  3244. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3245. }
  3246. return Res;
  3247. }
  3248. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3249. assert(E && "ActOnParenExpr() missing expr");
  3250. return new (Context) ParenExpr(L, R, E);
  3251. }
  3252. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3253. SourceLocation Loc,
  3254. SourceRange ArgRange) {
  3255. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3256. // scalar or vector data type argument..."
  3257. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3258. // type (C99 6.2.5p18) or void.
  3259. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3260. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3261. << T << ArgRange;
  3262. return true;
  3263. }
  3264. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3265. "Scalar types should always be complete");
  3266. return false;
  3267. }
  3268. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3269. SourceLocation Loc,
  3270. SourceRange ArgRange,
  3271. UnaryExprOrTypeTrait TraitKind) {
  3272. // Invalid types must be hard errors for SFINAE in C++.
  3273. if (S.LangOpts.CPlusPlus)
  3274. return true;
  3275. // C99 6.5.3.4p1:
  3276. if (T->isFunctionType() &&
  3277. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
  3278. TraitKind == UETT_PreferredAlignOf)) {
  3279. // sizeof(function)/alignof(function) is allowed as an extension.
  3280. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3281. << TraitKind << ArgRange;
  3282. return false;
  3283. }
  3284. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3285. // this is an error (OpenCL v1.1 s6.3.k)
  3286. if (T->isVoidType()) {
  3287. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3288. : diag::ext_sizeof_alignof_void_type;
  3289. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3290. return false;
  3291. }
  3292. return true;
  3293. }
  3294. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3295. SourceLocation Loc,
  3296. SourceRange ArgRange,
  3297. UnaryExprOrTypeTrait TraitKind) {
  3298. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3299. // runtime doesn't allow it.
  3300. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3301. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3302. << T << (TraitKind == UETT_SizeOf)
  3303. << ArgRange;
  3304. return true;
  3305. }
  3306. return false;
  3307. }
  3308. /// Check whether E is a pointer from a decayed array type (the decayed
  3309. /// pointer type is equal to T) and emit a warning if it is.
  3310. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3311. Expr *E) {
  3312. // Don't warn if the operation changed the type.
  3313. if (T != E->getType())
  3314. return;
  3315. // Now look for array decays.
  3316. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3317. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3318. return;
  3319. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3320. << ICE->getType()
  3321. << ICE->getSubExpr()->getType();
  3322. }
  3323. /// Check the constraints on expression operands to unary type expression
  3324. /// and type traits.
  3325. ///
  3326. /// Completes any types necessary and validates the constraints on the operand
  3327. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3328. /// the expression as it completes the type for that expression through template
  3329. /// instantiation, etc.
  3330. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3331. UnaryExprOrTypeTrait ExprKind) {
  3332. QualType ExprTy = E->getType();
  3333. assert(!ExprTy->isReferenceType());
  3334. if (ExprKind == UETT_VecStep)
  3335. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3336. E->getSourceRange());
  3337. // Whitelist some types as extensions
  3338. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3339. E->getSourceRange(), ExprKind))
  3340. return false;
  3341. // 'alignof' applied to an expression only requires the base element type of
  3342. // the expression to be complete. 'sizeof' requires the expression's type to
  3343. // be complete (and will attempt to complete it if it's an array of unknown
  3344. // bound).
  3345. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3346. if (RequireCompleteType(E->getExprLoc(),
  3347. Context.getBaseElementType(E->getType()),
  3348. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3349. E->getSourceRange()))
  3350. return true;
  3351. } else {
  3352. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3353. ExprKind, E->getSourceRange()))
  3354. return true;
  3355. }
  3356. // Completing the expression's type may have changed it.
  3357. ExprTy = E->getType();
  3358. assert(!ExprTy->isReferenceType());
  3359. if (ExprTy->isFunctionType()) {
  3360. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3361. << ExprKind << E->getSourceRange();
  3362. return true;
  3363. }
  3364. // The operand for sizeof and alignof is in an unevaluated expression context,
  3365. // so side effects could result in unintended consequences.
  3366. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
  3367. ExprKind == UETT_PreferredAlignOf) &&
  3368. !inTemplateInstantiation() && E->HasSideEffects(Context, false))
  3369. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3370. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3371. E->getSourceRange(), ExprKind))
  3372. return true;
  3373. if (ExprKind == UETT_SizeOf) {
  3374. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3375. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3376. QualType OType = PVD->getOriginalType();
  3377. QualType Type = PVD->getType();
  3378. if (Type->isPointerType() && OType->isArrayType()) {
  3379. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3380. << Type << OType;
  3381. Diag(PVD->getLocation(), diag::note_declared_at);
  3382. }
  3383. }
  3384. }
  3385. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3386. // decays into a pointer and returns an unintended result. This is most
  3387. // likely a typo for "sizeof(array) op x".
  3388. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3389. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3390. BO->getLHS());
  3391. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3392. BO->getRHS());
  3393. }
  3394. }
  3395. return false;
  3396. }
  3397. /// Check the constraints on operands to unary expression and type
  3398. /// traits.
  3399. ///
  3400. /// This will complete any types necessary, and validate the various constraints
  3401. /// on those operands.
  3402. ///
  3403. /// The UsualUnaryConversions() function is *not* called by this routine.
  3404. /// C99 6.3.2.1p[2-4] all state:
  3405. /// Except when it is the operand of the sizeof operator ...
  3406. ///
  3407. /// C++ [expr.sizeof]p4
  3408. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3409. /// standard conversions are not applied to the operand of sizeof.
  3410. ///
  3411. /// This policy is followed for all of the unary trait expressions.
  3412. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3413. SourceLocation OpLoc,
  3414. SourceRange ExprRange,
  3415. UnaryExprOrTypeTrait ExprKind) {
  3416. if (ExprType->isDependentType())
  3417. return false;
  3418. // C++ [expr.sizeof]p2:
  3419. // When applied to a reference or a reference type, the result
  3420. // is the size of the referenced type.
  3421. // C++11 [expr.alignof]p3:
  3422. // When alignof is applied to a reference type, the result
  3423. // shall be the alignment of the referenced type.
  3424. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3425. ExprType = Ref->getPointeeType();
  3426. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3427. // When alignof or _Alignof is applied to an array type, the result
  3428. // is the alignment of the element type.
  3429. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
  3430. ExprKind == UETT_OpenMPRequiredSimdAlign)
  3431. ExprType = Context.getBaseElementType(ExprType);
  3432. if (ExprKind == UETT_VecStep)
  3433. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3434. // Whitelist some types as extensions
  3435. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3436. ExprKind))
  3437. return false;
  3438. if (RequireCompleteType(OpLoc, ExprType,
  3439. diag::err_sizeof_alignof_incomplete_type,
  3440. ExprKind, ExprRange))
  3441. return true;
  3442. if (ExprType->isFunctionType()) {
  3443. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3444. << ExprKind << ExprRange;
  3445. return true;
  3446. }
  3447. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3448. ExprKind))
  3449. return true;
  3450. return false;
  3451. }
  3452. static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
  3453. E = E->IgnoreParens();
  3454. // Cannot know anything else if the expression is dependent.
  3455. if (E->isTypeDependent())
  3456. return false;
  3457. if (E->getObjectKind() == OK_BitField) {
  3458. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3459. << 1 << E->getSourceRange();
  3460. return true;
  3461. }
  3462. ValueDecl *D = nullptr;
  3463. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3464. D = DRE->getDecl();
  3465. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3466. D = ME->getMemberDecl();
  3467. }
  3468. // If it's a field, require the containing struct to have a
  3469. // complete definition so that we can compute the layout.
  3470. //
  3471. // This can happen in C++11 onwards, either by naming the member
  3472. // in a way that is not transformed into a member access expression
  3473. // (in an unevaluated operand, for instance), or by naming the member
  3474. // in a trailing-return-type.
  3475. //
  3476. // For the record, since __alignof__ on expressions is a GCC
  3477. // extension, GCC seems to permit this but always gives the
  3478. // nonsensical answer 0.
  3479. //
  3480. // We don't really need the layout here --- we could instead just
  3481. // directly check for all the appropriate alignment-lowing
  3482. // attributes --- but that would require duplicating a lot of
  3483. // logic that just isn't worth duplicating for such a marginal
  3484. // use-case.
  3485. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3486. // Fast path this check, since we at least know the record has a
  3487. // definition if we can find a member of it.
  3488. if (!FD->getParent()->isCompleteDefinition()) {
  3489. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3490. << E->getSourceRange();
  3491. return true;
  3492. }
  3493. // Otherwise, if it's a field, and the field doesn't have
  3494. // reference type, then it must have a complete type (or be a
  3495. // flexible array member, which we explicitly want to
  3496. // white-list anyway), which makes the following checks trivial.
  3497. if (!FD->getType()->isReferenceType())
  3498. return false;
  3499. }
  3500. return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
  3501. }
  3502. bool Sema::CheckVecStepExpr(Expr *E) {
  3503. E = E->IgnoreParens();
  3504. // Cannot know anything else if the expression is dependent.
  3505. if (E->isTypeDependent())
  3506. return false;
  3507. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3508. }
  3509. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3510. CapturingScopeInfo *CSI) {
  3511. assert(T->isVariablyModifiedType());
  3512. assert(CSI != nullptr);
  3513. // We're going to walk down into the type and look for VLA expressions.
  3514. do {
  3515. const Type *Ty = T.getTypePtr();
  3516. switch (Ty->getTypeClass()) {
  3517. #define TYPE(Class, Base)
  3518. #define ABSTRACT_TYPE(Class, Base)
  3519. #define NON_CANONICAL_TYPE(Class, Base)
  3520. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3521. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3522. #include "clang/AST/TypeNodes.def"
  3523. T = QualType();
  3524. break;
  3525. // These types are never variably-modified.
  3526. case Type::Builtin:
  3527. case Type::Complex:
  3528. case Type::Vector:
  3529. case Type::ExtVector:
  3530. case Type::Record:
  3531. case Type::Enum:
  3532. case Type::Elaborated:
  3533. case Type::TemplateSpecialization:
  3534. case Type::ObjCObject:
  3535. case Type::ObjCInterface:
  3536. case Type::ObjCObjectPointer:
  3537. case Type::ObjCTypeParam:
  3538. case Type::Pipe:
  3539. llvm_unreachable("type class is never variably-modified!");
  3540. case Type::Adjusted:
  3541. T = cast<AdjustedType>(Ty)->getOriginalType();
  3542. break;
  3543. case Type::Decayed:
  3544. T = cast<DecayedType>(Ty)->getPointeeType();
  3545. break;
  3546. case Type::Pointer:
  3547. T = cast<PointerType>(Ty)->getPointeeType();
  3548. break;
  3549. case Type::BlockPointer:
  3550. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3551. break;
  3552. case Type::LValueReference:
  3553. case Type::RValueReference:
  3554. T = cast<ReferenceType>(Ty)->getPointeeType();
  3555. break;
  3556. case Type::MemberPointer:
  3557. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3558. break;
  3559. case Type::ConstantArray:
  3560. case Type::IncompleteArray:
  3561. // Losing element qualification here is fine.
  3562. T = cast<ArrayType>(Ty)->getElementType();
  3563. break;
  3564. case Type::VariableArray: {
  3565. // Losing element qualification here is fine.
  3566. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3567. // Unknown size indication requires no size computation.
  3568. // Otherwise, evaluate and record it.
  3569. auto Size = VAT->getSizeExpr();
  3570. if (Size && !CSI->isVLATypeCaptured(VAT) &&
  3571. (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
  3572. CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
  3573. T = VAT->getElementType();
  3574. break;
  3575. }
  3576. case Type::FunctionProto:
  3577. case Type::FunctionNoProto:
  3578. T = cast<FunctionType>(Ty)->getReturnType();
  3579. break;
  3580. case Type::Paren:
  3581. case Type::TypeOf:
  3582. case Type::UnaryTransform:
  3583. case Type::Attributed:
  3584. case Type::SubstTemplateTypeParm:
  3585. case Type::PackExpansion:
  3586. case Type::MacroQualified:
  3587. // Keep walking after single level desugaring.
  3588. T = T.getSingleStepDesugaredType(Context);
  3589. break;
  3590. case Type::Typedef:
  3591. T = cast<TypedefType>(Ty)->desugar();
  3592. break;
  3593. case Type::Decltype:
  3594. T = cast<DecltypeType>(Ty)->desugar();
  3595. break;
  3596. case Type::Auto:
  3597. case Type::DeducedTemplateSpecialization:
  3598. T = cast<DeducedType>(Ty)->getDeducedType();
  3599. break;
  3600. case Type::TypeOfExpr:
  3601. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3602. break;
  3603. case Type::Atomic:
  3604. T = cast<AtomicType>(Ty)->getValueType();
  3605. break;
  3606. }
  3607. } while (!T.isNull() && T->isVariablyModifiedType());
  3608. }
  3609. /// Build a sizeof or alignof expression given a type operand.
  3610. ExprResult
  3611. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3612. SourceLocation OpLoc,
  3613. UnaryExprOrTypeTrait ExprKind,
  3614. SourceRange R) {
  3615. if (!TInfo)
  3616. return ExprError();
  3617. QualType T = TInfo->getType();
  3618. if (!T->isDependentType() &&
  3619. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3620. return ExprError();
  3621. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3622. if (auto *TT = T->getAs<TypedefType>()) {
  3623. for (auto I = FunctionScopes.rbegin(),
  3624. E = std::prev(FunctionScopes.rend());
  3625. I != E; ++I) {
  3626. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3627. if (CSI == nullptr)
  3628. break;
  3629. DeclContext *DC = nullptr;
  3630. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3631. DC = LSI->CallOperator;
  3632. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3633. DC = CRSI->TheCapturedDecl;
  3634. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3635. DC = BSI->TheDecl;
  3636. if (DC) {
  3637. if (DC->containsDecl(TT->getDecl()))
  3638. break;
  3639. captureVariablyModifiedType(Context, T, CSI);
  3640. }
  3641. }
  3642. }
  3643. }
  3644. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3645. return new (Context) UnaryExprOrTypeTraitExpr(
  3646. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3647. }
  3648. /// Build a sizeof or alignof expression given an expression
  3649. /// operand.
  3650. ExprResult
  3651. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3652. UnaryExprOrTypeTrait ExprKind) {
  3653. ExprResult PE = CheckPlaceholderExpr(E);
  3654. if (PE.isInvalid())
  3655. return ExprError();
  3656. E = PE.get();
  3657. // Verify that the operand is valid.
  3658. bool isInvalid = false;
  3659. if (E->isTypeDependent()) {
  3660. // Delay type-checking for type-dependent expressions.
  3661. } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3662. isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
  3663. } else if (ExprKind == UETT_VecStep) {
  3664. isInvalid = CheckVecStepExpr(E);
  3665. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3666. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3667. isInvalid = true;
  3668. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3669. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3670. isInvalid = true;
  3671. } else {
  3672. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3673. }
  3674. if (isInvalid)
  3675. return ExprError();
  3676. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3677. PE = TransformToPotentiallyEvaluated(E);
  3678. if (PE.isInvalid()) return ExprError();
  3679. E = PE.get();
  3680. }
  3681. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3682. return new (Context) UnaryExprOrTypeTraitExpr(
  3683. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3684. }
  3685. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3686. /// expr and the same for @c alignof and @c __alignof
  3687. /// Note that the ArgRange is invalid if isType is false.
  3688. ExprResult
  3689. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3690. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3691. void *TyOrEx, SourceRange ArgRange) {
  3692. // If error parsing type, ignore.
  3693. if (!TyOrEx) return ExprError();
  3694. if (IsType) {
  3695. TypeSourceInfo *TInfo;
  3696. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3697. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3698. }
  3699. Expr *ArgEx = (Expr *)TyOrEx;
  3700. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3701. return Result;
  3702. }
  3703. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3704. bool IsReal) {
  3705. if (V.get()->isTypeDependent())
  3706. return S.Context.DependentTy;
  3707. // _Real and _Imag are only l-values for normal l-values.
  3708. if (V.get()->getObjectKind() != OK_Ordinary) {
  3709. V = S.DefaultLvalueConversion(V.get());
  3710. if (V.isInvalid())
  3711. return QualType();
  3712. }
  3713. // These operators return the element type of a complex type.
  3714. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3715. return CT->getElementType();
  3716. // Otherwise they pass through real integer and floating point types here.
  3717. if (V.get()->getType()->isArithmeticType())
  3718. return V.get()->getType();
  3719. // Test for placeholders.
  3720. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3721. if (PR.isInvalid()) return QualType();
  3722. if (PR.get() != V.get()) {
  3723. V = PR;
  3724. return CheckRealImagOperand(S, V, Loc, IsReal);
  3725. }
  3726. // Reject anything else.
  3727. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3728. << (IsReal ? "__real" : "__imag");
  3729. return QualType();
  3730. }
  3731. ExprResult
  3732. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3733. tok::TokenKind Kind, Expr *Input) {
  3734. UnaryOperatorKind Opc;
  3735. switch (Kind) {
  3736. default: llvm_unreachable("Unknown unary op!");
  3737. case tok::plusplus: Opc = UO_PostInc; break;
  3738. case tok::minusminus: Opc = UO_PostDec; break;
  3739. }
  3740. // Since this might is a postfix expression, get rid of ParenListExprs.
  3741. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3742. if (Result.isInvalid()) return ExprError();
  3743. Input = Result.get();
  3744. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3745. }
  3746. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  3747. ///
  3748. /// \return true on error
  3749. static bool checkArithmeticOnObjCPointer(Sema &S,
  3750. SourceLocation opLoc,
  3751. Expr *op) {
  3752. assert(op->getType()->isObjCObjectPointerType());
  3753. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3754. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3755. return false;
  3756. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3757. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3758. << op->getSourceRange();
  3759. return true;
  3760. }
  3761. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3762. auto *BaseNoParens = Base->IgnoreParens();
  3763. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3764. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3765. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3766. }
  3767. ExprResult
  3768. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3769. Expr *idx, SourceLocation rbLoc) {
  3770. if (base && !base->getType().isNull() &&
  3771. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3772. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3773. /*Length=*/nullptr, rbLoc);
  3774. // Since this might be a postfix expression, get rid of ParenListExprs.
  3775. if (isa<ParenListExpr>(base)) {
  3776. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3777. if (result.isInvalid()) return ExprError();
  3778. base = result.get();
  3779. }
  3780. // A comma-expression as the index is deprecated in C++2a onwards.
  3781. if (getLangOpts().CPlusPlus2a &&
  3782. ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
  3783. (isa<CXXOperatorCallExpr>(idx) &&
  3784. cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
  3785. Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
  3786. << SourceRange(base->getBeginLoc(), rbLoc);
  3787. }
  3788. // Handle any non-overload placeholder types in the base and index
  3789. // expressions. We can't handle overloads here because the other
  3790. // operand might be an overloadable type, in which case the overload
  3791. // resolution for the operator overload should get the first crack
  3792. // at the overload.
  3793. bool IsMSPropertySubscript = false;
  3794. if (base->getType()->isNonOverloadPlaceholderType()) {
  3795. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3796. if (!IsMSPropertySubscript) {
  3797. ExprResult result = CheckPlaceholderExpr(base);
  3798. if (result.isInvalid())
  3799. return ExprError();
  3800. base = result.get();
  3801. }
  3802. }
  3803. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3804. ExprResult result = CheckPlaceholderExpr(idx);
  3805. if (result.isInvalid()) return ExprError();
  3806. idx = result.get();
  3807. }
  3808. // Build an unanalyzed expression if either operand is type-dependent.
  3809. if (getLangOpts().CPlusPlus &&
  3810. (base->isTypeDependent() || idx->isTypeDependent())) {
  3811. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3812. VK_LValue, OK_Ordinary, rbLoc);
  3813. }
  3814. // MSDN, property (C++)
  3815. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3816. // This attribute can also be used in the declaration of an empty array in a
  3817. // class or structure definition. For example:
  3818. // __declspec(property(get=GetX, put=PutX)) int x[];
  3819. // The above statement indicates that x[] can be used with one or more array
  3820. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3821. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3822. if (IsMSPropertySubscript) {
  3823. // Build MS property subscript expression if base is MS property reference
  3824. // or MS property subscript.
  3825. return new (Context) MSPropertySubscriptExpr(
  3826. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3827. }
  3828. // Use C++ overloaded-operator rules if either operand has record
  3829. // type. The spec says to do this if either type is *overloadable*,
  3830. // but enum types can't declare subscript operators or conversion
  3831. // operators, so there's nothing interesting for overload resolution
  3832. // to do if there aren't any record types involved.
  3833. //
  3834. // ObjC pointers have their own subscripting logic that is not tied
  3835. // to overload resolution and so should not take this path.
  3836. if (getLangOpts().CPlusPlus &&
  3837. (base->getType()->isRecordType() ||
  3838. (!base->getType()->isObjCObjectPointerType() &&
  3839. idx->getType()->isRecordType()))) {
  3840. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3841. }
  3842. ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3843. if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
  3844. CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
  3845. return Res;
  3846. }
  3847. void Sema::CheckAddressOfNoDeref(const Expr *E) {
  3848. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3849. const Expr *StrippedExpr = E->IgnoreParenImpCasts();
  3850. // For expressions like `&(*s).b`, the base is recorded and what should be
  3851. // checked.
  3852. const MemberExpr *Member = nullptr;
  3853. while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
  3854. StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
  3855. LastRecord.PossibleDerefs.erase(StrippedExpr);
  3856. }
  3857. void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
  3858. QualType ResultTy = E->getType();
  3859. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3860. // Bail if the element is an array since it is not memory access.
  3861. if (isa<ArrayType>(ResultTy))
  3862. return;
  3863. if (ResultTy->hasAttr(attr::NoDeref)) {
  3864. LastRecord.PossibleDerefs.insert(E);
  3865. return;
  3866. }
  3867. // Check if the base type is a pointer to a member access of a struct
  3868. // marked with noderef.
  3869. const Expr *Base = E->getBase();
  3870. QualType BaseTy = Base->getType();
  3871. if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
  3872. // Not a pointer access
  3873. return;
  3874. const MemberExpr *Member = nullptr;
  3875. while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
  3876. Member->isArrow())
  3877. Base = Member->getBase();
  3878. if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
  3879. if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
  3880. LastRecord.PossibleDerefs.insert(E);
  3881. }
  3882. }
  3883. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3884. Expr *LowerBound,
  3885. SourceLocation ColonLoc, Expr *Length,
  3886. SourceLocation RBLoc) {
  3887. if (Base->getType()->isPlaceholderType() &&
  3888. !Base->getType()->isSpecificPlaceholderType(
  3889. BuiltinType::OMPArraySection)) {
  3890. ExprResult Result = CheckPlaceholderExpr(Base);
  3891. if (Result.isInvalid())
  3892. return ExprError();
  3893. Base = Result.get();
  3894. }
  3895. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3896. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3897. if (Result.isInvalid())
  3898. return ExprError();
  3899. Result = DefaultLvalueConversion(Result.get());
  3900. if (Result.isInvalid())
  3901. return ExprError();
  3902. LowerBound = Result.get();
  3903. }
  3904. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3905. ExprResult Result = CheckPlaceholderExpr(Length);
  3906. if (Result.isInvalid())
  3907. return ExprError();
  3908. Result = DefaultLvalueConversion(Result.get());
  3909. if (Result.isInvalid())
  3910. return ExprError();
  3911. Length = Result.get();
  3912. }
  3913. // Build an unanalyzed expression if either operand is type-dependent.
  3914. if (Base->isTypeDependent() ||
  3915. (LowerBound &&
  3916. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3917. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3918. return new (Context)
  3919. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3920. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3921. }
  3922. // Perform default conversions.
  3923. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3924. QualType ResultTy;
  3925. if (OriginalTy->isAnyPointerType()) {
  3926. ResultTy = OriginalTy->getPointeeType();
  3927. } else if (OriginalTy->isArrayType()) {
  3928. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3929. } else {
  3930. return ExprError(
  3931. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3932. << Base->getSourceRange());
  3933. }
  3934. // C99 6.5.2.1p1
  3935. if (LowerBound) {
  3936. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3937. LowerBound);
  3938. if (Res.isInvalid())
  3939. return ExprError(Diag(LowerBound->getExprLoc(),
  3940. diag::err_omp_typecheck_section_not_integer)
  3941. << 0 << LowerBound->getSourceRange());
  3942. LowerBound = Res.get();
  3943. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3944. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3945. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3946. << 0 << LowerBound->getSourceRange();
  3947. }
  3948. if (Length) {
  3949. auto Res =
  3950. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3951. if (Res.isInvalid())
  3952. return ExprError(Diag(Length->getExprLoc(),
  3953. diag::err_omp_typecheck_section_not_integer)
  3954. << 1 << Length->getSourceRange());
  3955. Length = Res.get();
  3956. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3957. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3958. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3959. << 1 << Length->getSourceRange();
  3960. }
  3961. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3962. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3963. // type. Note that functions are not objects, and that (in C99 parlance)
  3964. // incomplete types are not object types.
  3965. if (ResultTy->isFunctionType()) {
  3966. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3967. << ResultTy << Base->getSourceRange();
  3968. return ExprError();
  3969. }
  3970. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3971. diag::err_omp_section_incomplete_type, Base))
  3972. return ExprError();
  3973. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  3974. Expr::EvalResult Result;
  3975. if (LowerBound->EvaluateAsInt(Result, Context)) {
  3976. // OpenMP 4.5, [2.4 Array Sections]
  3977. // The array section must be a subset of the original array.
  3978. llvm::APSInt LowerBoundValue = Result.Val.getInt();
  3979. if (LowerBoundValue.isNegative()) {
  3980. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  3981. << LowerBound->getSourceRange();
  3982. return ExprError();
  3983. }
  3984. }
  3985. }
  3986. if (Length) {
  3987. Expr::EvalResult Result;
  3988. if (Length->EvaluateAsInt(Result, Context)) {
  3989. // OpenMP 4.5, [2.4 Array Sections]
  3990. // The length must evaluate to non-negative integers.
  3991. llvm::APSInt LengthValue = Result.Val.getInt();
  3992. if (LengthValue.isNegative()) {
  3993. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  3994. << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  3995. << Length->getSourceRange();
  3996. return ExprError();
  3997. }
  3998. }
  3999. } else if (ColonLoc.isValid() &&
  4000. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  4001. !OriginalTy->isVariableArrayType()))) {
  4002. // OpenMP 4.5, [2.4 Array Sections]
  4003. // When the size of the array dimension is not known, the length must be
  4004. // specified explicitly.
  4005. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  4006. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  4007. return ExprError();
  4008. }
  4009. if (!Base->getType()->isSpecificPlaceholderType(
  4010. BuiltinType::OMPArraySection)) {
  4011. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  4012. if (Result.isInvalid())
  4013. return ExprError();
  4014. Base = Result.get();
  4015. }
  4016. return new (Context)
  4017. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  4018. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  4019. }
  4020. ExprResult
  4021. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  4022. Expr *Idx, SourceLocation RLoc) {
  4023. Expr *LHSExp = Base;
  4024. Expr *RHSExp = Idx;
  4025. ExprValueKind VK = VK_LValue;
  4026. ExprObjectKind OK = OK_Ordinary;
  4027. // Per C++ core issue 1213, the result is an xvalue if either operand is
  4028. // a non-lvalue array, and an lvalue otherwise.
  4029. if (getLangOpts().CPlusPlus11) {
  4030. for (auto *Op : {LHSExp, RHSExp}) {
  4031. Op = Op->IgnoreImplicit();
  4032. if (Op->getType()->isArrayType() && !Op->isLValue())
  4033. VK = VK_XValue;
  4034. }
  4035. }
  4036. // Perform default conversions.
  4037. if (!LHSExp->getType()->getAs<VectorType>()) {
  4038. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  4039. if (Result.isInvalid())
  4040. return ExprError();
  4041. LHSExp = Result.get();
  4042. }
  4043. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  4044. if (Result.isInvalid())
  4045. return ExprError();
  4046. RHSExp = Result.get();
  4047. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  4048. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  4049. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  4050. // in the subscript position. As a result, we need to derive the array base
  4051. // and index from the expression types.
  4052. Expr *BaseExpr, *IndexExpr;
  4053. QualType ResultType;
  4054. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  4055. BaseExpr = LHSExp;
  4056. IndexExpr = RHSExp;
  4057. ResultType = Context.DependentTy;
  4058. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  4059. BaseExpr = LHSExp;
  4060. IndexExpr = RHSExp;
  4061. ResultType = PTy->getPointeeType();
  4062. } else if (const ObjCObjectPointerType *PTy =
  4063. LHSTy->getAs<ObjCObjectPointerType>()) {
  4064. BaseExpr = LHSExp;
  4065. IndexExpr = RHSExp;
  4066. // Use custom logic if this should be the pseudo-object subscript
  4067. // expression.
  4068. if (!LangOpts.isSubscriptPointerArithmetic())
  4069. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  4070. nullptr);
  4071. ResultType = PTy->getPointeeType();
  4072. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  4073. // Handle the uncommon case of "123[Ptr]".
  4074. BaseExpr = RHSExp;
  4075. IndexExpr = LHSExp;
  4076. ResultType = PTy->getPointeeType();
  4077. } else if (const ObjCObjectPointerType *PTy =
  4078. RHSTy->getAs<ObjCObjectPointerType>()) {
  4079. // Handle the uncommon case of "123[Ptr]".
  4080. BaseExpr = RHSExp;
  4081. IndexExpr = LHSExp;
  4082. ResultType = PTy->getPointeeType();
  4083. if (!LangOpts.isSubscriptPointerArithmetic()) {
  4084. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  4085. << ResultType << BaseExpr->getSourceRange();
  4086. return ExprError();
  4087. }
  4088. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  4089. BaseExpr = LHSExp; // vectors: V[123]
  4090. IndexExpr = RHSExp;
  4091. // We apply C++ DR1213 to vector subscripting too.
  4092. if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
  4093. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  4094. if (Materialized.isInvalid())
  4095. return ExprError();
  4096. LHSExp = Materialized.get();
  4097. }
  4098. VK = LHSExp->getValueKind();
  4099. if (VK != VK_RValue)
  4100. OK = OK_VectorComponent;
  4101. ResultType = VTy->getElementType();
  4102. QualType BaseType = BaseExpr->getType();
  4103. Qualifiers BaseQuals = BaseType.getQualifiers();
  4104. Qualifiers MemberQuals = ResultType.getQualifiers();
  4105. Qualifiers Combined = BaseQuals + MemberQuals;
  4106. if (Combined != MemberQuals)
  4107. ResultType = Context.getQualifiedType(ResultType, Combined);
  4108. } else if (LHSTy->isArrayType()) {
  4109. // If we see an array that wasn't promoted by
  4110. // DefaultFunctionArrayLvalueConversion, it must be an array that
  4111. // wasn't promoted because of the C90 rule that doesn't
  4112. // allow promoting non-lvalue arrays. Warn, then
  4113. // force the promotion here.
  4114. Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4115. << LHSExp->getSourceRange();
  4116. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  4117. CK_ArrayToPointerDecay).get();
  4118. LHSTy = LHSExp->getType();
  4119. BaseExpr = LHSExp;
  4120. IndexExpr = RHSExp;
  4121. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  4122. } else if (RHSTy->isArrayType()) {
  4123. // Same as previous, except for 123[f().a] case
  4124. Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4125. << RHSExp->getSourceRange();
  4126. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  4127. CK_ArrayToPointerDecay).get();
  4128. RHSTy = RHSExp->getType();
  4129. BaseExpr = RHSExp;
  4130. IndexExpr = LHSExp;
  4131. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  4132. } else {
  4133. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  4134. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  4135. }
  4136. // C99 6.5.2.1p1
  4137. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  4138. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  4139. << IndexExpr->getSourceRange());
  4140. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4141. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4142. && !IndexExpr->isTypeDependent())
  4143. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  4144. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  4145. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  4146. // type. Note that Functions are not objects, and that (in C99 parlance)
  4147. // incomplete types are not object types.
  4148. if (ResultType->isFunctionType()) {
  4149. Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
  4150. << ResultType << BaseExpr->getSourceRange();
  4151. return ExprError();
  4152. }
  4153. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  4154. // GNU extension: subscripting on pointer to void
  4155. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  4156. << BaseExpr->getSourceRange();
  4157. // C forbids expressions of unqualified void type from being l-values.
  4158. // See IsCForbiddenLValueType.
  4159. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  4160. } else if (!ResultType->isDependentType() &&
  4161. RequireCompleteType(LLoc, ResultType,
  4162. diag::err_subscript_incomplete_type, BaseExpr))
  4163. return ExprError();
  4164. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  4165. !ResultType.isCForbiddenLValueType());
  4166. if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
  4167. FunctionScopes.size() > 1) {
  4168. if (auto *TT =
  4169. LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
  4170. for (auto I = FunctionScopes.rbegin(),
  4171. E = std::prev(FunctionScopes.rend());
  4172. I != E; ++I) {
  4173. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  4174. if (CSI == nullptr)
  4175. break;
  4176. DeclContext *DC = nullptr;
  4177. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  4178. DC = LSI->CallOperator;
  4179. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  4180. DC = CRSI->TheCapturedDecl;
  4181. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  4182. DC = BSI->TheDecl;
  4183. if (DC) {
  4184. if (DC->containsDecl(TT->getDecl()))
  4185. break;
  4186. captureVariablyModifiedType(
  4187. Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
  4188. }
  4189. }
  4190. }
  4191. }
  4192. return new (Context)
  4193. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  4194. }
  4195. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  4196. ParmVarDecl *Param) {
  4197. if (Param->hasUnparsedDefaultArg()) {
  4198. Diag(CallLoc,
  4199. diag::err_use_of_default_argument_to_function_declared_later) <<
  4200. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  4201. Diag(UnparsedDefaultArgLocs[Param],
  4202. diag::note_default_argument_declared_here);
  4203. return true;
  4204. }
  4205. if (Param->hasUninstantiatedDefaultArg()) {
  4206. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  4207. EnterExpressionEvaluationContext EvalContext(
  4208. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4209. // Instantiate the expression.
  4210. //
  4211. // FIXME: Pass in a correct Pattern argument, otherwise
  4212. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  4213. //
  4214. // template<typename T>
  4215. // struct A {
  4216. // static int FooImpl();
  4217. //
  4218. // template<typename Tp>
  4219. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  4220. // // template argument list [[T], [Tp]], should be [[Tp]].
  4221. // friend A<Tp> Foo(int a);
  4222. // };
  4223. //
  4224. // template<typename T>
  4225. // A<T> Foo(int a = A<T>::FooImpl());
  4226. MultiLevelTemplateArgumentList MutiLevelArgList
  4227. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  4228. InstantiatingTemplate Inst(*this, CallLoc, Param,
  4229. MutiLevelArgList.getInnermost());
  4230. if (Inst.isInvalid())
  4231. return true;
  4232. if (Inst.isAlreadyInstantiating()) {
  4233. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4234. Param->setInvalidDecl();
  4235. return true;
  4236. }
  4237. ExprResult Result;
  4238. {
  4239. // C++ [dcl.fct.default]p5:
  4240. // The names in the [default argument] expression are bound, and
  4241. // the semantic constraints are checked, at the point where the
  4242. // default argument expression appears.
  4243. ContextRAII SavedContext(*this, FD);
  4244. LocalInstantiationScope Local(*this);
  4245. runWithSufficientStackSpace(CallLoc, [&] {
  4246. Result = SubstInitializer(UninstExpr, MutiLevelArgList,
  4247. /*DirectInit*/false);
  4248. });
  4249. }
  4250. if (Result.isInvalid())
  4251. return true;
  4252. // Check the expression as an initializer for the parameter.
  4253. InitializedEntity Entity
  4254. = InitializedEntity::InitializeParameter(Context, Param);
  4255. InitializationKind Kind = InitializationKind::CreateCopy(
  4256. Param->getLocation(),
  4257. /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
  4258. Expr *ResultE = Result.getAs<Expr>();
  4259. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  4260. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  4261. if (Result.isInvalid())
  4262. return true;
  4263. Result =
  4264. ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
  4265. /*DiscardedValue*/ false);
  4266. if (Result.isInvalid())
  4267. return true;
  4268. // Remember the instantiated default argument.
  4269. Param->setDefaultArg(Result.getAs<Expr>());
  4270. if (ASTMutationListener *L = getASTMutationListener()) {
  4271. L->DefaultArgumentInstantiated(Param);
  4272. }
  4273. }
  4274. // If the default argument expression is not set yet, we are building it now.
  4275. if (!Param->hasInit()) {
  4276. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4277. Param->setInvalidDecl();
  4278. return true;
  4279. }
  4280. // If the default expression creates temporaries, we need to
  4281. // push them to the current stack of expression temporaries so they'll
  4282. // be properly destroyed.
  4283. // FIXME: We should really be rebuilding the default argument with new
  4284. // bound temporaries; see the comment in PR5810.
  4285. // We don't need to do that with block decls, though, because
  4286. // blocks in default argument expression can never capture anything.
  4287. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  4288. // Set the "needs cleanups" bit regardless of whether there are
  4289. // any explicit objects.
  4290. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  4291. // Append all the objects to the cleanup list. Right now, this
  4292. // should always be a no-op, because blocks in default argument
  4293. // expressions should never be able to capture anything.
  4294. assert(!Init->getNumObjects() &&
  4295. "default argument expression has capturing blocks?");
  4296. }
  4297. // We already type-checked the argument, so we know it works.
  4298. // Just mark all of the declarations in this potentially-evaluated expression
  4299. // as being "referenced".
  4300. EnterExpressionEvaluationContext EvalContext(
  4301. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4302. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  4303. /*SkipLocalVariables=*/true);
  4304. return false;
  4305. }
  4306. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  4307. FunctionDecl *FD, ParmVarDecl *Param) {
  4308. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  4309. return ExprError();
  4310. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
  4311. }
  4312. Sema::VariadicCallType
  4313. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  4314. Expr *Fn) {
  4315. if (Proto && Proto->isVariadic()) {
  4316. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  4317. return VariadicConstructor;
  4318. else if (Fn && Fn->getType()->isBlockPointerType())
  4319. return VariadicBlock;
  4320. else if (FDecl) {
  4321. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4322. if (Method->isInstance())
  4323. return VariadicMethod;
  4324. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  4325. return VariadicMethod;
  4326. return VariadicFunction;
  4327. }
  4328. return VariadicDoesNotApply;
  4329. }
  4330. namespace {
  4331. class FunctionCallCCC final : public FunctionCallFilterCCC {
  4332. public:
  4333. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  4334. unsigned NumArgs, MemberExpr *ME)
  4335. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  4336. FunctionName(FuncName) {}
  4337. bool ValidateCandidate(const TypoCorrection &candidate) override {
  4338. if (!candidate.getCorrectionSpecifier() ||
  4339. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  4340. return false;
  4341. }
  4342. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  4343. }
  4344. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  4345. return std::make_unique<FunctionCallCCC>(*this);
  4346. }
  4347. private:
  4348. const IdentifierInfo *const FunctionName;
  4349. };
  4350. }
  4351. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  4352. FunctionDecl *FDecl,
  4353. ArrayRef<Expr *> Args) {
  4354. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  4355. DeclarationName FuncName = FDecl->getDeclName();
  4356. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
  4357. FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
  4358. if (TypoCorrection Corrected = S.CorrectTypo(
  4359. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  4360. S.getScopeForContext(S.CurContext), nullptr, CCC,
  4361. Sema::CTK_ErrorRecovery)) {
  4362. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  4363. if (Corrected.isOverloaded()) {
  4364. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  4365. OverloadCandidateSet::iterator Best;
  4366. for (NamedDecl *CD : Corrected) {
  4367. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  4368. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  4369. OCS);
  4370. }
  4371. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  4372. case OR_Success:
  4373. ND = Best->FoundDecl;
  4374. Corrected.setCorrectionDecl(ND);
  4375. break;
  4376. default:
  4377. break;
  4378. }
  4379. }
  4380. ND = ND->getUnderlyingDecl();
  4381. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  4382. return Corrected;
  4383. }
  4384. }
  4385. return TypoCorrection();
  4386. }
  4387. /// ConvertArgumentsForCall - Converts the arguments specified in
  4388. /// Args/NumArgs to the parameter types of the function FDecl with
  4389. /// function prototype Proto. Call is the call expression itself, and
  4390. /// Fn is the function expression. For a C++ member function, this
  4391. /// routine does not attempt to convert the object argument. Returns
  4392. /// true if the call is ill-formed.
  4393. bool
  4394. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  4395. FunctionDecl *FDecl,
  4396. const FunctionProtoType *Proto,
  4397. ArrayRef<Expr *> Args,
  4398. SourceLocation RParenLoc,
  4399. bool IsExecConfig) {
  4400. // Bail out early if calling a builtin with custom typechecking.
  4401. if (FDecl)
  4402. if (unsigned ID = FDecl->getBuiltinID())
  4403. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  4404. return false;
  4405. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  4406. // assignment, to the types of the corresponding parameter, ...
  4407. unsigned NumParams = Proto->getNumParams();
  4408. bool Invalid = false;
  4409. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  4410. unsigned FnKind = Fn->getType()->isBlockPointerType()
  4411. ? 1 /* block */
  4412. : (IsExecConfig ? 3 /* kernel function (exec config) */
  4413. : 0 /* function */);
  4414. // If too few arguments are available (and we don't have default
  4415. // arguments for the remaining parameters), don't make the call.
  4416. if (Args.size() < NumParams) {
  4417. if (Args.size() < MinArgs) {
  4418. TypoCorrection TC;
  4419. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4420. unsigned diag_id =
  4421. MinArgs == NumParams && !Proto->isVariadic()
  4422. ? diag::err_typecheck_call_too_few_args_suggest
  4423. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  4424. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  4425. << static_cast<unsigned>(Args.size())
  4426. << TC.getCorrectionRange());
  4427. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  4428. Diag(RParenLoc,
  4429. MinArgs == NumParams && !Proto->isVariadic()
  4430. ? diag::err_typecheck_call_too_few_args_one
  4431. : diag::err_typecheck_call_too_few_args_at_least_one)
  4432. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  4433. else
  4434. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  4435. ? diag::err_typecheck_call_too_few_args
  4436. : diag::err_typecheck_call_too_few_args_at_least)
  4437. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  4438. << Fn->getSourceRange();
  4439. // Emit the location of the prototype.
  4440. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4441. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4442. return true;
  4443. }
  4444. // We reserve space for the default arguments when we create
  4445. // the call expression, before calling ConvertArgumentsForCall.
  4446. assert((Call->getNumArgs() == NumParams) &&
  4447. "We should have reserved space for the default arguments before!");
  4448. }
  4449. // If too many are passed and not variadic, error on the extras and drop
  4450. // them.
  4451. if (Args.size() > NumParams) {
  4452. if (!Proto->isVariadic()) {
  4453. TypoCorrection TC;
  4454. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4455. unsigned diag_id =
  4456. MinArgs == NumParams && !Proto->isVariadic()
  4457. ? diag::err_typecheck_call_too_many_args_suggest
  4458. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4459. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4460. << static_cast<unsigned>(Args.size())
  4461. << TC.getCorrectionRange());
  4462. } else if (NumParams == 1 && FDecl &&
  4463. FDecl->getParamDecl(0)->getDeclName())
  4464. Diag(Args[NumParams]->getBeginLoc(),
  4465. MinArgs == NumParams
  4466. ? diag::err_typecheck_call_too_many_args_one
  4467. : diag::err_typecheck_call_too_many_args_at_most_one)
  4468. << FnKind << FDecl->getParamDecl(0)
  4469. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4470. << SourceRange(Args[NumParams]->getBeginLoc(),
  4471. Args.back()->getEndLoc());
  4472. else
  4473. Diag(Args[NumParams]->getBeginLoc(),
  4474. MinArgs == NumParams
  4475. ? diag::err_typecheck_call_too_many_args
  4476. : diag::err_typecheck_call_too_many_args_at_most)
  4477. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4478. << Fn->getSourceRange()
  4479. << SourceRange(Args[NumParams]->getBeginLoc(),
  4480. Args.back()->getEndLoc());
  4481. // Emit the location of the prototype.
  4482. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4483. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4484. // This deletes the extra arguments.
  4485. Call->shrinkNumArgs(NumParams);
  4486. return true;
  4487. }
  4488. }
  4489. SmallVector<Expr *, 8> AllArgs;
  4490. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4491. Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
  4492. AllArgs, CallType);
  4493. if (Invalid)
  4494. return true;
  4495. unsigned TotalNumArgs = AllArgs.size();
  4496. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4497. Call->setArg(i, AllArgs[i]);
  4498. return false;
  4499. }
  4500. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4501. const FunctionProtoType *Proto,
  4502. unsigned FirstParam, ArrayRef<Expr *> Args,
  4503. SmallVectorImpl<Expr *> &AllArgs,
  4504. VariadicCallType CallType, bool AllowExplicit,
  4505. bool IsListInitialization) {
  4506. unsigned NumParams = Proto->getNumParams();
  4507. bool Invalid = false;
  4508. size_t ArgIx = 0;
  4509. // Continue to check argument types (even if we have too few/many args).
  4510. for (unsigned i = FirstParam; i < NumParams; i++) {
  4511. QualType ProtoArgType = Proto->getParamType(i);
  4512. Expr *Arg;
  4513. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4514. if (ArgIx < Args.size()) {
  4515. Arg = Args[ArgIx++];
  4516. if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
  4517. diag::err_call_incomplete_argument, Arg))
  4518. return true;
  4519. // Strip the unbridged-cast placeholder expression off, if applicable.
  4520. bool CFAudited = false;
  4521. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4522. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4523. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4524. Arg = stripARCUnbridgedCast(Arg);
  4525. else if (getLangOpts().ObjCAutoRefCount &&
  4526. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4527. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4528. CFAudited = true;
  4529. if (Proto->getExtParameterInfo(i).isNoEscape())
  4530. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  4531. BE->getBlockDecl()->setDoesNotEscape();
  4532. InitializedEntity Entity =
  4533. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4534. ProtoArgType)
  4535. : InitializedEntity::InitializeParameter(
  4536. Context, ProtoArgType, Proto->isParamConsumed(i));
  4537. // Remember that parameter belongs to a CF audited API.
  4538. if (CFAudited)
  4539. Entity.setParameterCFAudited();
  4540. ExprResult ArgE = PerformCopyInitialization(
  4541. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4542. if (ArgE.isInvalid())
  4543. return true;
  4544. Arg = ArgE.getAs<Expr>();
  4545. } else {
  4546. assert(Param && "can't use default arguments without a known callee");
  4547. ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4548. if (ArgExpr.isInvalid())
  4549. return true;
  4550. Arg = ArgExpr.getAs<Expr>();
  4551. }
  4552. // Check for array bounds violations for each argument to the call. This
  4553. // check only triggers warnings when the argument isn't a more complex Expr
  4554. // with its own checking, such as a BinaryOperator.
  4555. CheckArrayAccess(Arg);
  4556. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4557. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4558. AllArgs.push_back(Arg);
  4559. }
  4560. // If this is a variadic call, handle args passed through "...".
  4561. if (CallType != VariadicDoesNotApply) {
  4562. // Assume that extern "C" functions with variadic arguments that
  4563. // return __unknown_anytype aren't *really* variadic.
  4564. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4565. FDecl->isExternC()) {
  4566. for (Expr *A : Args.slice(ArgIx)) {
  4567. QualType paramType; // ignored
  4568. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  4569. Invalid |= arg.isInvalid();
  4570. AllArgs.push_back(arg.get());
  4571. }
  4572. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4573. } else {
  4574. for (Expr *A : Args.slice(ArgIx)) {
  4575. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  4576. Invalid |= Arg.isInvalid();
  4577. AllArgs.push_back(Arg.get());
  4578. }
  4579. }
  4580. // Check for array bounds violations.
  4581. for (Expr *A : Args.slice(ArgIx))
  4582. CheckArrayAccess(A);
  4583. }
  4584. return Invalid;
  4585. }
  4586. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4587. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4588. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4589. TL = DTL.getOriginalLoc();
  4590. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4591. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4592. << ATL.getLocalSourceRange();
  4593. }
  4594. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4595. /// array parameter, check that it is non-null, and that if it is formed by
  4596. /// array-to-pointer decay, the underlying array is sufficiently large.
  4597. ///
  4598. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4599. /// array type derivation, then for each call to the function, the value of the
  4600. /// corresponding actual argument shall provide access to the first element of
  4601. /// an array with at least as many elements as specified by the size expression.
  4602. void
  4603. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4604. ParmVarDecl *Param,
  4605. const Expr *ArgExpr) {
  4606. // Static array parameters are not supported in C++.
  4607. if (!Param || getLangOpts().CPlusPlus)
  4608. return;
  4609. QualType OrigTy = Param->getOriginalType();
  4610. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4611. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4612. return;
  4613. if (ArgExpr->isNullPointerConstant(Context,
  4614. Expr::NPC_NeverValueDependent)) {
  4615. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4616. DiagnoseCalleeStaticArrayParam(*this, Param);
  4617. return;
  4618. }
  4619. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4620. if (!CAT)
  4621. return;
  4622. const ConstantArrayType *ArgCAT =
  4623. Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
  4624. if (!ArgCAT)
  4625. return;
  4626. if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
  4627. ArgCAT->getElementType())) {
  4628. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4629. Diag(CallLoc, diag::warn_static_array_too_small)
  4630. << ArgExpr->getSourceRange()
  4631. << (unsigned)ArgCAT->getSize().getZExtValue()
  4632. << (unsigned)CAT->getSize().getZExtValue() << 0;
  4633. DiagnoseCalleeStaticArrayParam(*this, Param);
  4634. }
  4635. return;
  4636. }
  4637. Optional<CharUnits> ArgSize =
  4638. getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
  4639. Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
  4640. if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
  4641. Diag(CallLoc, diag::warn_static_array_too_small)
  4642. << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
  4643. << (unsigned)ParmSize->getQuantity() << 1;
  4644. DiagnoseCalleeStaticArrayParam(*this, Param);
  4645. }
  4646. }
  4647. /// Given a function expression of unknown-any type, try to rebuild it
  4648. /// to have a function type.
  4649. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4650. /// Is the given type a placeholder that we need to lower out
  4651. /// immediately during argument processing?
  4652. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4653. // Placeholders are never sugared.
  4654. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4655. if (!placeholder) return false;
  4656. switch (placeholder->getKind()) {
  4657. // Ignore all the non-placeholder types.
  4658. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  4659. case BuiltinType::Id:
  4660. #include "clang/Basic/OpenCLImageTypes.def"
  4661. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  4662. case BuiltinType::Id:
  4663. #include "clang/Basic/OpenCLExtensionTypes.def"
  4664. // In practice we'll never use this, since all SVE types are sugared
  4665. // via TypedefTypes rather than exposed directly as BuiltinTypes.
  4666. #define SVE_TYPE(Name, Id, SingletonId) \
  4667. case BuiltinType::Id:
  4668. #include "clang/Basic/AArch64SVEACLETypes.def"
  4669. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4670. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4671. #include "clang/AST/BuiltinTypes.def"
  4672. return false;
  4673. // We cannot lower out overload sets; they might validly be resolved
  4674. // by the call machinery.
  4675. case BuiltinType::Overload:
  4676. return false;
  4677. // Unbridged casts in ARC can be handled in some call positions and
  4678. // should be left in place.
  4679. case BuiltinType::ARCUnbridgedCast:
  4680. return false;
  4681. // Pseudo-objects should be converted as soon as possible.
  4682. case BuiltinType::PseudoObject:
  4683. return true;
  4684. // The debugger mode could theoretically but currently does not try
  4685. // to resolve unknown-typed arguments based on known parameter types.
  4686. case BuiltinType::UnknownAny:
  4687. return true;
  4688. // These are always invalid as call arguments and should be reported.
  4689. case BuiltinType::BoundMember:
  4690. case BuiltinType::BuiltinFn:
  4691. case BuiltinType::OMPArraySection:
  4692. return true;
  4693. }
  4694. llvm_unreachable("bad builtin type kind");
  4695. }
  4696. /// Check an argument list for placeholders that we won't try to
  4697. /// handle later.
  4698. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4699. // Apply this processing to all the arguments at once instead of
  4700. // dying at the first failure.
  4701. bool hasInvalid = false;
  4702. for (size_t i = 0, e = args.size(); i != e; i++) {
  4703. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4704. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4705. if (result.isInvalid()) hasInvalid = true;
  4706. else args[i] = result.get();
  4707. } else if (hasInvalid) {
  4708. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4709. }
  4710. }
  4711. return hasInvalid;
  4712. }
  4713. /// If a builtin function has a pointer argument with no explicit address
  4714. /// space, then it should be able to accept a pointer to any address
  4715. /// space as input. In order to do this, we need to replace the
  4716. /// standard builtin declaration with one that uses the same address space
  4717. /// as the call.
  4718. ///
  4719. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4720. /// it does not contain any pointer arguments without
  4721. /// an address space qualifer. Otherwise the rewritten
  4722. /// FunctionDecl is returned.
  4723. /// TODO: Handle pointer return types.
  4724. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4725. FunctionDecl *FDecl,
  4726. MultiExprArg ArgExprs) {
  4727. QualType DeclType = FDecl->getType();
  4728. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4729. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
  4730. ArgExprs.size() < FT->getNumParams())
  4731. return nullptr;
  4732. bool NeedsNewDecl = false;
  4733. unsigned i = 0;
  4734. SmallVector<QualType, 8> OverloadParams;
  4735. for (QualType ParamType : FT->param_types()) {
  4736. // Convert array arguments to pointer to simplify type lookup.
  4737. ExprResult ArgRes =
  4738. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  4739. if (ArgRes.isInvalid())
  4740. return nullptr;
  4741. Expr *Arg = ArgRes.get();
  4742. QualType ArgType = Arg->getType();
  4743. if (!ParamType->isPointerType() ||
  4744. ParamType.getQualifiers().hasAddressSpace() ||
  4745. !ArgType->isPointerType() ||
  4746. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4747. OverloadParams.push_back(ParamType);
  4748. continue;
  4749. }
  4750. QualType PointeeType = ParamType->getPointeeType();
  4751. if (PointeeType.getQualifiers().hasAddressSpace())
  4752. continue;
  4753. NeedsNewDecl = true;
  4754. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  4755. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4756. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4757. }
  4758. if (!NeedsNewDecl)
  4759. return nullptr;
  4760. FunctionProtoType::ExtProtoInfo EPI;
  4761. EPI.Variadic = FT->isVariadic();
  4762. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4763. OverloadParams, EPI);
  4764. DeclContext *Parent = FDecl->getParent();
  4765. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4766. FDecl->getLocation(),
  4767. FDecl->getLocation(),
  4768. FDecl->getIdentifier(),
  4769. OverloadTy,
  4770. /*TInfo=*/nullptr,
  4771. SC_Extern, false,
  4772. /*hasPrototype=*/true);
  4773. SmallVector<ParmVarDecl*, 16> Params;
  4774. FT = cast<FunctionProtoType>(OverloadTy);
  4775. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4776. QualType ParamType = FT->getParamType(i);
  4777. ParmVarDecl *Parm =
  4778. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4779. SourceLocation(), nullptr, ParamType,
  4780. /*TInfo=*/nullptr, SC_None, nullptr);
  4781. Parm->setScopeInfo(0, i);
  4782. Params.push_back(Parm);
  4783. }
  4784. OverloadDecl->setParams(Params);
  4785. return OverloadDecl;
  4786. }
  4787. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  4788. FunctionDecl *Callee,
  4789. MultiExprArg ArgExprs) {
  4790. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  4791. // similar attributes) really don't like it when functions are called with an
  4792. // invalid number of args.
  4793. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  4794. /*PartialOverloading=*/false) &&
  4795. !Callee->isVariadic())
  4796. return;
  4797. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  4798. return;
  4799. if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
  4800. S.Diag(Fn->getBeginLoc(),
  4801. isa<CXXMethodDecl>(Callee)
  4802. ? diag::err_ovl_no_viable_member_function_in_call
  4803. : diag::err_ovl_no_viable_function_in_call)
  4804. << Callee << Callee->getSourceRange();
  4805. S.Diag(Callee->getLocation(),
  4806. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  4807. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4808. return;
  4809. }
  4810. }
  4811. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  4812. const UnresolvedMemberExpr *const UME, Sema &S) {
  4813. const auto GetFunctionLevelDCIfCXXClass =
  4814. [](Sema &S) -> const CXXRecordDecl * {
  4815. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  4816. if (!DC || !DC->getParent())
  4817. return nullptr;
  4818. // If the call to some member function was made from within a member
  4819. // function body 'M' return return 'M's parent.
  4820. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  4821. return MD->getParent()->getCanonicalDecl();
  4822. // else the call was made from within a default member initializer of a
  4823. // class, so return the class.
  4824. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  4825. return RD->getCanonicalDecl();
  4826. return nullptr;
  4827. };
  4828. // If our DeclContext is neither a member function nor a class (in the
  4829. // case of a lambda in a default member initializer), we can't have an
  4830. // enclosing 'this'.
  4831. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  4832. if (!CurParentClass)
  4833. return false;
  4834. // The naming class for implicit member functions call is the class in which
  4835. // name lookup starts.
  4836. const CXXRecordDecl *const NamingClass =
  4837. UME->getNamingClass()->getCanonicalDecl();
  4838. assert(NamingClass && "Must have naming class even for implicit access");
  4839. // If the unresolved member functions were found in a 'naming class' that is
  4840. // related (either the same or derived from) to the class that contains the
  4841. // member function that itself contained the implicit member access.
  4842. return CurParentClass == NamingClass ||
  4843. CurParentClass->isDerivedFrom(NamingClass);
  4844. }
  4845. static void
  4846. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4847. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  4848. if (!UME)
  4849. return;
  4850. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  4851. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  4852. // already been captured, or if this is an implicit member function call (if
  4853. // it isn't, an attempt to capture 'this' should already have been made).
  4854. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  4855. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  4856. return;
  4857. // Check if the naming class in which the unresolved members were found is
  4858. // related (same as or is a base of) to the enclosing class.
  4859. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  4860. return;
  4861. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  4862. // If the enclosing function is not dependent, then this lambda is
  4863. // capture ready, so if we can capture this, do so.
  4864. if (!EnclosingFunctionCtx->isDependentContext()) {
  4865. // If the current lambda and all enclosing lambdas can capture 'this' -
  4866. // then go ahead and capture 'this' (since our unresolved overload set
  4867. // contains at least one non-static member function).
  4868. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  4869. S.CheckCXXThisCapture(CallLoc);
  4870. } else if (S.CurContext->isDependentContext()) {
  4871. // ... since this is an implicit member reference, that might potentially
  4872. // involve a 'this' capture, mark 'this' for potential capture in
  4873. // enclosing lambdas.
  4874. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  4875. CurLSI->addPotentialThisCapture(CallLoc);
  4876. }
  4877. }
  4878. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4879. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4880. Expr *ExecConfig) {
  4881. ExprResult Call =
  4882. BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
  4883. if (Call.isInvalid())
  4884. return Call;
  4885. // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
  4886. // language modes.
  4887. if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
  4888. if (ULE->hasExplicitTemplateArgs() &&
  4889. ULE->decls_begin() == ULE->decls_end()) {
  4890. Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
  4891. ? diag::warn_cxx17_compat_adl_only_template_id
  4892. : diag::ext_adl_only_template_id)
  4893. << ULE->getName();
  4894. }
  4895. }
  4896. return Call;
  4897. }
  4898. /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
  4899. /// This provides the location of the left/right parens and a list of comma
  4900. /// locations.
  4901. ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4902. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4903. Expr *ExecConfig, bool IsExecConfig) {
  4904. // Since this might be a postfix expression, get rid of ParenListExprs.
  4905. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  4906. if (Result.isInvalid()) return ExprError();
  4907. Fn = Result.get();
  4908. if (checkArgsForPlaceholders(*this, ArgExprs))
  4909. return ExprError();
  4910. if (getLangOpts().CPlusPlus) {
  4911. // If this is a pseudo-destructor expression, build the call immediately.
  4912. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4913. if (!ArgExprs.empty()) {
  4914. // Pseudo-destructor calls should not have any arguments.
  4915. Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
  4916. << FixItHint::CreateRemoval(
  4917. SourceRange(ArgExprs.front()->getBeginLoc(),
  4918. ArgExprs.back()->getEndLoc()));
  4919. }
  4920. return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
  4921. VK_RValue, RParenLoc);
  4922. }
  4923. if (Fn->getType() == Context.PseudoObjectTy) {
  4924. ExprResult result = CheckPlaceholderExpr(Fn);
  4925. if (result.isInvalid()) return ExprError();
  4926. Fn = result.get();
  4927. }
  4928. // Determine whether this is a dependent call inside a C++ template,
  4929. // in which case we won't do any semantic analysis now.
  4930. if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
  4931. if (ExecConfig) {
  4932. return CUDAKernelCallExpr::Create(
  4933. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4934. Context.DependentTy, VK_RValue, RParenLoc);
  4935. } else {
  4936. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4937. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  4938. Fn->getBeginLoc());
  4939. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4940. VK_RValue, RParenLoc);
  4941. }
  4942. }
  4943. // Determine whether this is a call to an object (C++ [over.call.object]).
  4944. if (Fn->getType()->isRecordType())
  4945. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  4946. RParenLoc);
  4947. if (Fn->getType() == Context.UnknownAnyTy) {
  4948. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4949. if (result.isInvalid()) return ExprError();
  4950. Fn = result.get();
  4951. }
  4952. if (Fn->getType() == Context.BoundMemberTy) {
  4953. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4954. RParenLoc);
  4955. }
  4956. }
  4957. // Check for overloaded calls. This can happen even in C due to extensions.
  4958. if (Fn->getType() == Context.OverloadTy) {
  4959. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4960. // We aren't supposed to apply this logic if there's an '&' involved.
  4961. if (!find.HasFormOfMemberPointer) {
  4962. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4963. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4964. VK_RValue, RParenLoc);
  4965. OverloadExpr *ovl = find.Expression;
  4966. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  4967. return BuildOverloadedCallExpr(
  4968. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  4969. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  4970. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4971. RParenLoc);
  4972. }
  4973. }
  4974. // If we're directly calling a function, get the appropriate declaration.
  4975. if (Fn->getType() == Context.UnknownAnyTy) {
  4976. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4977. if (result.isInvalid()) return ExprError();
  4978. Fn = result.get();
  4979. }
  4980. Expr *NakedFn = Fn->IgnoreParens();
  4981. bool CallingNDeclIndirectly = false;
  4982. NamedDecl *NDecl = nullptr;
  4983. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  4984. if (UnOp->getOpcode() == UO_AddrOf) {
  4985. CallingNDeclIndirectly = true;
  4986. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4987. }
  4988. }
  4989. if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
  4990. NDecl = DRE->getDecl();
  4991. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4992. if (FDecl && FDecl->getBuiltinID()) {
  4993. // Rewrite the function decl for this builtin by replacing parameters
  4994. // with no explicit address space with the address space of the arguments
  4995. // in ArgExprs.
  4996. if ((FDecl =
  4997. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4998. NDecl = FDecl;
  4999. Fn = DeclRefExpr::Create(
  5000. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  5001. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
  5002. nullptr, DRE->isNonOdrUse());
  5003. }
  5004. }
  5005. } else if (isa<MemberExpr>(NakedFn))
  5006. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  5007. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  5008. if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
  5009. FD, /*Complain=*/true, Fn->getBeginLoc()))
  5010. return ExprError();
  5011. if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
  5012. return ExprError();
  5013. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  5014. }
  5015. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  5016. ExecConfig, IsExecConfig);
  5017. }
  5018. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  5019. ///
  5020. /// __builtin_astype( value, dst type )
  5021. ///
  5022. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  5023. SourceLocation BuiltinLoc,
  5024. SourceLocation RParenLoc) {
  5025. ExprValueKind VK = VK_RValue;
  5026. ExprObjectKind OK = OK_Ordinary;
  5027. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  5028. QualType SrcTy = E->getType();
  5029. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  5030. return ExprError(Diag(BuiltinLoc,
  5031. diag::err_invalid_astype_of_different_size)
  5032. << DstTy
  5033. << SrcTy
  5034. << E->getSourceRange());
  5035. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5036. }
  5037. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  5038. /// provided arguments.
  5039. ///
  5040. /// __builtin_convertvector( value, dst type )
  5041. ///
  5042. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  5043. SourceLocation BuiltinLoc,
  5044. SourceLocation RParenLoc) {
  5045. TypeSourceInfo *TInfo;
  5046. GetTypeFromParser(ParsedDestTy, &TInfo);
  5047. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  5048. }
  5049. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  5050. /// i.e. an expression not of \p OverloadTy. The expression should
  5051. /// unary-convert to an expression of function-pointer or
  5052. /// block-pointer type.
  5053. ///
  5054. /// \param NDecl the declaration being called, if available
  5055. ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  5056. SourceLocation LParenLoc,
  5057. ArrayRef<Expr *> Args,
  5058. SourceLocation RParenLoc, Expr *Config,
  5059. bool IsExecConfig, ADLCallKind UsesADL) {
  5060. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  5061. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  5062. // Functions with 'interrupt' attribute cannot be called directly.
  5063. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  5064. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  5065. return ExprError();
  5066. }
  5067. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  5068. // so there's some risk when calling out to non-interrupt handler functions
  5069. // that the callee might not preserve them. This is easy to diagnose here,
  5070. // but can be very challenging to debug.
  5071. if (auto *Caller = getCurFunctionDecl())
  5072. if (Caller->hasAttr<ARMInterruptAttr>()) {
  5073. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  5074. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
  5075. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  5076. }
  5077. // Promote the function operand.
  5078. // We special-case function promotion here because we only allow promoting
  5079. // builtin functions to function pointers in the callee of a call.
  5080. ExprResult Result;
  5081. QualType ResultTy;
  5082. if (BuiltinID &&
  5083. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  5084. // Extract the return type from the (builtin) function pointer type.
  5085. // FIXME Several builtins still have setType in
  5086. // Sema::CheckBuiltinFunctionCall. One should review their definitions in
  5087. // Builtins.def to ensure they are correct before removing setType calls.
  5088. QualType FnPtrTy = Context.getPointerType(FDecl->getType());
  5089. Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
  5090. ResultTy = FDecl->getCallResultType();
  5091. } else {
  5092. Result = CallExprUnaryConversions(Fn);
  5093. ResultTy = Context.BoolTy;
  5094. }
  5095. if (Result.isInvalid())
  5096. return ExprError();
  5097. Fn = Result.get();
  5098. // Check for a valid function type, but only if it is not a builtin which
  5099. // requires custom type checking. These will be handled by
  5100. // CheckBuiltinFunctionCall below just after creation of the call expression.
  5101. const FunctionType *FuncT = nullptr;
  5102. if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
  5103. retry:
  5104. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  5105. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  5106. // have type pointer to function".
  5107. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  5108. if (!FuncT)
  5109. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5110. << Fn->getType() << Fn->getSourceRange());
  5111. } else if (const BlockPointerType *BPT =
  5112. Fn->getType()->getAs<BlockPointerType>()) {
  5113. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  5114. } else {
  5115. // Handle calls to expressions of unknown-any type.
  5116. if (Fn->getType() == Context.UnknownAnyTy) {
  5117. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  5118. if (rewrite.isInvalid())
  5119. return ExprError();
  5120. Fn = rewrite.get();
  5121. goto retry;
  5122. }
  5123. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5124. << Fn->getType() << Fn->getSourceRange());
  5125. }
  5126. }
  5127. // Get the number of parameters in the function prototype, if any.
  5128. // We will allocate space for max(Args.size(), NumParams) arguments
  5129. // in the call expression.
  5130. const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
  5131. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  5132. CallExpr *TheCall;
  5133. if (Config) {
  5134. assert(UsesADL == ADLCallKind::NotADL &&
  5135. "CUDAKernelCallExpr should not use ADL");
  5136. TheCall =
  5137. CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
  5138. ResultTy, VK_RValue, RParenLoc, NumParams);
  5139. } else {
  5140. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5141. RParenLoc, NumParams, UsesADL);
  5142. }
  5143. if (!getLangOpts().CPlusPlus) {
  5144. // Forget about the nulled arguments since typo correction
  5145. // do not handle them well.
  5146. TheCall->shrinkNumArgs(Args.size());
  5147. // C cannot always handle TypoExpr nodes in builtin calls and direct
  5148. // function calls as their argument checking don't necessarily handle
  5149. // dependent types properly, so make sure any TypoExprs have been
  5150. // dealt with.
  5151. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  5152. if (!Result.isUsable()) return ExprError();
  5153. CallExpr *TheOldCall = TheCall;
  5154. TheCall = dyn_cast<CallExpr>(Result.get());
  5155. bool CorrectedTypos = TheCall != TheOldCall;
  5156. if (!TheCall) return Result;
  5157. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  5158. // A new call expression node was created if some typos were corrected.
  5159. // However it may not have been constructed with enough storage. In this
  5160. // case, rebuild the node with enough storage. The waste of space is
  5161. // immaterial since this only happens when some typos were corrected.
  5162. if (CorrectedTypos && Args.size() < NumParams) {
  5163. if (Config)
  5164. TheCall = CUDAKernelCallExpr::Create(
  5165. Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
  5166. RParenLoc, NumParams);
  5167. else
  5168. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5169. RParenLoc, NumParams, UsesADL);
  5170. }
  5171. // We can now handle the nulled arguments for the default arguments.
  5172. TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
  5173. }
  5174. // Bail out early if calling a builtin with custom type checking.
  5175. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  5176. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5177. if (getLangOpts().CUDA) {
  5178. if (Config) {
  5179. // CUDA: Kernel calls must be to global functions
  5180. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  5181. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  5182. << FDecl << Fn->getSourceRange());
  5183. // CUDA: Kernel function must have 'void' return type
  5184. if (!FuncT->getReturnType()->isVoidType())
  5185. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  5186. << Fn->getType() << Fn->getSourceRange());
  5187. } else {
  5188. // CUDA: Calls to global functions must be configured
  5189. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  5190. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  5191. << FDecl << Fn->getSourceRange());
  5192. }
  5193. }
  5194. // Check for a valid return type
  5195. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
  5196. FDecl))
  5197. return ExprError();
  5198. // We know the result type of the call, set it.
  5199. TheCall->setType(FuncT->getCallResultType(Context));
  5200. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  5201. if (Proto) {
  5202. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  5203. IsExecConfig))
  5204. return ExprError();
  5205. } else {
  5206. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  5207. if (FDecl) {
  5208. // Check if we have too few/too many template arguments, based
  5209. // on our knowledge of the function definition.
  5210. const FunctionDecl *Def = nullptr;
  5211. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  5212. Proto = Def->getType()->getAs<FunctionProtoType>();
  5213. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  5214. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  5215. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  5216. }
  5217. // If the function we're calling isn't a function prototype, but we have
  5218. // a function prototype from a prior declaratiom, use that prototype.
  5219. if (!FDecl->hasPrototype())
  5220. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  5221. }
  5222. // Promote the arguments (C99 6.5.2.2p6).
  5223. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  5224. Expr *Arg = Args[i];
  5225. if (Proto && i < Proto->getNumParams()) {
  5226. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5227. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  5228. ExprResult ArgE =
  5229. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5230. if (ArgE.isInvalid())
  5231. return true;
  5232. Arg = ArgE.getAs<Expr>();
  5233. } else {
  5234. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  5235. if (ArgE.isInvalid())
  5236. return true;
  5237. Arg = ArgE.getAs<Expr>();
  5238. }
  5239. if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
  5240. diag::err_call_incomplete_argument, Arg))
  5241. return ExprError();
  5242. TheCall->setArg(i, Arg);
  5243. }
  5244. }
  5245. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  5246. if (!Method->isStatic())
  5247. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  5248. << Fn->getSourceRange());
  5249. // Check for sentinels
  5250. if (NDecl)
  5251. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  5252. // Do special checking on direct calls to functions.
  5253. if (FDecl) {
  5254. if (CheckFunctionCall(FDecl, TheCall, Proto))
  5255. return ExprError();
  5256. checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
  5257. if (BuiltinID)
  5258. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5259. } else if (NDecl) {
  5260. if (CheckPointerCall(NDecl, TheCall, Proto))
  5261. return ExprError();
  5262. } else {
  5263. if (CheckOtherCall(TheCall, Proto))
  5264. return ExprError();
  5265. }
  5266. return MaybeBindToTemporary(TheCall);
  5267. }
  5268. ExprResult
  5269. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  5270. SourceLocation RParenLoc, Expr *InitExpr) {
  5271. assert(Ty && "ActOnCompoundLiteral(): missing type");
  5272. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  5273. TypeSourceInfo *TInfo;
  5274. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  5275. if (!TInfo)
  5276. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  5277. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  5278. }
  5279. ExprResult
  5280. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  5281. SourceLocation RParenLoc, Expr *LiteralExpr) {
  5282. QualType literalType = TInfo->getType();
  5283. if (literalType->isArrayType()) {
  5284. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  5285. diag::err_illegal_decl_array_incomplete_type,
  5286. SourceRange(LParenLoc,
  5287. LiteralExpr->getSourceRange().getEnd())))
  5288. return ExprError();
  5289. if (literalType->isVariableArrayType())
  5290. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  5291. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  5292. } else if (!literalType->isDependentType() &&
  5293. RequireCompleteType(LParenLoc, literalType,
  5294. diag::err_typecheck_decl_incomplete_type,
  5295. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  5296. return ExprError();
  5297. InitializedEntity Entity
  5298. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  5299. InitializationKind Kind
  5300. = InitializationKind::CreateCStyleCast(LParenLoc,
  5301. SourceRange(LParenLoc, RParenLoc),
  5302. /*InitList=*/true);
  5303. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  5304. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  5305. &literalType);
  5306. if (Result.isInvalid())
  5307. return ExprError();
  5308. LiteralExpr = Result.get();
  5309. bool isFileScope = !CurContext->isFunctionOrMethod();
  5310. // In C, compound literals are l-values for some reason.
  5311. // For GCC compatibility, in C++, file-scope array compound literals with
  5312. // constant initializers are also l-values, and compound literals are
  5313. // otherwise prvalues.
  5314. //
  5315. // (GCC also treats C++ list-initialized file-scope array prvalues with
  5316. // constant initializers as l-values, but that's non-conforming, so we don't
  5317. // follow it there.)
  5318. //
  5319. // FIXME: It would be better to handle the lvalue cases as materializing and
  5320. // lifetime-extending a temporary object, but our materialized temporaries
  5321. // representation only supports lifetime extension from a variable, not "out
  5322. // of thin air".
  5323. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  5324. // is bound to the result of applying array-to-pointer decay to the compound
  5325. // literal.
  5326. // FIXME: GCC supports compound literals of reference type, which should
  5327. // obviously have a value kind derived from the kind of reference involved.
  5328. ExprValueKind VK =
  5329. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  5330. ? VK_RValue
  5331. : VK_LValue;
  5332. if (isFileScope)
  5333. if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
  5334. for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
  5335. Expr *Init = ILE->getInit(i);
  5336. ILE->setInit(i, ConstantExpr::Create(Context, Init));
  5337. }
  5338. auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  5339. VK, LiteralExpr, isFileScope);
  5340. if (isFileScope) {
  5341. if (!LiteralExpr->isTypeDependent() &&
  5342. !LiteralExpr->isValueDependent() &&
  5343. !literalType->isDependentType()) // C99 6.5.2.5p3
  5344. if (CheckForConstantInitializer(LiteralExpr, literalType))
  5345. return ExprError();
  5346. } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  5347. literalType.getAddressSpace() != LangAS::Default) {
  5348. // Embedded-C extensions to C99 6.5.2.5:
  5349. // "If the compound literal occurs inside the body of a function, the
  5350. // type name shall not be qualified by an address-space qualifier."
  5351. Diag(LParenLoc, diag::err_compound_literal_with_address_space)
  5352. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
  5353. return ExprError();
  5354. }
  5355. // Compound literals that have automatic storage duration are destroyed at
  5356. // the end of the scope. Emit diagnostics if it is or contains a C union type
  5357. // that is non-trivial to destruct.
  5358. if (!isFileScope)
  5359. if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
  5360. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  5361. NTCUC_CompoundLiteral, NTCUK_Destruct);
  5362. if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  5363. E->getType().hasNonTrivialToPrimitiveCopyCUnion())
  5364. checkNonTrivialCUnionInInitializer(E->getInitializer(),
  5365. E->getInitializer()->getExprLoc());
  5366. return MaybeBindToTemporary(E);
  5367. }
  5368. ExprResult
  5369. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5370. SourceLocation RBraceLoc) {
  5371. // Only produce each kind of designated initialization diagnostic once.
  5372. SourceLocation FirstDesignator;
  5373. bool DiagnosedArrayDesignator = false;
  5374. bool DiagnosedNestedDesignator = false;
  5375. bool DiagnosedMixedDesignator = false;
  5376. // Check that any designated initializers are syntactically valid in the
  5377. // current language mode.
  5378. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5379. if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
  5380. if (FirstDesignator.isInvalid())
  5381. FirstDesignator = DIE->getBeginLoc();
  5382. if (!getLangOpts().CPlusPlus)
  5383. break;
  5384. if (!DiagnosedNestedDesignator && DIE->size() > 1) {
  5385. DiagnosedNestedDesignator = true;
  5386. Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
  5387. << DIE->getDesignatorsSourceRange();
  5388. }
  5389. for (auto &Desig : DIE->designators()) {
  5390. if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
  5391. DiagnosedArrayDesignator = true;
  5392. Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
  5393. << Desig.getSourceRange();
  5394. }
  5395. }
  5396. if (!DiagnosedMixedDesignator &&
  5397. !isa<DesignatedInitExpr>(InitArgList[0])) {
  5398. DiagnosedMixedDesignator = true;
  5399. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  5400. << DIE->getSourceRange();
  5401. Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
  5402. << InitArgList[0]->getSourceRange();
  5403. }
  5404. } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
  5405. isa<DesignatedInitExpr>(InitArgList[0])) {
  5406. DiagnosedMixedDesignator = true;
  5407. auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
  5408. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  5409. << DIE->getSourceRange();
  5410. Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
  5411. << InitArgList[I]->getSourceRange();
  5412. }
  5413. }
  5414. if (FirstDesignator.isValid()) {
  5415. // Only diagnose designated initiaization as a C++20 extension if we didn't
  5416. // already diagnose use of (non-C++20) C99 designator syntax.
  5417. if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
  5418. !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
  5419. Diag(FirstDesignator, getLangOpts().CPlusPlus2a
  5420. ? diag::warn_cxx17_compat_designated_init
  5421. : diag::ext_cxx_designated_init);
  5422. } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
  5423. Diag(FirstDesignator, diag::ext_designated_init);
  5424. }
  5425. }
  5426. return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
  5427. }
  5428. ExprResult
  5429. Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5430. SourceLocation RBraceLoc) {
  5431. // Semantic analysis for initializers is done by ActOnDeclarator() and
  5432. // CheckInitializer() - it requires knowledge of the object being initialized.
  5433. // Immediately handle non-overload placeholders. Overloads can be
  5434. // resolved contextually, but everything else here can't.
  5435. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5436. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  5437. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  5438. // Ignore failures; dropping the entire initializer list because
  5439. // of one failure would be terrible for indexing/etc.
  5440. if (result.isInvalid()) continue;
  5441. InitArgList[I] = result.get();
  5442. }
  5443. }
  5444. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  5445. RBraceLoc);
  5446. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  5447. return E;
  5448. }
  5449. /// Do an explicit extend of the given block pointer if we're in ARC.
  5450. void Sema::maybeExtendBlockObject(ExprResult &E) {
  5451. assert(E.get()->getType()->isBlockPointerType());
  5452. assert(E.get()->isRValue());
  5453. // Only do this in an r-value context.
  5454. if (!getLangOpts().ObjCAutoRefCount) return;
  5455. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  5456. CK_ARCExtendBlockObject, E.get(),
  5457. /*base path*/ nullptr, VK_RValue);
  5458. Cleanup.setExprNeedsCleanups(true);
  5459. }
  5460. /// Prepare a conversion of the given expression to an ObjC object
  5461. /// pointer type.
  5462. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  5463. QualType type = E.get()->getType();
  5464. if (type->isObjCObjectPointerType()) {
  5465. return CK_BitCast;
  5466. } else if (type->isBlockPointerType()) {
  5467. maybeExtendBlockObject(E);
  5468. return CK_BlockPointerToObjCPointerCast;
  5469. } else {
  5470. assert(type->isPointerType());
  5471. return CK_CPointerToObjCPointerCast;
  5472. }
  5473. }
  5474. /// Prepares for a scalar cast, performing all the necessary stages
  5475. /// except the final cast and returning the kind required.
  5476. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  5477. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  5478. // Also, callers should have filtered out the invalid cases with
  5479. // pointers. Everything else should be possible.
  5480. QualType SrcTy = Src.get()->getType();
  5481. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  5482. return CK_NoOp;
  5483. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  5484. case Type::STK_MemberPointer:
  5485. llvm_unreachable("member pointer type in C");
  5486. case Type::STK_CPointer:
  5487. case Type::STK_BlockPointer:
  5488. case Type::STK_ObjCObjectPointer:
  5489. switch (DestTy->getScalarTypeKind()) {
  5490. case Type::STK_CPointer: {
  5491. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  5492. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  5493. if (SrcAS != DestAS)
  5494. return CK_AddressSpaceConversion;
  5495. if (Context.hasCvrSimilarType(SrcTy, DestTy))
  5496. return CK_NoOp;
  5497. return CK_BitCast;
  5498. }
  5499. case Type::STK_BlockPointer:
  5500. return (SrcKind == Type::STK_BlockPointer
  5501. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  5502. case Type::STK_ObjCObjectPointer:
  5503. if (SrcKind == Type::STK_ObjCObjectPointer)
  5504. return CK_BitCast;
  5505. if (SrcKind == Type::STK_CPointer)
  5506. return CK_CPointerToObjCPointerCast;
  5507. maybeExtendBlockObject(Src);
  5508. return CK_BlockPointerToObjCPointerCast;
  5509. case Type::STK_Bool:
  5510. return CK_PointerToBoolean;
  5511. case Type::STK_Integral:
  5512. return CK_PointerToIntegral;
  5513. case Type::STK_Floating:
  5514. case Type::STK_FloatingComplex:
  5515. case Type::STK_IntegralComplex:
  5516. case Type::STK_MemberPointer:
  5517. case Type::STK_FixedPoint:
  5518. llvm_unreachable("illegal cast from pointer");
  5519. }
  5520. llvm_unreachable("Should have returned before this");
  5521. case Type::STK_FixedPoint:
  5522. switch (DestTy->getScalarTypeKind()) {
  5523. case Type::STK_FixedPoint:
  5524. return CK_FixedPointCast;
  5525. case Type::STK_Bool:
  5526. return CK_FixedPointToBoolean;
  5527. case Type::STK_Integral:
  5528. return CK_FixedPointToIntegral;
  5529. case Type::STK_Floating:
  5530. case Type::STK_IntegralComplex:
  5531. case Type::STK_FloatingComplex:
  5532. Diag(Src.get()->getExprLoc(),
  5533. diag::err_unimplemented_conversion_with_fixed_point_type)
  5534. << DestTy;
  5535. return CK_IntegralCast;
  5536. case Type::STK_CPointer:
  5537. case Type::STK_ObjCObjectPointer:
  5538. case Type::STK_BlockPointer:
  5539. case Type::STK_MemberPointer:
  5540. llvm_unreachable("illegal cast to pointer type");
  5541. }
  5542. llvm_unreachable("Should have returned before this");
  5543. case Type::STK_Bool: // casting from bool is like casting from an integer
  5544. case Type::STK_Integral:
  5545. switch (DestTy->getScalarTypeKind()) {
  5546. case Type::STK_CPointer:
  5547. case Type::STK_ObjCObjectPointer:
  5548. case Type::STK_BlockPointer:
  5549. if (Src.get()->isNullPointerConstant(Context,
  5550. Expr::NPC_ValueDependentIsNull))
  5551. return CK_NullToPointer;
  5552. return CK_IntegralToPointer;
  5553. case Type::STK_Bool:
  5554. return CK_IntegralToBoolean;
  5555. case Type::STK_Integral:
  5556. return CK_IntegralCast;
  5557. case Type::STK_Floating:
  5558. return CK_IntegralToFloating;
  5559. case Type::STK_IntegralComplex:
  5560. Src = ImpCastExprToType(Src.get(),
  5561. DestTy->castAs<ComplexType>()->getElementType(),
  5562. CK_IntegralCast);
  5563. return CK_IntegralRealToComplex;
  5564. case Type::STK_FloatingComplex:
  5565. Src = ImpCastExprToType(Src.get(),
  5566. DestTy->castAs<ComplexType>()->getElementType(),
  5567. CK_IntegralToFloating);
  5568. return CK_FloatingRealToComplex;
  5569. case Type::STK_MemberPointer:
  5570. llvm_unreachable("member pointer type in C");
  5571. case Type::STK_FixedPoint:
  5572. return CK_IntegralToFixedPoint;
  5573. }
  5574. llvm_unreachable("Should have returned before this");
  5575. case Type::STK_Floating:
  5576. switch (DestTy->getScalarTypeKind()) {
  5577. case Type::STK_Floating:
  5578. return CK_FloatingCast;
  5579. case Type::STK_Bool:
  5580. return CK_FloatingToBoolean;
  5581. case Type::STK_Integral:
  5582. return CK_FloatingToIntegral;
  5583. case Type::STK_FloatingComplex:
  5584. Src = ImpCastExprToType(Src.get(),
  5585. DestTy->castAs<ComplexType>()->getElementType(),
  5586. CK_FloatingCast);
  5587. return CK_FloatingRealToComplex;
  5588. case Type::STK_IntegralComplex:
  5589. Src = ImpCastExprToType(Src.get(),
  5590. DestTy->castAs<ComplexType>()->getElementType(),
  5591. CK_FloatingToIntegral);
  5592. return CK_IntegralRealToComplex;
  5593. case Type::STK_CPointer:
  5594. case Type::STK_ObjCObjectPointer:
  5595. case Type::STK_BlockPointer:
  5596. llvm_unreachable("valid float->pointer cast?");
  5597. case Type::STK_MemberPointer:
  5598. llvm_unreachable("member pointer type in C");
  5599. case Type::STK_FixedPoint:
  5600. Diag(Src.get()->getExprLoc(),
  5601. diag::err_unimplemented_conversion_with_fixed_point_type)
  5602. << SrcTy;
  5603. return CK_IntegralCast;
  5604. }
  5605. llvm_unreachable("Should have returned before this");
  5606. case Type::STK_FloatingComplex:
  5607. switch (DestTy->getScalarTypeKind()) {
  5608. case Type::STK_FloatingComplex:
  5609. return CK_FloatingComplexCast;
  5610. case Type::STK_IntegralComplex:
  5611. return CK_FloatingComplexToIntegralComplex;
  5612. case Type::STK_Floating: {
  5613. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5614. if (Context.hasSameType(ET, DestTy))
  5615. return CK_FloatingComplexToReal;
  5616. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  5617. return CK_FloatingCast;
  5618. }
  5619. case Type::STK_Bool:
  5620. return CK_FloatingComplexToBoolean;
  5621. case Type::STK_Integral:
  5622. Src = ImpCastExprToType(Src.get(),
  5623. SrcTy->castAs<ComplexType>()->getElementType(),
  5624. CK_FloatingComplexToReal);
  5625. return CK_FloatingToIntegral;
  5626. case Type::STK_CPointer:
  5627. case Type::STK_ObjCObjectPointer:
  5628. case Type::STK_BlockPointer:
  5629. llvm_unreachable("valid complex float->pointer cast?");
  5630. case Type::STK_MemberPointer:
  5631. llvm_unreachable("member pointer type in C");
  5632. case Type::STK_FixedPoint:
  5633. Diag(Src.get()->getExprLoc(),
  5634. diag::err_unimplemented_conversion_with_fixed_point_type)
  5635. << SrcTy;
  5636. return CK_IntegralCast;
  5637. }
  5638. llvm_unreachable("Should have returned before this");
  5639. case Type::STK_IntegralComplex:
  5640. switch (DestTy->getScalarTypeKind()) {
  5641. case Type::STK_FloatingComplex:
  5642. return CK_IntegralComplexToFloatingComplex;
  5643. case Type::STK_IntegralComplex:
  5644. return CK_IntegralComplexCast;
  5645. case Type::STK_Integral: {
  5646. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5647. if (Context.hasSameType(ET, DestTy))
  5648. return CK_IntegralComplexToReal;
  5649. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  5650. return CK_IntegralCast;
  5651. }
  5652. case Type::STK_Bool:
  5653. return CK_IntegralComplexToBoolean;
  5654. case Type::STK_Floating:
  5655. Src = ImpCastExprToType(Src.get(),
  5656. SrcTy->castAs<ComplexType>()->getElementType(),
  5657. CK_IntegralComplexToReal);
  5658. return CK_IntegralToFloating;
  5659. case Type::STK_CPointer:
  5660. case Type::STK_ObjCObjectPointer:
  5661. case Type::STK_BlockPointer:
  5662. llvm_unreachable("valid complex int->pointer cast?");
  5663. case Type::STK_MemberPointer:
  5664. llvm_unreachable("member pointer type in C");
  5665. case Type::STK_FixedPoint:
  5666. Diag(Src.get()->getExprLoc(),
  5667. diag::err_unimplemented_conversion_with_fixed_point_type)
  5668. << SrcTy;
  5669. return CK_IntegralCast;
  5670. }
  5671. llvm_unreachable("Should have returned before this");
  5672. }
  5673. llvm_unreachable("Unhandled scalar cast");
  5674. }
  5675. static bool breakDownVectorType(QualType type, uint64_t &len,
  5676. QualType &eltType) {
  5677. // Vectors are simple.
  5678. if (const VectorType *vecType = type->getAs<VectorType>()) {
  5679. len = vecType->getNumElements();
  5680. eltType = vecType->getElementType();
  5681. assert(eltType->isScalarType());
  5682. return true;
  5683. }
  5684. // We allow lax conversion to and from non-vector types, but only if
  5685. // they're real types (i.e. non-complex, non-pointer scalar types).
  5686. if (!type->isRealType()) return false;
  5687. len = 1;
  5688. eltType = type;
  5689. return true;
  5690. }
  5691. /// Are the two types lax-compatible vector types? That is, given
  5692. /// that one of them is a vector, do they have equal storage sizes,
  5693. /// where the storage size is the number of elements times the element
  5694. /// size?
  5695. ///
  5696. /// This will also return false if either of the types is neither a
  5697. /// vector nor a real type.
  5698. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  5699. assert(destTy->isVectorType() || srcTy->isVectorType());
  5700. // Disallow lax conversions between scalars and ExtVectors (these
  5701. // conversions are allowed for other vector types because common headers
  5702. // depend on them). Most scalar OP ExtVector cases are handled by the
  5703. // splat path anyway, which does what we want (convert, not bitcast).
  5704. // What this rules out for ExtVectors is crazy things like char4*float.
  5705. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  5706. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  5707. uint64_t srcLen, destLen;
  5708. QualType srcEltTy, destEltTy;
  5709. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  5710. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  5711. // ASTContext::getTypeSize will return the size rounded up to a
  5712. // power of 2, so instead of using that, we need to use the raw
  5713. // element size multiplied by the element count.
  5714. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  5715. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  5716. return (srcLen * srcEltSize == destLen * destEltSize);
  5717. }
  5718. /// Is this a legal conversion between two types, one of which is
  5719. /// known to be a vector type?
  5720. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  5721. assert(destTy->isVectorType() || srcTy->isVectorType());
  5722. switch (Context.getLangOpts().getLaxVectorConversions()) {
  5723. case LangOptions::LaxVectorConversionKind::None:
  5724. return false;
  5725. case LangOptions::LaxVectorConversionKind::Integer:
  5726. if (!srcTy->isIntegralOrEnumerationType()) {
  5727. auto *Vec = srcTy->getAs<VectorType>();
  5728. if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
  5729. return false;
  5730. }
  5731. if (!destTy->isIntegralOrEnumerationType()) {
  5732. auto *Vec = destTy->getAs<VectorType>();
  5733. if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
  5734. return false;
  5735. }
  5736. // OK, integer (vector) -> integer (vector) bitcast.
  5737. break;
  5738. case LangOptions::LaxVectorConversionKind::All:
  5739. break;
  5740. }
  5741. return areLaxCompatibleVectorTypes(srcTy, destTy);
  5742. }
  5743. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  5744. CastKind &Kind) {
  5745. assert(VectorTy->isVectorType() && "Not a vector type!");
  5746. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  5747. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  5748. return Diag(R.getBegin(),
  5749. Ty->isVectorType() ?
  5750. diag::err_invalid_conversion_between_vectors :
  5751. diag::err_invalid_conversion_between_vector_and_integer)
  5752. << VectorTy << Ty << R;
  5753. } else
  5754. return Diag(R.getBegin(),
  5755. diag::err_invalid_conversion_between_vector_and_scalar)
  5756. << VectorTy << Ty << R;
  5757. Kind = CK_BitCast;
  5758. return false;
  5759. }
  5760. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  5761. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  5762. if (DestElemTy == SplattedExpr->getType())
  5763. return SplattedExpr;
  5764. assert(DestElemTy->isFloatingType() ||
  5765. DestElemTy->isIntegralOrEnumerationType());
  5766. CastKind CK;
  5767. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  5768. // OpenCL requires that we convert `true` boolean expressions to -1, but
  5769. // only when splatting vectors.
  5770. if (DestElemTy->isFloatingType()) {
  5771. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  5772. // in two steps: boolean to signed integral, then to floating.
  5773. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  5774. CK_BooleanToSignedIntegral);
  5775. SplattedExpr = CastExprRes.get();
  5776. CK = CK_IntegralToFloating;
  5777. } else {
  5778. CK = CK_BooleanToSignedIntegral;
  5779. }
  5780. } else {
  5781. ExprResult CastExprRes = SplattedExpr;
  5782. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  5783. if (CastExprRes.isInvalid())
  5784. return ExprError();
  5785. SplattedExpr = CastExprRes.get();
  5786. }
  5787. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  5788. }
  5789. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  5790. Expr *CastExpr, CastKind &Kind) {
  5791. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  5792. QualType SrcTy = CastExpr->getType();
  5793. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  5794. // an ExtVectorType.
  5795. // In OpenCL, casts between vectors of different types are not allowed.
  5796. // (See OpenCL 6.2).
  5797. if (SrcTy->isVectorType()) {
  5798. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  5799. (getLangOpts().OpenCL &&
  5800. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  5801. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  5802. << DestTy << SrcTy << R;
  5803. return ExprError();
  5804. }
  5805. Kind = CK_BitCast;
  5806. return CastExpr;
  5807. }
  5808. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  5809. // conversion will take place first from scalar to elt type, and then
  5810. // splat from elt type to vector.
  5811. if (SrcTy->isPointerType())
  5812. return Diag(R.getBegin(),
  5813. diag::err_invalid_conversion_between_vector_and_scalar)
  5814. << DestTy << SrcTy << R;
  5815. Kind = CK_VectorSplat;
  5816. return prepareVectorSplat(DestTy, CastExpr);
  5817. }
  5818. ExprResult
  5819. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  5820. Declarator &D, ParsedType &Ty,
  5821. SourceLocation RParenLoc, Expr *CastExpr) {
  5822. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  5823. "ActOnCastExpr(): missing type or expr");
  5824. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  5825. if (D.isInvalidType())
  5826. return ExprError();
  5827. if (getLangOpts().CPlusPlus) {
  5828. // Check that there are no default arguments (C++ only).
  5829. CheckExtraCXXDefaultArguments(D);
  5830. } else {
  5831. // Make sure any TypoExprs have been dealt with.
  5832. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  5833. if (!Res.isUsable())
  5834. return ExprError();
  5835. CastExpr = Res.get();
  5836. }
  5837. checkUnusedDeclAttributes(D);
  5838. QualType castType = castTInfo->getType();
  5839. Ty = CreateParsedType(castType, castTInfo);
  5840. bool isVectorLiteral = false;
  5841. // Check for an altivec or OpenCL literal,
  5842. // i.e. all the elements are integer constants.
  5843. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5844. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5845. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5846. && castType->isVectorType() && (PE || PLE)) {
  5847. if (PLE && PLE->getNumExprs() == 0) {
  5848. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5849. return ExprError();
  5850. }
  5851. if (PE || PLE->getNumExprs() == 1) {
  5852. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5853. if (!E->getType()->isVectorType())
  5854. isVectorLiteral = true;
  5855. }
  5856. else
  5857. isVectorLiteral = true;
  5858. }
  5859. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5860. // then handle it as such.
  5861. if (isVectorLiteral)
  5862. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5863. // If the Expr being casted is a ParenListExpr, handle it specially.
  5864. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5865. // sequence of BinOp comma operators.
  5866. if (isa<ParenListExpr>(CastExpr)) {
  5867. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5868. if (Result.isInvalid()) return ExprError();
  5869. CastExpr = Result.get();
  5870. }
  5871. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5872. !getSourceManager().isInSystemMacro(LParenLoc))
  5873. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5874. CheckTollFreeBridgeCast(castType, CastExpr);
  5875. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5876. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  5877. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5878. }
  5879. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5880. SourceLocation RParenLoc, Expr *E,
  5881. TypeSourceInfo *TInfo) {
  5882. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5883. "Expected paren or paren list expression");
  5884. Expr **exprs;
  5885. unsigned numExprs;
  5886. Expr *subExpr;
  5887. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5888. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5889. LiteralLParenLoc = PE->getLParenLoc();
  5890. LiteralRParenLoc = PE->getRParenLoc();
  5891. exprs = PE->getExprs();
  5892. numExprs = PE->getNumExprs();
  5893. } else { // isa<ParenExpr> by assertion at function entrance
  5894. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5895. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5896. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5897. exprs = &subExpr;
  5898. numExprs = 1;
  5899. }
  5900. QualType Ty = TInfo->getType();
  5901. assert(Ty->isVectorType() && "Expected vector type");
  5902. SmallVector<Expr *, 8> initExprs;
  5903. const VectorType *VTy = Ty->getAs<VectorType>();
  5904. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5905. // '(...)' form of vector initialization in AltiVec: the number of
  5906. // initializers must be one or must match the size of the vector.
  5907. // If a single value is specified in the initializer then it will be
  5908. // replicated to all the components of the vector
  5909. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5910. // The number of initializers must be one or must match the size of the
  5911. // vector. If a single value is specified in the initializer then it will
  5912. // be replicated to all the components of the vector
  5913. if (numExprs == 1) {
  5914. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5915. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5916. if (Literal.isInvalid())
  5917. return ExprError();
  5918. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5919. PrepareScalarCast(Literal, ElemTy));
  5920. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5921. }
  5922. else if (numExprs < numElems) {
  5923. Diag(E->getExprLoc(),
  5924. diag::err_incorrect_number_of_vector_initializers);
  5925. return ExprError();
  5926. }
  5927. else
  5928. initExprs.append(exprs, exprs + numExprs);
  5929. }
  5930. else {
  5931. // For OpenCL, when the number of initializers is a single value,
  5932. // it will be replicated to all components of the vector.
  5933. if (getLangOpts().OpenCL &&
  5934. VTy->getVectorKind() == VectorType::GenericVector &&
  5935. numExprs == 1) {
  5936. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5937. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5938. if (Literal.isInvalid())
  5939. return ExprError();
  5940. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5941. PrepareScalarCast(Literal, ElemTy));
  5942. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5943. }
  5944. initExprs.append(exprs, exprs + numExprs);
  5945. }
  5946. // FIXME: This means that pretty-printing the final AST will produce curly
  5947. // braces instead of the original commas.
  5948. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5949. initExprs, LiteralRParenLoc);
  5950. initE->setType(Ty);
  5951. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5952. }
  5953. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5954. /// the ParenListExpr into a sequence of comma binary operators.
  5955. ExprResult
  5956. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5957. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5958. if (!E)
  5959. return OrigExpr;
  5960. ExprResult Result(E->getExpr(0));
  5961. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5962. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5963. E->getExpr(i));
  5964. if (Result.isInvalid()) return ExprError();
  5965. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5966. }
  5967. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5968. SourceLocation R,
  5969. MultiExprArg Val) {
  5970. return ParenListExpr::Create(Context, L, Val, R);
  5971. }
  5972. /// Emit a specialized diagnostic when one expression is a null pointer
  5973. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5974. /// emitted.
  5975. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5976. SourceLocation QuestionLoc) {
  5977. Expr *NullExpr = LHSExpr;
  5978. Expr *NonPointerExpr = RHSExpr;
  5979. Expr::NullPointerConstantKind NullKind =
  5980. NullExpr->isNullPointerConstant(Context,
  5981. Expr::NPC_ValueDependentIsNotNull);
  5982. if (NullKind == Expr::NPCK_NotNull) {
  5983. NullExpr = RHSExpr;
  5984. NonPointerExpr = LHSExpr;
  5985. NullKind =
  5986. NullExpr->isNullPointerConstant(Context,
  5987. Expr::NPC_ValueDependentIsNotNull);
  5988. }
  5989. if (NullKind == Expr::NPCK_NotNull)
  5990. return false;
  5991. if (NullKind == Expr::NPCK_ZeroExpression)
  5992. return false;
  5993. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5994. // In this case, check to make sure that we got here from a "NULL"
  5995. // string in the source code.
  5996. NullExpr = NullExpr->IgnoreParenImpCasts();
  5997. SourceLocation loc = NullExpr->getExprLoc();
  5998. if (!findMacroSpelling(loc, "NULL"))
  5999. return false;
  6000. }
  6001. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  6002. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  6003. << NonPointerExpr->getType() << DiagType
  6004. << NonPointerExpr->getSourceRange();
  6005. return true;
  6006. }
  6007. /// Return false if the condition expression is valid, true otherwise.
  6008. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  6009. QualType CondTy = Cond->getType();
  6010. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  6011. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  6012. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  6013. << CondTy << Cond->getSourceRange();
  6014. return true;
  6015. }
  6016. // C99 6.5.15p2
  6017. if (CondTy->isScalarType()) return false;
  6018. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  6019. << CondTy << Cond->getSourceRange();
  6020. return true;
  6021. }
  6022. /// Handle when one or both operands are void type.
  6023. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  6024. ExprResult &RHS) {
  6025. Expr *LHSExpr = LHS.get();
  6026. Expr *RHSExpr = RHS.get();
  6027. if (!LHSExpr->getType()->isVoidType())
  6028. S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  6029. << RHSExpr->getSourceRange();
  6030. if (!RHSExpr->getType()->isVoidType())
  6031. S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  6032. << LHSExpr->getSourceRange();
  6033. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  6034. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  6035. return S.Context.VoidTy;
  6036. }
  6037. /// Return false if the NullExpr can be promoted to PointerTy,
  6038. /// true otherwise.
  6039. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  6040. QualType PointerTy) {
  6041. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  6042. !NullExpr.get()->isNullPointerConstant(S.Context,
  6043. Expr::NPC_ValueDependentIsNull))
  6044. return true;
  6045. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  6046. return false;
  6047. }
  6048. /// Checks compatibility between two pointers and return the resulting
  6049. /// type.
  6050. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  6051. ExprResult &RHS,
  6052. SourceLocation Loc) {
  6053. QualType LHSTy = LHS.get()->getType();
  6054. QualType RHSTy = RHS.get()->getType();
  6055. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  6056. // Two identical pointers types are always compatible.
  6057. return LHSTy;
  6058. }
  6059. QualType lhptee, rhptee;
  6060. // Get the pointee types.
  6061. bool IsBlockPointer = false;
  6062. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  6063. lhptee = LHSBTy->getPointeeType();
  6064. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  6065. IsBlockPointer = true;
  6066. } else {
  6067. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  6068. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  6069. }
  6070. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  6071. // differently qualified versions of compatible types, the result type is
  6072. // a pointer to an appropriately qualified version of the composite
  6073. // type.
  6074. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  6075. // clause doesn't make sense for our extensions. E.g. address space 2 should
  6076. // be incompatible with address space 3: they may live on different devices or
  6077. // anything.
  6078. Qualifiers lhQual = lhptee.getQualifiers();
  6079. Qualifiers rhQual = rhptee.getQualifiers();
  6080. LangAS ResultAddrSpace = LangAS::Default;
  6081. LangAS LAddrSpace = lhQual.getAddressSpace();
  6082. LangAS RAddrSpace = rhQual.getAddressSpace();
  6083. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  6084. // spaces is disallowed.
  6085. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  6086. ResultAddrSpace = LAddrSpace;
  6087. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  6088. ResultAddrSpace = RAddrSpace;
  6089. else {
  6090. S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6091. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  6092. << RHS.get()->getSourceRange();
  6093. return QualType();
  6094. }
  6095. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  6096. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  6097. lhQual.removeCVRQualifiers();
  6098. rhQual.removeCVRQualifiers();
  6099. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  6100. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  6101. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  6102. // qual types are compatible iff
  6103. // * corresponded types are compatible
  6104. // * CVR qualifiers are equal
  6105. // * address spaces are equal
  6106. // Thus for conditional operator we merge CVR and address space unqualified
  6107. // pointees and if there is a composite type we return a pointer to it with
  6108. // merged qualifiers.
  6109. LHSCastKind =
  6110. LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  6111. RHSCastKind =
  6112. RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  6113. lhQual.removeAddressSpace();
  6114. rhQual.removeAddressSpace();
  6115. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  6116. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  6117. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  6118. if (CompositeTy.isNull()) {
  6119. // In this situation, we assume void* type. No especially good
  6120. // reason, but this is what gcc does, and we do have to pick
  6121. // to get a consistent AST.
  6122. QualType incompatTy;
  6123. incompatTy = S.Context.getPointerType(
  6124. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  6125. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  6126. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  6127. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  6128. // for casts between types with incompatible address space qualifiers.
  6129. // For the following code the compiler produces casts between global and
  6130. // local address spaces of the corresponded innermost pointees:
  6131. // local int *global *a;
  6132. // global int *global *b;
  6133. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  6134. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  6135. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6136. << RHS.get()->getSourceRange();
  6137. return incompatTy;
  6138. }
  6139. // The pointer types are compatible.
  6140. // In case of OpenCL ResultTy should have the address space qualifier
  6141. // which is a superset of address spaces of both the 2nd and the 3rd
  6142. // operands of the conditional operator.
  6143. QualType ResultTy = [&, ResultAddrSpace]() {
  6144. if (S.getLangOpts().OpenCL) {
  6145. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  6146. CompositeQuals.setAddressSpace(ResultAddrSpace);
  6147. return S.Context
  6148. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  6149. .withCVRQualifiers(MergedCVRQual);
  6150. }
  6151. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  6152. }();
  6153. if (IsBlockPointer)
  6154. ResultTy = S.Context.getBlockPointerType(ResultTy);
  6155. else
  6156. ResultTy = S.Context.getPointerType(ResultTy);
  6157. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  6158. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  6159. return ResultTy;
  6160. }
  6161. /// Return the resulting type when the operands are both block pointers.
  6162. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  6163. ExprResult &LHS,
  6164. ExprResult &RHS,
  6165. SourceLocation Loc) {
  6166. QualType LHSTy = LHS.get()->getType();
  6167. QualType RHSTy = RHS.get()->getType();
  6168. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  6169. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  6170. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  6171. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6172. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6173. return destType;
  6174. }
  6175. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  6176. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6177. << RHS.get()->getSourceRange();
  6178. return QualType();
  6179. }
  6180. // We have 2 block pointer types.
  6181. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6182. }
  6183. /// Return the resulting type when the operands are both pointers.
  6184. static QualType
  6185. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  6186. ExprResult &RHS,
  6187. SourceLocation Loc) {
  6188. // get the pointer types
  6189. QualType LHSTy = LHS.get()->getType();
  6190. QualType RHSTy = RHS.get()->getType();
  6191. // get the "pointed to" types
  6192. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6193. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6194. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  6195. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  6196. // Figure out necessary qualifiers (C99 6.5.15p6)
  6197. QualType destPointee
  6198. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6199. QualType destType = S.Context.getPointerType(destPointee);
  6200. // Add qualifiers if necessary.
  6201. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6202. // Promote to void*.
  6203. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6204. return destType;
  6205. }
  6206. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  6207. QualType destPointee
  6208. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6209. QualType destType = S.Context.getPointerType(destPointee);
  6210. // Add qualifiers if necessary.
  6211. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6212. // Promote to void*.
  6213. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6214. return destType;
  6215. }
  6216. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6217. }
  6218. /// Return false if the first expression is not an integer and the second
  6219. /// expression is not a pointer, true otherwise.
  6220. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  6221. Expr* PointerExpr, SourceLocation Loc,
  6222. bool IsIntFirstExpr) {
  6223. if (!PointerExpr->getType()->isPointerType() ||
  6224. !Int.get()->getType()->isIntegerType())
  6225. return false;
  6226. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  6227. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  6228. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  6229. << Expr1->getType() << Expr2->getType()
  6230. << Expr1->getSourceRange() << Expr2->getSourceRange();
  6231. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  6232. CK_IntegralToPointer);
  6233. return true;
  6234. }
  6235. /// Simple conversion between integer and floating point types.
  6236. ///
  6237. /// Used when handling the OpenCL conditional operator where the
  6238. /// condition is a vector while the other operands are scalar.
  6239. ///
  6240. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  6241. /// types are either integer or floating type. Between the two
  6242. /// operands, the type with the higher rank is defined as the "result
  6243. /// type". The other operand needs to be promoted to the same type. No
  6244. /// other type promotion is allowed. We cannot use
  6245. /// UsualArithmeticConversions() for this purpose, since it always
  6246. /// promotes promotable types.
  6247. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  6248. ExprResult &RHS,
  6249. SourceLocation QuestionLoc) {
  6250. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  6251. if (LHS.isInvalid())
  6252. return QualType();
  6253. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  6254. if (RHS.isInvalid())
  6255. return QualType();
  6256. // For conversion purposes, we ignore any qualifiers.
  6257. // For example, "const float" and "float" are equivalent.
  6258. QualType LHSType =
  6259. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  6260. QualType RHSType =
  6261. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  6262. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  6263. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6264. << LHSType << LHS.get()->getSourceRange();
  6265. return QualType();
  6266. }
  6267. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  6268. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6269. << RHSType << RHS.get()->getSourceRange();
  6270. return QualType();
  6271. }
  6272. // If both types are identical, no conversion is needed.
  6273. if (LHSType == RHSType)
  6274. return LHSType;
  6275. // Now handle "real" floating types (i.e. float, double, long double).
  6276. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  6277. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  6278. /*IsCompAssign = */ false);
  6279. // Finally, we have two differing integer types.
  6280. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  6281. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  6282. }
  6283. /// Convert scalar operands to a vector that matches the
  6284. /// condition in length.
  6285. ///
  6286. /// Used when handling the OpenCL conditional operator where the
  6287. /// condition is a vector while the other operands are scalar.
  6288. ///
  6289. /// We first compute the "result type" for the scalar operands
  6290. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  6291. /// into a vector of that type where the length matches the condition
  6292. /// vector type. s6.11.6 requires that the element types of the result
  6293. /// and the condition must have the same number of bits.
  6294. static QualType
  6295. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6296. QualType CondTy, SourceLocation QuestionLoc) {
  6297. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  6298. if (ResTy.isNull()) return QualType();
  6299. const VectorType *CV = CondTy->getAs<VectorType>();
  6300. assert(CV);
  6301. // Determine the vector result type
  6302. unsigned NumElements = CV->getNumElements();
  6303. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  6304. // Ensure that all types have the same number of bits
  6305. if (S.Context.getTypeSize(CV->getElementType())
  6306. != S.Context.getTypeSize(ResTy)) {
  6307. // Since VectorTy is created internally, it does not pretty print
  6308. // with an OpenCL name. Instead, we just print a description.
  6309. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  6310. SmallString<64> Str;
  6311. llvm::raw_svector_ostream OS(Str);
  6312. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  6313. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6314. << CondTy << OS.str();
  6315. return QualType();
  6316. }
  6317. // Convert operands to the vector result type
  6318. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  6319. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  6320. return VectorTy;
  6321. }
  6322. /// Return false if this is a valid OpenCL condition vector
  6323. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  6324. SourceLocation QuestionLoc) {
  6325. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  6326. // integral type.
  6327. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  6328. assert(CondTy);
  6329. QualType EleTy = CondTy->getElementType();
  6330. if (EleTy->isIntegerType()) return false;
  6331. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  6332. << Cond->getType() << Cond->getSourceRange();
  6333. return true;
  6334. }
  6335. /// Return false if the vector condition type and the vector
  6336. /// result type are compatible.
  6337. ///
  6338. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  6339. /// number of elements, and their element types have the same number
  6340. /// of bits.
  6341. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  6342. SourceLocation QuestionLoc) {
  6343. const VectorType *CV = CondTy->getAs<VectorType>();
  6344. const VectorType *RV = VecResTy->getAs<VectorType>();
  6345. assert(CV && RV);
  6346. if (CV->getNumElements() != RV->getNumElements()) {
  6347. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  6348. << CondTy << VecResTy;
  6349. return true;
  6350. }
  6351. QualType CVE = CV->getElementType();
  6352. QualType RVE = RV->getElementType();
  6353. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  6354. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6355. << CondTy << VecResTy;
  6356. return true;
  6357. }
  6358. return false;
  6359. }
  6360. /// Return the resulting type for the conditional operator in
  6361. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  6362. /// s6.3.i) when the condition is a vector type.
  6363. static QualType
  6364. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  6365. ExprResult &LHS, ExprResult &RHS,
  6366. SourceLocation QuestionLoc) {
  6367. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  6368. if (Cond.isInvalid())
  6369. return QualType();
  6370. QualType CondTy = Cond.get()->getType();
  6371. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  6372. return QualType();
  6373. // If either operand is a vector then find the vector type of the
  6374. // result as specified in OpenCL v1.1 s6.3.i.
  6375. if (LHS.get()->getType()->isVectorType() ||
  6376. RHS.get()->getType()->isVectorType()) {
  6377. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  6378. /*isCompAssign*/false,
  6379. /*AllowBothBool*/true,
  6380. /*AllowBoolConversions*/false);
  6381. if (VecResTy.isNull()) return QualType();
  6382. // The result type must match the condition type as specified in
  6383. // OpenCL v1.1 s6.11.6.
  6384. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  6385. return QualType();
  6386. return VecResTy;
  6387. }
  6388. // Both operands are scalar.
  6389. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  6390. }
  6391. /// Return true if the Expr is block type
  6392. static bool checkBlockType(Sema &S, const Expr *E) {
  6393. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6394. QualType Ty = CE->getCallee()->getType();
  6395. if (Ty->isBlockPointerType()) {
  6396. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  6397. return true;
  6398. }
  6399. }
  6400. return false;
  6401. }
  6402. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  6403. /// In that case, LHS = cond.
  6404. /// C99 6.5.15
  6405. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  6406. ExprResult &RHS, ExprValueKind &VK,
  6407. ExprObjectKind &OK,
  6408. SourceLocation QuestionLoc) {
  6409. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  6410. if (!LHSResult.isUsable()) return QualType();
  6411. LHS = LHSResult;
  6412. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  6413. if (!RHSResult.isUsable()) return QualType();
  6414. RHS = RHSResult;
  6415. // C++ is sufficiently different to merit its own checker.
  6416. if (getLangOpts().CPlusPlus)
  6417. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  6418. VK = VK_RValue;
  6419. OK = OK_Ordinary;
  6420. // The OpenCL operator with a vector condition is sufficiently
  6421. // different to merit its own checker.
  6422. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  6423. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  6424. // First, check the condition.
  6425. Cond = UsualUnaryConversions(Cond.get());
  6426. if (Cond.isInvalid())
  6427. return QualType();
  6428. if (checkCondition(*this, Cond.get(), QuestionLoc))
  6429. return QualType();
  6430. // Now check the two expressions.
  6431. if (LHS.get()->getType()->isVectorType() ||
  6432. RHS.get()->getType()->isVectorType())
  6433. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  6434. /*AllowBothBool*/true,
  6435. /*AllowBoolConversions*/false);
  6436. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  6437. if (LHS.isInvalid() || RHS.isInvalid())
  6438. return QualType();
  6439. QualType LHSTy = LHS.get()->getType();
  6440. QualType RHSTy = RHS.get()->getType();
  6441. // Diagnose attempts to convert between __float128 and long double where
  6442. // such conversions currently can't be handled.
  6443. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  6444. Diag(QuestionLoc,
  6445. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  6446. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6447. return QualType();
  6448. }
  6449. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  6450. // selection operator (?:).
  6451. if (getLangOpts().OpenCL &&
  6452. (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
  6453. return QualType();
  6454. }
  6455. // If both operands have arithmetic type, do the usual arithmetic conversions
  6456. // to find a common type: C99 6.5.15p3,5.
  6457. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  6458. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  6459. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  6460. return ResTy;
  6461. }
  6462. // If both operands are the same structure or union type, the result is that
  6463. // type.
  6464. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  6465. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  6466. if (LHSRT->getDecl() == RHSRT->getDecl())
  6467. // "If both the operands have structure or union type, the result has
  6468. // that type." This implies that CV qualifiers are dropped.
  6469. return LHSTy.getUnqualifiedType();
  6470. // FIXME: Type of conditional expression must be complete in C mode.
  6471. }
  6472. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  6473. // The following || allows only one side to be void (a GCC-ism).
  6474. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  6475. return checkConditionalVoidType(*this, LHS, RHS);
  6476. }
  6477. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  6478. // the type of the other operand."
  6479. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  6480. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  6481. // All objective-c pointer type analysis is done here.
  6482. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  6483. QuestionLoc);
  6484. if (LHS.isInvalid() || RHS.isInvalid())
  6485. return QualType();
  6486. if (!compositeType.isNull())
  6487. return compositeType;
  6488. // Handle block pointer types.
  6489. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  6490. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  6491. QuestionLoc);
  6492. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  6493. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  6494. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  6495. QuestionLoc);
  6496. // GCC compatibility: soften pointer/integer mismatch. Note that
  6497. // null pointers have been filtered out by this point.
  6498. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  6499. /*IsIntFirstExpr=*/true))
  6500. return RHSTy;
  6501. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  6502. /*IsIntFirstExpr=*/false))
  6503. return LHSTy;
  6504. // Emit a better diagnostic if one of the expressions is a null pointer
  6505. // constant and the other is not a pointer type. In this case, the user most
  6506. // likely forgot to take the address of the other expression.
  6507. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  6508. return QualType();
  6509. // Otherwise, the operands are not compatible.
  6510. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  6511. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6512. << RHS.get()->getSourceRange();
  6513. return QualType();
  6514. }
  6515. /// FindCompositeObjCPointerType - Helper method to find composite type of
  6516. /// two objective-c pointer types of the two input expressions.
  6517. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  6518. SourceLocation QuestionLoc) {
  6519. QualType LHSTy = LHS.get()->getType();
  6520. QualType RHSTy = RHS.get()->getType();
  6521. // Handle things like Class and struct objc_class*. Here we case the result
  6522. // to the pseudo-builtin, because that will be implicitly cast back to the
  6523. // redefinition type if an attempt is made to access its fields.
  6524. if (LHSTy->isObjCClassType() &&
  6525. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  6526. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6527. return LHSTy;
  6528. }
  6529. if (RHSTy->isObjCClassType() &&
  6530. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  6531. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6532. return RHSTy;
  6533. }
  6534. // And the same for struct objc_object* / id
  6535. if (LHSTy->isObjCIdType() &&
  6536. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  6537. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6538. return LHSTy;
  6539. }
  6540. if (RHSTy->isObjCIdType() &&
  6541. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  6542. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6543. return RHSTy;
  6544. }
  6545. // And the same for struct objc_selector* / SEL
  6546. if (Context.isObjCSelType(LHSTy) &&
  6547. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  6548. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  6549. return LHSTy;
  6550. }
  6551. if (Context.isObjCSelType(RHSTy) &&
  6552. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  6553. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  6554. return RHSTy;
  6555. }
  6556. // Check constraints for Objective-C object pointers types.
  6557. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  6558. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  6559. // Two identical object pointer types are always compatible.
  6560. return LHSTy;
  6561. }
  6562. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  6563. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  6564. QualType compositeType = LHSTy;
  6565. // If both operands are interfaces and either operand can be
  6566. // assigned to the other, use that type as the composite
  6567. // type. This allows
  6568. // xxx ? (A*) a : (B*) b
  6569. // where B is a subclass of A.
  6570. //
  6571. // Additionally, as for assignment, if either type is 'id'
  6572. // allow silent coercion. Finally, if the types are
  6573. // incompatible then make sure to use 'id' as the composite
  6574. // type so the result is acceptable for sending messages to.
  6575. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  6576. // It could return the composite type.
  6577. if (!(compositeType =
  6578. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  6579. // Nothing more to do.
  6580. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  6581. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  6582. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  6583. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  6584. } else if ((LHSOPT->isObjCQualifiedIdType() ||
  6585. RHSOPT->isObjCQualifiedIdType()) &&
  6586. Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
  6587. true)) {
  6588. // Need to handle "id<xx>" explicitly.
  6589. // GCC allows qualified id and any Objective-C type to devolve to
  6590. // id. Currently localizing to here until clear this should be
  6591. // part of ObjCQualifiedIdTypesAreCompatible.
  6592. compositeType = Context.getObjCIdType();
  6593. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  6594. compositeType = Context.getObjCIdType();
  6595. } else {
  6596. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  6597. << LHSTy << RHSTy
  6598. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6599. QualType incompatTy = Context.getObjCIdType();
  6600. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  6601. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  6602. return incompatTy;
  6603. }
  6604. // The object pointer types are compatible.
  6605. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  6606. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  6607. return compositeType;
  6608. }
  6609. // Check Objective-C object pointer types and 'void *'
  6610. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  6611. if (getLangOpts().ObjCAutoRefCount) {
  6612. // ARC forbids the implicit conversion of object pointers to 'void *',
  6613. // so these types are not compatible.
  6614. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6615. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6616. LHS = RHS = true;
  6617. return QualType();
  6618. }
  6619. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6620. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6621. QualType destPointee
  6622. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6623. QualType destType = Context.getPointerType(destPointee);
  6624. // Add qualifiers if necessary.
  6625. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6626. // Promote to void*.
  6627. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6628. return destType;
  6629. }
  6630. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  6631. if (getLangOpts().ObjCAutoRefCount) {
  6632. // ARC forbids the implicit conversion of object pointers to 'void *',
  6633. // so these types are not compatible.
  6634. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6635. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6636. LHS = RHS = true;
  6637. return QualType();
  6638. }
  6639. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6640. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6641. QualType destPointee
  6642. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6643. QualType destType = Context.getPointerType(destPointee);
  6644. // Add qualifiers if necessary.
  6645. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6646. // Promote to void*.
  6647. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6648. return destType;
  6649. }
  6650. return QualType();
  6651. }
  6652. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  6653. /// ParenRange in parentheses.
  6654. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  6655. const PartialDiagnostic &Note,
  6656. SourceRange ParenRange) {
  6657. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  6658. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  6659. EndLoc.isValid()) {
  6660. Self.Diag(Loc, Note)
  6661. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  6662. << FixItHint::CreateInsertion(EndLoc, ")");
  6663. } else {
  6664. // We can't display the parentheses, so just show the bare note.
  6665. Self.Diag(Loc, Note) << ParenRange;
  6666. }
  6667. }
  6668. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  6669. return BinaryOperator::isAdditiveOp(Opc) ||
  6670. BinaryOperator::isMultiplicativeOp(Opc) ||
  6671. BinaryOperator::isShiftOp(Opc);
  6672. }
  6673. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6674. /// expression, either using a built-in or overloaded operator,
  6675. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6676. /// expression.
  6677. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6678. Expr **RHSExprs) {
  6679. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6680. E = E->IgnoreImpCasts();
  6681. E = E->IgnoreConversionOperator();
  6682. E = E->IgnoreImpCasts();
  6683. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  6684. E = MTE->GetTemporaryExpr();
  6685. E = E->IgnoreImpCasts();
  6686. }
  6687. // Built-in binary operator.
  6688. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6689. if (IsArithmeticOp(OP->getOpcode())) {
  6690. *Opcode = OP->getOpcode();
  6691. *RHSExprs = OP->getRHS();
  6692. return true;
  6693. }
  6694. }
  6695. // Overloaded operator.
  6696. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6697. if (Call->getNumArgs() != 2)
  6698. return false;
  6699. // Make sure this is really a binary operator that is safe to pass into
  6700. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6701. OverloadedOperatorKind OO = Call->getOperator();
  6702. if (OO < OO_Plus || OO > OO_Arrow ||
  6703. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6704. return false;
  6705. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6706. if (IsArithmeticOp(OpKind)) {
  6707. *Opcode = OpKind;
  6708. *RHSExprs = Call->getArg(1);
  6709. return true;
  6710. }
  6711. }
  6712. return false;
  6713. }
  6714. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6715. /// or is a logical expression such as (x==y) which has int type, but is
  6716. /// commonly interpreted as boolean.
  6717. static bool ExprLooksBoolean(Expr *E) {
  6718. E = E->IgnoreParenImpCasts();
  6719. if (E->getType()->isBooleanType())
  6720. return true;
  6721. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6722. return OP->isComparisonOp() || OP->isLogicalOp();
  6723. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6724. return OP->getOpcode() == UO_LNot;
  6725. if (E->getType()->isPointerType())
  6726. return true;
  6727. // FIXME: What about overloaded operator calls returning "unspecified boolean
  6728. // type"s (commonly pointer-to-members)?
  6729. return false;
  6730. }
  6731. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6732. /// and binary operator are mixed in a way that suggests the programmer assumed
  6733. /// the conditional operator has higher precedence, for example:
  6734. /// "int x = a + someBinaryCondition ? 1 : 2".
  6735. static void DiagnoseConditionalPrecedence(Sema &Self,
  6736. SourceLocation OpLoc,
  6737. Expr *Condition,
  6738. Expr *LHSExpr,
  6739. Expr *RHSExpr) {
  6740. BinaryOperatorKind CondOpcode;
  6741. Expr *CondRHS;
  6742. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6743. return;
  6744. if (!ExprLooksBoolean(CondRHS))
  6745. return;
  6746. // The condition is an arithmetic binary expression, with a right-
  6747. // hand side that looks boolean, so warn.
  6748. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  6749. << Condition->getSourceRange()
  6750. << BinaryOperator::getOpcodeStr(CondOpcode);
  6751. SuggestParentheses(
  6752. Self, OpLoc,
  6753. Self.PDiag(diag::note_precedence_silence)
  6754. << BinaryOperator::getOpcodeStr(CondOpcode),
  6755. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  6756. SuggestParentheses(Self, OpLoc,
  6757. Self.PDiag(diag::note_precedence_conditional_first),
  6758. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  6759. }
  6760. /// Compute the nullability of a conditional expression.
  6761. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6762. QualType LHSTy, QualType RHSTy,
  6763. ASTContext &Ctx) {
  6764. if (!ResTy->isAnyPointerType())
  6765. return ResTy;
  6766. auto GetNullability = [&Ctx](QualType Ty) {
  6767. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6768. if (Kind)
  6769. return *Kind;
  6770. return NullabilityKind::Unspecified;
  6771. };
  6772. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6773. NullabilityKind MergedKind;
  6774. // Compute nullability of a binary conditional expression.
  6775. if (IsBin) {
  6776. if (LHSKind == NullabilityKind::NonNull)
  6777. MergedKind = NullabilityKind::NonNull;
  6778. else
  6779. MergedKind = RHSKind;
  6780. // Compute nullability of a normal conditional expression.
  6781. } else {
  6782. if (LHSKind == NullabilityKind::Nullable ||
  6783. RHSKind == NullabilityKind::Nullable)
  6784. MergedKind = NullabilityKind::Nullable;
  6785. else if (LHSKind == NullabilityKind::NonNull)
  6786. MergedKind = RHSKind;
  6787. else if (RHSKind == NullabilityKind::NonNull)
  6788. MergedKind = LHSKind;
  6789. else
  6790. MergedKind = NullabilityKind::Unspecified;
  6791. }
  6792. // Return if ResTy already has the correct nullability.
  6793. if (GetNullability(ResTy) == MergedKind)
  6794. return ResTy;
  6795. // Strip all nullability from ResTy.
  6796. while (ResTy->getNullability(Ctx))
  6797. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6798. // Create a new AttributedType with the new nullability kind.
  6799. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6800. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6801. }
  6802. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6803. /// in the case of a the GNU conditional expr extension.
  6804. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6805. SourceLocation ColonLoc,
  6806. Expr *CondExpr, Expr *LHSExpr,
  6807. Expr *RHSExpr) {
  6808. if (!getLangOpts().CPlusPlus) {
  6809. // C cannot handle TypoExpr nodes in the condition because it
  6810. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6811. // been dealt with before checking the operands.
  6812. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6813. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6814. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6815. if (!CondResult.isUsable())
  6816. return ExprError();
  6817. if (LHSExpr) {
  6818. if (!LHSResult.isUsable())
  6819. return ExprError();
  6820. }
  6821. if (!RHSResult.isUsable())
  6822. return ExprError();
  6823. CondExpr = CondResult.get();
  6824. LHSExpr = LHSResult.get();
  6825. RHSExpr = RHSResult.get();
  6826. }
  6827. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6828. // was the condition.
  6829. OpaqueValueExpr *opaqueValue = nullptr;
  6830. Expr *commonExpr = nullptr;
  6831. if (!LHSExpr) {
  6832. commonExpr = CondExpr;
  6833. // Lower out placeholder types first. This is important so that we don't
  6834. // try to capture a placeholder. This happens in few cases in C++; such
  6835. // as Objective-C++'s dictionary subscripting syntax.
  6836. if (commonExpr->hasPlaceholderType()) {
  6837. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6838. if (!result.isUsable()) return ExprError();
  6839. commonExpr = result.get();
  6840. }
  6841. // We usually want to apply unary conversions *before* saving, except
  6842. // in the special case of a C++ l-value conditional.
  6843. if (!(getLangOpts().CPlusPlus
  6844. && !commonExpr->isTypeDependent()
  6845. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6846. && commonExpr->isGLValue()
  6847. && commonExpr->isOrdinaryOrBitFieldObject()
  6848. && RHSExpr->isOrdinaryOrBitFieldObject()
  6849. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6850. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6851. if (commonRes.isInvalid())
  6852. return ExprError();
  6853. commonExpr = commonRes.get();
  6854. }
  6855. // If the common expression is a class or array prvalue, materialize it
  6856. // so that we can safely refer to it multiple times.
  6857. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6858. commonExpr->getType()->isArrayType())) {
  6859. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6860. if (MatExpr.isInvalid())
  6861. return ExprError();
  6862. commonExpr = MatExpr.get();
  6863. }
  6864. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6865. commonExpr->getType(),
  6866. commonExpr->getValueKind(),
  6867. commonExpr->getObjectKind(),
  6868. commonExpr);
  6869. LHSExpr = CondExpr = opaqueValue;
  6870. }
  6871. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6872. ExprValueKind VK = VK_RValue;
  6873. ExprObjectKind OK = OK_Ordinary;
  6874. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6875. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6876. VK, OK, QuestionLoc);
  6877. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6878. RHS.isInvalid())
  6879. return ExprError();
  6880. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6881. RHS.get());
  6882. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6883. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6884. Context);
  6885. if (!commonExpr)
  6886. return new (Context)
  6887. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6888. RHS.get(), result, VK, OK);
  6889. return new (Context) BinaryConditionalOperator(
  6890. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6891. ColonLoc, result, VK, OK);
  6892. }
  6893. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6894. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6895. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6896. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6897. // FIXME: add a couple examples in this comment.
  6898. static Sema::AssignConvertType
  6899. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6900. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6901. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6902. // get the "pointed to" type (ignoring qualifiers at the top level)
  6903. const Type *lhptee, *rhptee;
  6904. Qualifiers lhq, rhq;
  6905. std::tie(lhptee, lhq) =
  6906. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6907. std::tie(rhptee, rhq) =
  6908. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6909. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6910. // C99 6.5.16.1p1: This following citation is common to constraints
  6911. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6912. // qualifiers of the type *pointed to* by the right;
  6913. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6914. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6915. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6916. // Ignore lifetime for further calculation.
  6917. lhq.removeObjCLifetime();
  6918. rhq.removeObjCLifetime();
  6919. }
  6920. if (!lhq.compatiblyIncludes(rhq)) {
  6921. // Treat address-space mismatches as fatal.
  6922. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6923. return Sema::IncompatiblePointerDiscardsQualifiers;
  6924. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6925. // and from void*.
  6926. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6927. .compatiblyIncludes(
  6928. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6929. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6930. ; // keep old
  6931. // Treat lifetime mismatches as fatal.
  6932. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6933. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6934. // For GCC/MS compatibility, other qualifier mismatches are treated
  6935. // as still compatible in C.
  6936. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6937. }
  6938. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6939. // incomplete type and the other is a pointer to a qualified or unqualified
  6940. // version of void...
  6941. if (lhptee->isVoidType()) {
  6942. if (rhptee->isIncompleteOrObjectType())
  6943. return ConvTy;
  6944. // As an extension, we allow cast to/from void* to function pointer.
  6945. assert(rhptee->isFunctionType());
  6946. return Sema::FunctionVoidPointer;
  6947. }
  6948. if (rhptee->isVoidType()) {
  6949. if (lhptee->isIncompleteOrObjectType())
  6950. return ConvTy;
  6951. // As an extension, we allow cast to/from void* to function pointer.
  6952. assert(lhptee->isFunctionType());
  6953. return Sema::FunctionVoidPointer;
  6954. }
  6955. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6956. // unqualified versions of compatible types, ...
  6957. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6958. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6959. // Check if the pointee types are compatible ignoring the sign.
  6960. // We explicitly check for char so that we catch "char" vs
  6961. // "unsigned char" on systems where "char" is unsigned.
  6962. if (lhptee->isCharType())
  6963. ltrans = S.Context.UnsignedCharTy;
  6964. else if (lhptee->hasSignedIntegerRepresentation())
  6965. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  6966. if (rhptee->isCharType())
  6967. rtrans = S.Context.UnsignedCharTy;
  6968. else if (rhptee->hasSignedIntegerRepresentation())
  6969. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  6970. if (ltrans == rtrans) {
  6971. // Types are compatible ignoring the sign. Qualifier incompatibility
  6972. // takes priority over sign incompatibility because the sign
  6973. // warning can be disabled.
  6974. if (ConvTy != Sema::Compatible)
  6975. return ConvTy;
  6976. return Sema::IncompatiblePointerSign;
  6977. }
  6978. // If we are a multi-level pointer, it's possible that our issue is simply
  6979. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  6980. // the eventual target type is the same and the pointers have the same
  6981. // level of indirection, this must be the issue.
  6982. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  6983. do {
  6984. std::tie(lhptee, lhq) =
  6985. cast<PointerType>(lhptee)->getPointeeType().split().asPair();
  6986. std::tie(rhptee, rhq) =
  6987. cast<PointerType>(rhptee)->getPointeeType().split().asPair();
  6988. // Inconsistent address spaces at this point is invalid, even if the
  6989. // address spaces would be compatible.
  6990. // FIXME: This doesn't catch address space mismatches for pointers of
  6991. // different nesting levels, like:
  6992. // __local int *** a;
  6993. // int ** b = a;
  6994. // It's not clear how to actually determine when such pointers are
  6995. // invalidly incompatible.
  6996. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  6997. return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
  6998. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  6999. if (lhptee == rhptee)
  7000. return Sema::IncompatibleNestedPointerQualifiers;
  7001. }
  7002. // General pointer incompatibility takes priority over qualifiers.
  7003. return Sema::IncompatiblePointer;
  7004. }
  7005. if (!S.getLangOpts().CPlusPlus &&
  7006. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  7007. return Sema::IncompatiblePointer;
  7008. return ConvTy;
  7009. }
  7010. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  7011. /// block pointer types are compatible or whether a block and normal pointer
  7012. /// are compatible. It is more restrict than comparing two function pointer
  7013. // types.
  7014. static Sema::AssignConvertType
  7015. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  7016. QualType RHSType) {
  7017. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  7018. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  7019. QualType lhptee, rhptee;
  7020. // get the "pointed to" type (ignoring qualifiers at the top level)
  7021. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  7022. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  7023. // In C++, the types have to match exactly.
  7024. if (S.getLangOpts().CPlusPlus)
  7025. return Sema::IncompatibleBlockPointer;
  7026. Sema::AssignConvertType ConvTy = Sema::Compatible;
  7027. // For blocks we enforce that qualifiers are identical.
  7028. Qualifiers LQuals = lhptee.getLocalQualifiers();
  7029. Qualifiers RQuals = rhptee.getLocalQualifiers();
  7030. if (S.getLangOpts().OpenCL) {
  7031. LQuals.removeAddressSpace();
  7032. RQuals.removeAddressSpace();
  7033. }
  7034. if (LQuals != RQuals)
  7035. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  7036. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  7037. // assignment.
  7038. // The current behavior is similar to C++ lambdas. A block might be
  7039. // assigned to a variable iff its return type and parameters are compatible
  7040. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  7041. // an assignment. Presumably it should behave in way that a function pointer
  7042. // assignment does in C, so for each parameter and return type:
  7043. // * CVR and address space of LHS should be a superset of CVR and address
  7044. // space of RHS.
  7045. // * unqualified types should be compatible.
  7046. if (S.getLangOpts().OpenCL) {
  7047. if (!S.Context.typesAreBlockPointerCompatible(
  7048. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  7049. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  7050. return Sema::IncompatibleBlockPointer;
  7051. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  7052. return Sema::IncompatibleBlockPointer;
  7053. return ConvTy;
  7054. }
  7055. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  7056. /// for assignment compatibility.
  7057. static Sema::AssignConvertType
  7058. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  7059. QualType RHSType) {
  7060. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  7061. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  7062. if (LHSType->isObjCBuiltinType()) {
  7063. // Class is not compatible with ObjC object pointers.
  7064. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  7065. !RHSType->isObjCQualifiedClassType())
  7066. return Sema::IncompatiblePointer;
  7067. return Sema::Compatible;
  7068. }
  7069. if (RHSType->isObjCBuiltinType()) {
  7070. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  7071. !LHSType->isObjCQualifiedClassType())
  7072. return Sema::IncompatiblePointer;
  7073. return Sema::Compatible;
  7074. }
  7075. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  7076. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  7077. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  7078. // make an exception for id<P>
  7079. !LHSType->isObjCQualifiedIdType())
  7080. return Sema::CompatiblePointerDiscardsQualifiers;
  7081. if (S.Context.typesAreCompatible(LHSType, RHSType))
  7082. return Sema::Compatible;
  7083. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  7084. return Sema::IncompatibleObjCQualifiedId;
  7085. return Sema::IncompatiblePointer;
  7086. }
  7087. Sema::AssignConvertType
  7088. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  7089. QualType LHSType, QualType RHSType) {
  7090. // Fake up an opaque expression. We don't actually care about what
  7091. // cast operations are required, so if CheckAssignmentConstraints
  7092. // adds casts to this they'll be wasted, but fortunately that doesn't
  7093. // usually happen on valid code.
  7094. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  7095. ExprResult RHSPtr = &RHSExpr;
  7096. CastKind K;
  7097. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  7098. }
  7099. /// This helper function returns true if QT is a vector type that has element
  7100. /// type ElementType.
  7101. static bool isVector(QualType QT, QualType ElementType) {
  7102. if (const VectorType *VT = QT->getAs<VectorType>())
  7103. return VT->getElementType() == ElementType;
  7104. return false;
  7105. }
  7106. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  7107. /// has code to accommodate several GCC extensions when type checking
  7108. /// pointers. Here are some objectionable examples that GCC considers warnings:
  7109. ///
  7110. /// int a, *pint;
  7111. /// short *pshort;
  7112. /// struct foo *pfoo;
  7113. ///
  7114. /// pint = pshort; // warning: assignment from incompatible pointer type
  7115. /// a = pint; // warning: assignment makes integer from pointer without a cast
  7116. /// pint = a; // warning: assignment makes pointer from integer without a cast
  7117. /// pint = pfoo; // warning: assignment from incompatible pointer type
  7118. ///
  7119. /// As a result, the code for dealing with pointers is more complex than the
  7120. /// C99 spec dictates.
  7121. ///
  7122. /// Sets 'Kind' for any result kind except Incompatible.
  7123. Sema::AssignConvertType
  7124. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  7125. CastKind &Kind, bool ConvertRHS) {
  7126. QualType RHSType = RHS.get()->getType();
  7127. QualType OrigLHSType = LHSType;
  7128. // Get canonical types. We're not formatting these types, just comparing
  7129. // them.
  7130. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  7131. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  7132. // Common case: no conversion required.
  7133. if (LHSType == RHSType) {
  7134. Kind = CK_NoOp;
  7135. return Compatible;
  7136. }
  7137. // If we have an atomic type, try a non-atomic assignment, then just add an
  7138. // atomic qualification step.
  7139. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  7140. Sema::AssignConvertType result =
  7141. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  7142. if (result != Compatible)
  7143. return result;
  7144. if (Kind != CK_NoOp && ConvertRHS)
  7145. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  7146. Kind = CK_NonAtomicToAtomic;
  7147. return Compatible;
  7148. }
  7149. // If the left-hand side is a reference type, then we are in a
  7150. // (rare!) case where we've allowed the use of references in C,
  7151. // e.g., as a parameter type in a built-in function. In this case,
  7152. // just make sure that the type referenced is compatible with the
  7153. // right-hand side type. The caller is responsible for adjusting
  7154. // LHSType so that the resulting expression does not have reference
  7155. // type.
  7156. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  7157. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  7158. Kind = CK_LValueBitCast;
  7159. return Compatible;
  7160. }
  7161. return Incompatible;
  7162. }
  7163. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  7164. // to the same ExtVector type.
  7165. if (LHSType->isExtVectorType()) {
  7166. if (RHSType->isExtVectorType())
  7167. return Incompatible;
  7168. if (RHSType->isArithmeticType()) {
  7169. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  7170. if (ConvertRHS)
  7171. RHS = prepareVectorSplat(LHSType, RHS.get());
  7172. Kind = CK_VectorSplat;
  7173. return Compatible;
  7174. }
  7175. }
  7176. // Conversions to or from vector type.
  7177. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  7178. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  7179. // Allow assignments of an AltiVec vector type to an equivalent GCC
  7180. // vector type and vice versa
  7181. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7182. Kind = CK_BitCast;
  7183. return Compatible;
  7184. }
  7185. // If we are allowing lax vector conversions, and LHS and RHS are both
  7186. // vectors, the total size only needs to be the same. This is a bitcast;
  7187. // no bits are changed but the result type is different.
  7188. if (isLaxVectorConversion(RHSType, LHSType)) {
  7189. Kind = CK_BitCast;
  7190. return IncompatibleVectors;
  7191. }
  7192. }
  7193. // When the RHS comes from another lax conversion (e.g. binops between
  7194. // scalars and vectors) the result is canonicalized as a vector. When the
  7195. // LHS is also a vector, the lax is allowed by the condition above. Handle
  7196. // the case where LHS is a scalar.
  7197. if (LHSType->isScalarType()) {
  7198. const VectorType *VecType = RHSType->getAs<VectorType>();
  7199. if (VecType && VecType->getNumElements() == 1 &&
  7200. isLaxVectorConversion(RHSType, LHSType)) {
  7201. ExprResult *VecExpr = &RHS;
  7202. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  7203. Kind = CK_BitCast;
  7204. return Compatible;
  7205. }
  7206. }
  7207. return Incompatible;
  7208. }
  7209. // Diagnose attempts to convert between __float128 and long double where
  7210. // such conversions currently can't be handled.
  7211. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  7212. return Incompatible;
  7213. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  7214. // discards the imaginary part.
  7215. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  7216. !LHSType->getAs<ComplexType>())
  7217. return Incompatible;
  7218. // Arithmetic conversions.
  7219. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  7220. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  7221. if (ConvertRHS)
  7222. Kind = PrepareScalarCast(RHS, LHSType);
  7223. return Compatible;
  7224. }
  7225. // Conversions to normal pointers.
  7226. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  7227. // U* -> T*
  7228. if (isa<PointerType>(RHSType)) {
  7229. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7230. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  7231. if (AddrSpaceL != AddrSpaceR)
  7232. Kind = CK_AddressSpaceConversion;
  7233. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  7234. Kind = CK_NoOp;
  7235. else
  7236. Kind = CK_BitCast;
  7237. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  7238. }
  7239. // int -> T*
  7240. if (RHSType->isIntegerType()) {
  7241. Kind = CK_IntegralToPointer; // FIXME: null?
  7242. return IntToPointer;
  7243. }
  7244. // C pointers are not compatible with ObjC object pointers,
  7245. // with two exceptions:
  7246. if (isa<ObjCObjectPointerType>(RHSType)) {
  7247. // - conversions to void*
  7248. if (LHSPointer->getPointeeType()->isVoidType()) {
  7249. Kind = CK_BitCast;
  7250. return Compatible;
  7251. }
  7252. // - conversions from 'Class' to the redefinition type
  7253. if (RHSType->isObjCClassType() &&
  7254. Context.hasSameType(LHSType,
  7255. Context.getObjCClassRedefinitionType())) {
  7256. Kind = CK_BitCast;
  7257. return Compatible;
  7258. }
  7259. Kind = CK_BitCast;
  7260. return IncompatiblePointer;
  7261. }
  7262. // U^ -> void*
  7263. if (RHSType->getAs<BlockPointerType>()) {
  7264. if (LHSPointer->getPointeeType()->isVoidType()) {
  7265. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7266. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7267. ->getPointeeType()
  7268. .getAddressSpace();
  7269. Kind =
  7270. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7271. return Compatible;
  7272. }
  7273. }
  7274. return Incompatible;
  7275. }
  7276. // Conversions to block pointers.
  7277. if (isa<BlockPointerType>(LHSType)) {
  7278. // U^ -> T^
  7279. if (RHSType->isBlockPointerType()) {
  7280. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  7281. ->getPointeeType()
  7282. .getAddressSpace();
  7283. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7284. ->getPointeeType()
  7285. .getAddressSpace();
  7286. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7287. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  7288. }
  7289. // int or null -> T^
  7290. if (RHSType->isIntegerType()) {
  7291. Kind = CK_IntegralToPointer; // FIXME: null
  7292. return IntToBlockPointer;
  7293. }
  7294. // id -> T^
  7295. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  7296. Kind = CK_AnyPointerToBlockPointerCast;
  7297. return Compatible;
  7298. }
  7299. // void* -> T^
  7300. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  7301. if (RHSPT->getPointeeType()->isVoidType()) {
  7302. Kind = CK_AnyPointerToBlockPointerCast;
  7303. return Compatible;
  7304. }
  7305. return Incompatible;
  7306. }
  7307. // Conversions to Objective-C pointers.
  7308. if (isa<ObjCObjectPointerType>(LHSType)) {
  7309. // A* -> B*
  7310. if (RHSType->isObjCObjectPointerType()) {
  7311. Kind = CK_BitCast;
  7312. Sema::AssignConvertType result =
  7313. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  7314. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7315. result == Compatible &&
  7316. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  7317. result = IncompatibleObjCWeakRef;
  7318. return result;
  7319. }
  7320. // int or null -> A*
  7321. if (RHSType->isIntegerType()) {
  7322. Kind = CK_IntegralToPointer; // FIXME: null
  7323. return IntToPointer;
  7324. }
  7325. // In general, C pointers are not compatible with ObjC object pointers,
  7326. // with two exceptions:
  7327. if (isa<PointerType>(RHSType)) {
  7328. Kind = CK_CPointerToObjCPointerCast;
  7329. // - conversions from 'void*'
  7330. if (RHSType->isVoidPointerType()) {
  7331. return Compatible;
  7332. }
  7333. // - conversions to 'Class' from its redefinition type
  7334. if (LHSType->isObjCClassType() &&
  7335. Context.hasSameType(RHSType,
  7336. Context.getObjCClassRedefinitionType())) {
  7337. return Compatible;
  7338. }
  7339. return IncompatiblePointer;
  7340. }
  7341. // Only under strict condition T^ is compatible with an Objective-C pointer.
  7342. if (RHSType->isBlockPointerType() &&
  7343. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  7344. if (ConvertRHS)
  7345. maybeExtendBlockObject(RHS);
  7346. Kind = CK_BlockPointerToObjCPointerCast;
  7347. return Compatible;
  7348. }
  7349. return Incompatible;
  7350. }
  7351. // Conversions from pointers that are not covered by the above.
  7352. if (isa<PointerType>(RHSType)) {
  7353. // T* -> _Bool
  7354. if (LHSType == Context.BoolTy) {
  7355. Kind = CK_PointerToBoolean;
  7356. return Compatible;
  7357. }
  7358. // T* -> int
  7359. if (LHSType->isIntegerType()) {
  7360. Kind = CK_PointerToIntegral;
  7361. return PointerToInt;
  7362. }
  7363. return Incompatible;
  7364. }
  7365. // Conversions from Objective-C pointers that are not covered by the above.
  7366. if (isa<ObjCObjectPointerType>(RHSType)) {
  7367. // T* -> _Bool
  7368. if (LHSType == Context.BoolTy) {
  7369. Kind = CK_PointerToBoolean;
  7370. return Compatible;
  7371. }
  7372. // T* -> int
  7373. if (LHSType->isIntegerType()) {
  7374. Kind = CK_PointerToIntegral;
  7375. return PointerToInt;
  7376. }
  7377. return Incompatible;
  7378. }
  7379. // struct A -> struct B
  7380. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  7381. if (Context.typesAreCompatible(LHSType, RHSType)) {
  7382. Kind = CK_NoOp;
  7383. return Compatible;
  7384. }
  7385. }
  7386. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  7387. Kind = CK_IntToOCLSampler;
  7388. return Compatible;
  7389. }
  7390. return Incompatible;
  7391. }
  7392. /// Constructs a transparent union from an expression that is
  7393. /// used to initialize the transparent union.
  7394. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  7395. ExprResult &EResult, QualType UnionType,
  7396. FieldDecl *Field) {
  7397. // Build an initializer list that designates the appropriate member
  7398. // of the transparent union.
  7399. Expr *E = EResult.get();
  7400. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  7401. E, SourceLocation());
  7402. Initializer->setType(UnionType);
  7403. Initializer->setInitializedFieldInUnion(Field);
  7404. // Build a compound literal constructing a value of the transparent
  7405. // union type from this initializer list.
  7406. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  7407. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  7408. VK_RValue, Initializer, false);
  7409. }
  7410. Sema::AssignConvertType
  7411. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  7412. ExprResult &RHS) {
  7413. QualType RHSType = RHS.get()->getType();
  7414. // If the ArgType is a Union type, we want to handle a potential
  7415. // transparent_union GCC extension.
  7416. const RecordType *UT = ArgType->getAsUnionType();
  7417. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  7418. return Incompatible;
  7419. // The field to initialize within the transparent union.
  7420. RecordDecl *UD = UT->getDecl();
  7421. FieldDecl *InitField = nullptr;
  7422. // It's compatible if the expression matches any of the fields.
  7423. for (auto *it : UD->fields()) {
  7424. if (it->getType()->isPointerType()) {
  7425. // If the transparent union contains a pointer type, we allow:
  7426. // 1) void pointer
  7427. // 2) null pointer constant
  7428. if (RHSType->isPointerType())
  7429. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  7430. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  7431. InitField = it;
  7432. break;
  7433. }
  7434. if (RHS.get()->isNullPointerConstant(Context,
  7435. Expr::NPC_ValueDependentIsNull)) {
  7436. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  7437. CK_NullToPointer);
  7438. InitField = it;
  7439. break;
  7440. }
  7441. }
  7442. CastKind Kind;
  7443. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  7444. == Compatible) {
  7445. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  7446. InitField = it;
  7447. break;
  7448. }
  7449. }
  7450. if (!InitField)
  7451. return Incompatible;
  7452. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  7453. return Compatible;
  7454. }
  7455. Sema::AssignConvertType
  7456. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  7457. bool Diagnose,
  7458. bool DiagnoseCFAudited,
  7459. bool ConvertRHS) {
  7460. // We need to be able to tell the caller whether we diagnosed a problem, if
  7461. // they ask us to issue diagnostics.
  7462. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  7463. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  7464. // we can't avoid *all* modifications at the moment, so we need some somewhere
  7465. // to put the updated value.
  7466. ExprResult LocalRHS = CallerRHS;
  7467. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  7468. if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
  7469. if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
  7470. if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  7471. !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  7472. Diag(RHS.get()->getExprLoc(),
  7473. diag::warn_noderef_to_dereferenceable_pointer)
  7474. << RHS.get()->getSourceRange();
  7475. }
  7476. }
  7477. }
  7478. if (getLangOpts().CPlusPlus) {
  7479. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  7480. // C++ 5.17p3: If the left operand is not of class type, the
  7481. // expression is implicitly converted (C++ 4) to the
  7482. // cv-unqualified type of the left operand.
  7483. QualType RHSType = RHS.get()->getType();
  7484. if (Diagnose) {
  7485. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7486. AA_Assigning);
  7487. } else {
  7488. ImplicitConversionSequence ICS =
  7489. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7490. /*SuppressUserConversions=*/false,
  7491. /*AllowExplicit=*/false,
  7492. /*InOverloadResolution=*/false,
  7493. /*CStyle=*/false,
  7494. /*AllowObjCWritebackConversion=*/false);
  7495. if (ICS.isFailure())
  7496. return Incompatible;
  7497. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7498. ICS, AA_Assigning);
  7499. }
  7500. if (RHS.isInvalid())
  7501. return Incompatible;
  7502. Sema::AssignConvertType result = Compatible;
  7503. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7504. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  7505. result = IncompatibleObjCWeakRef;
  7506. return result;
  7507. }
  7508. // FIXME: Currently, we fall through and treat C++ classes like C
  7509. // structures.
  7510. // FIXME: We also fall through for atomics; not sure what should
  7511. // happen there, though.
  7512. } else if (RHS.get()->getType() == Context.OverloadTy) {
  7513. // As a set of extensions to C, we support overloading on functions. These
  7514. // functions need to be resolved here.
  7515. DeclAccessPair DAP;
  7516. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  7517. RHS.get(), LHSType, /*Complain=*/false, DAP))
  7518. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  7519. else
  7520. return Incompatible;
  7521. }
  7522. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7523. // a null pointer constant.
  7524. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7525. LHSType->isBlockPointerType()) &&
  7526. RHS.get()->isNullPointerConstant(Context,
  7527. Expr::NPC_ValueDependentIsNull)) {
  7528. if (Diagnose || ConvertRHS) {
  7529. CastKind Kind;
  7530. CXXCastPath Path;
  7531. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7532. /*IgnoreBaseAccess=*/false, Diagnose);
  7533. if (ConvertRHS)
  7534. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7535. }
  7536. return Compatible;
  7537. }
  7538. // OpenCL queue_t type assignment.
  7539. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  7540. Context, Expr::NPC_ValueDependentIsNull)) {
  7541. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7542. return Compatible;
  7543. }
  7544. // This check seems unnatural, however it is necessary to ensure the proper
  7545. // conversion of functions/arrays. If the conversion were done for all
  7546. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7547. // expressions that suppress this implicit conversion (&, sizeof).
  7548. //
  7549. // Suppress this for references: C++ 8.5.3p5.
  7550. if (!LHSType->isReferenceType()) {
  7551. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7552. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7553. if (RHS.isInvalid())
  7554. return Incompatible;
  7555. }
  7556. CastKind Kind;
  7557. Sema::AssignConvertType result =
  7558. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7559. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7560. // type of the assignment expression.
  7561. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7562. // so that we can use references in built-in functions even in C.
  7563. // The getNonReferenceType() call makes sure that the resulting expression
  7564. // does not have reference type.
  7565. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7566. QualType Ty = LHSType.getNonLValueExprType(Context);
  7567. Expr *E = RHS.get();
  7568. // Check for various Objective-C errors. If we are not reporting
  7569. // diagnostics and just checking for errors, e.g., during overload
  7570. // resolution, return Incompatible to indicate the failure.
  7571. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7572. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7573. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7574. if (!Diagnose)
  7575. return Incompatible;
  7576. }
  7577. if (getLangOpts().ObjC &&
  7578. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  7579. E->getType(), E, Diagnose) ||
  7580. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7581. if (!Diagnose)
  7582. return Incompatible;
  7583. // Replace the expression with a corrected version and continue so we
  7584. // can find further errors.
  7585. RHS = E;
  7586. return Compatible;
  7587. }
  7588. if (ConvertRHS)
  7589. RHS = ImpCastExprToType(E, Ty, Kind);
  7590. }
  7591. return result;
  7592. }
  7593. namespace {
  7594. /// The original operand to an operator, prior to the application of the usual
  7595. /// arithmetic conversions and converting the arguments of a builtin operator
  7596. /// candidate.
  7597. struct OriginalOperand {
  7598. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  7599. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  7600. Op = MTE->GetTemporaryExpr();
  7601. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  7602. Op = BTE->getSubExpr();
  7603. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  7604. Orig = ICE->getSubExprAsWritten();
  7605. Conversion = ICE->getConversionFunction();
  7606. }
  7607. }
  7608. QualType getType() const { return Orig->getType(); }
  7609. Expr *Orig;
  7610. NamedDecl *Conversion;
  7611. };
  7612. }
  7613. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7614. ExprResult &RHS) {
  7615. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  7616. Diag(Loc, diag::err_typecheck_invalid_operands)
  7617. << OrigLHS.getType() << OrigRHS.getType()
  7618. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7619. // If a user-defined conversion was applied to either of the operands prior
  7620. // to applying the built-in operator rules, tell the user about it.
  7621. if (OrigLHS.Conversion) {
  7622. Diag(OrigLHS.Conversion->getLocation(),
  7623. diag::note_typecheck_invalid_operands_converted)
  7624. << 0 << LHS.get()->getType();
  7625. }
  7626. if (OrigRHS.Conversion) {
  7627. Diag(OrigRHS.Conversion->getLocation(),
  7628. diag::note_typecheck_invalid_operands_converted)
  7629. << 1 << RHS.get()->getType();
  7630. }
  7631. return QualType();
  7632. }
  7633. // Diagnose cases where a scalar was implicitly converted to a vector and
  7634. // diagnose the underlying types. Otherwise, diagnose the error
  7635. // as invalid vector logical operands for non-C++ cases.
  7636. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7637. ExprResult &RHS) {
  7638. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7639. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7640. bool LHSNatVec = LHSType->isVectorType();
  7641. bool RHSNatVec = RHSType->isVectorType();
  7642. if (!(LHSNatVec && RHSNatVec)) {
  7643. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7644. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7645. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7646. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7647. << Vector->getSourceRange();
  7648. return QualType();
  7649. }
  7650. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7651. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7652. << RHS.get()->getSourceRange();
  7653. return QualType();
  7654. }
  7655. /// Try to convert a value of non-vector type to a vector type by converting
  7656. /// the type to the element type of the vector and then performing a splat.
  7657. /// If the language is OpenCL, we only use conversions that promote scalar
  7658. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7659. /// for float->int.
  7660. ///
  7661. /// OpenCL V2.0 6.2.6.p2:
  7662. /// An error shall occur if any scalar operand type has greater rank
  7663. /// than the type of the vector element.
  7664. ///
  7665. /// \param scalar - if non-null, actually perform the conversions
  7666. /// \return true if the operation fails (but without diagnosing the failure)
  7667. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7668. QualType scalarTy,
  7669. QualType vectorEltTy,
  7670. QualType vectorTy,
  7671. unsigned &DiagID) {
  7672. // The conversion to apply to the scalar before splatting it,
  7673. // if necessary.
  7674. CastKind scalarCast = CK_NoOp;
  7675. if (vectorEltTy->isIntegralType(S.Context)) {
  7676. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7677. (scalarTy->isIntegerType() &&
  7678. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7679. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7680. return true;
  7681. }
  7682. if (!scalarTy->isIntegralType(S.Context))
  7683. return true;
  7684. scalarCast = CK_IntegralCast;
  7685. } else if (vectorEltTy->isRealFloatingType()) {
  7686. if (scalarTy->isRealFloatingType()) {
  7687. if (S.getLangOpts().OpenCL &&
  7688. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7689. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7690. return true;
  7691. }
  7692. scalarCast = CK_FloatingCast;
  7693. }
  7694. else if (scalarTy->isIntegralType(S.Context))
  7695. scalarCast = CK_IntegralToFloating;
  7696. else
  7697. return true;
  7698. } else {
  7699. return true;
  7700. }
  7701. // Adjust scalar if desired.
  7702. if (scalar) {
  7703. if (scalarCast != CK_NoOp)
  7704. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7705. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7706. }
  7707. return false;
  7708. }
  7709. /// Convert vector E to a vector with the same number of elements but different
  7710. /// element type.
  7711. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7712. const auto *VecTy = E->getType()->getAs<VectorType>();
  7713. assert(VecTy && "Expression E must be a vector");
  7714. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7715. VecTy->getNumElements(),
  7716. VecTy->getVectorKind());
  7717. // Look through the implicit cast. Return the subexpression if its type is
  7718. // NewVecTy.
  7719. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7720. if (ICE->getSubExpr()->getType() == NewVecTy)
  7721. return ICE->getSubExpr();
  7722. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7723. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7724. }
  7725. /// Test if a (constant) integer Int can be casted to another integer type
  7726. /// IntTy without losing precision.
  7727. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7728. QualType OtherIntTy) {
  7729. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7730. // Reject cases where the value of the Int is unknown as that would
  7731. // possibly cause truncation, but accept cases where the scalar can be
  7732. // demoted without loss of precision.
  7733. Expr::EvalResult EVResult;
  7734. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7735. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7736. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7737. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7738. if (CstInt) {
  7739. // If the scalar is constant and is of a higher order and has more active
  7740. // bits that the vector element type, reject it.
  7741. llvm::APSInt Result = EVResult.Val.getInt();
  7742. unsigned NumBits = IntSigned
  7743. ? (Result.isNegative() ? Result.getMinSignedBits()
  7744. : Result.getActiveBits())
  7745. : Result.getActiveBits();
  7746. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7747. return true;
  7748. // If the signedness of the scalar type and the vector element type
  7749. // differs and the number of bits is greater than that of the vector
  7750. // element reject it.
  7751. return (IntSigned != OtherIntSigned &&
  7752. NumBits > S.Context.getIntWidth(OtherIntTy));
  7753. }
  7754. // Reject cases where the value of the scalar is not constant and it's
  7755. // order is greater than that of the vector element type.
  7756. return (Order < 0);
  7757. }
  7758. /// Test if a (constant) integer Int can be casted to floating point type
  7759. /// FloatTy without losing precision.
  7760. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7761. QualType FloatTy) {
  7762. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7763. // Determine if the integer constant can be expressed as a floating point
  7764. // number of the appropriate type.
  7765. Expr::EvalResult EVResult;
  7766. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7767. uint64_t Bits = 0;
  7768. if (CstInt) {
  7769. // Reject constants that would be truncated if they were converted to
  7770. // the floating point type. Test by simple to/from conversion.
  7771. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7772. // could be avoided if there was a convertFromAPInt method
  7773. // which could signal back if implicit truncation occurred.
  7774. llvm::APSInt Result = EVResult.Val.getInt();
  7775. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7776. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7777. llvm::APFloat::rmTowardZero);
  7778. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7779. !IntTy->hasSignedIntegerRepresentation());
  7780. bool Ignored = false;
  7781. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7782. &Ignored);
  7783. if (Result != ConvertBack)
  7784. return true;
  7785. } else {
  7786. // Reject types that cannot be fully encoded into the mantissa of
  7787. // the float.
  7788. Bits = S.Context.getTypeSize(IntTy);
  7789. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7790. S.Context.getFloatTypeSemantics(FloatTy));
  7791. if (Bits > FloatPrec)
  7792. return true;
  7793. }
  7794. return false;
  7795. }
  7796. /// Attempt to convert and splat Scalar into a vector whose types matches
  7797. /// Vector following GCC conversion rules. The rule is that implicit
  7798. /// conversion can occur when Scalar can be casted to match Vector's element
  7799. /// type without causing truncation of Scalar.
  7800. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7801. ExprResult *Vector) {
  7802. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7803. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7804. const VectorType *VT = VectorTy->getAs<VectorType>();
  7805. assert(!isa<ExtVectorType>(VT) &&
  7806. "ExtVectorTypes should not be handled here!");
  7807. QualType VectorEltTy = VT->getElementType();
  7808. // Reject cases where the vector element type or the scalar element type are
  7809. // not integral or floating point types.
  7810. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7811. return true;
  7812. // The conversion to apply to the scalar before splatting it,
  7813. // if necessary.
  7814. CastKind ScalarCast = CK_NoOp;
  7815. // Accept cases where the vector elements are integers and the scalar is
  7816. // an integer.
  7817. // FIXME: Notionally if the scalar was a floating point value with a precise
  7818. // integral representation, we could cast it to an appropriate integer
  7819. // type and then perform the rest of the checks here. GCC will perform
  7820. // this conversion in some cases as determined by the input language.
  7821. // We should accept it on a language independent basis.
  7822. if (VectorEltTy->isIntegralType(S.Context) &&
  7823. ScalarTy->isIntegralType(S.Context) &&
  7824. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7825. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7826. return true;
  7827. ScalarCast = CK_IntegralCast;
  7828. } else if (VectorEltTy->isRealFloatingType()) {
  7829. if (ScalarTy->isRealFloatingType()) {
  7830. // Reject cases where the scalar type is not a constant and has a higher
  7831. // Order than the vector element type.
  7832. llvm::APFloat Result(0.0);
  7833. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7834. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7835. if (!CstScalar && Order < 0)
  7836. return true;
  7837. // If the scalar cannot be safely casted to the vector element type,
  7838. // reject it.
  7839. if (CstScalar) {
  7840. bool Truncated = false;
  7841. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7842. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7843. if (Truncated)
  7844. return true;
  7845. }
  7846. ScalarCast = CK_FloatingCast;
  7847. } else if (ScalarTy->isIntegralType(S.Context)) {
  7848. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7849. return true;
  7850. ScalarCast = CK_IntegralToFloating;
  7851. } else
  7852. return true;
  7853. }
  7854. // Adjust scalar if desired.
  7855. if (Scalar) {
  7856. if (ScalarCast != CK_NoOp)
  7857. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7858. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7859. }
  7860. return false;
  7861. }
  7862. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7863. SourceLocation Loc, bool IsCompAssign,
  7864. bool AllowBothBool,
  7865. bool AllowBoolConversions) {
  7866. if (!IsCompAssign) {
  7867. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7868. if (LHS.isInvalid())
  7869. return QualType();
  7870. }
  7871. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7872. if (RHS.isInvalid())
  7873. return QualType();
  7874. // For conversion purposes, we ignore any qualifiers.
  7875. // For example, "const float" and "float" are equivalent.
  7876. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7877. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7878. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7879. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7880. assert(LHSVecType || RHSVecType);
  7881. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7882. // for some operators but not others.
  7883. if (!AllowBothBool &&
  7884. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7885. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7886. return InvalidOperands(Loc, LHS, RHS);
  7887. // If the vector types are identical, return.
  7888. if (Context.hasSameType(LHSType, RHSType))
  7889. return LHSType;
  7890. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7891. if (LHSVecType && RHSVecType &&
  7892. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7893. if (isa<ExtVectorType>(LHSVecType)) {
  7894. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7895. return LHSType;
  7896. }
  7897. if (!IsCompAssign)
  7898. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7899. return RHSType;
  7900. }
  7901. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7902. // can be mixed, with the result being the non-bool type. The non-bool
  7903. // operand must have integer element type.
  7904. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7905. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7906. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7907. Context.getTypeSize(RHSVecType->getElementType()))) {
  7908. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7909. LHSVecType->getElementType()->isIntegerType() &&
  7910. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7911. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7912. return LHSType;
  7913. }
  7914. if (!IsCompAssign &&
  7915. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7916. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7917. RHSVecType->getElementType()->isIntegerType()) {
  7918. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7919. return RHSType;
  7920. }
  7921. }
  7922. // If there's a vector type and a scalar, try to convert the scalar to
  7923. // the vector element type and splat.
  7924. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7925. if (!RHSVecType) {
  7926. if (isa<ExtVectorType>(LHSVecType)) {
  7927. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7928. LHSVecType->getElementType(), LHSType,
  7929. DiagID))
  7930. return LHSType;
  7931. } else {
  7932. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7933. return LHSType;
  7934. }
  7935. }
  7936. if (!LHSVecType) {
  7937. if (isa<ExtVectorType>(RHSVecType)) {
  7938. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7939. LHSType, RHSVecType->getElementType(),
  7940. RHSType, DiagID))
  7941. return RHSType;
  7942. } else {
  7943. if (LHS.get()->getValueKind() == VK_LValue ||
  7944. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7945. return RHSType;
  7946. }
  7947. }
  7948. // FIXME: The code below also handles conversion between vectors and
  7949. // non-scalars, we should break this down into fine grained specific checks
  7950. // and emit proper diagnostics.
  7951. QualType VecType = LHSVecType ? LHSType : RHSType;
  7952. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7953. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7954. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7955. if (isLaxVectorConversion(OtherType, VecType)) {
  7956. // If we're allowing lax vector conversions, only the total (data) size
  7957. // needs to be the same. For non compound assignment, if one of the types is
  7958. // scalar, the result is always the vector type.
  7959. if (!IsCompAssign) {
  7960. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7961. return VecType;
  7962. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  7963. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  7964. // type. Note that this is already done by non-compound assignments in
  7965. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  7966. // <1 x T> -> T. The result is also a vector type.
  7967. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  7968. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  7969. ExprResult *RHSExpr = &RHS;
  7970. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  7971. return VecType;
  7972. }
  7973. }
  7974. // Okay, the expression is invalid.
  7975. // If there's a non-vector, non-real operand, diagnose that.
  7976. if ((!RHSVecType && !RHSType->isRealType()) ||
  7977. (!LHSVecType && !LHSType->isRealType())) {
  7978. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  7979. << LHSType << RHSType
  7980. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7981. return QualType();
  7982. }
  7983. // OpenCL V1.1 6.2.6.p1:
  7984. // If the operands are of more than one vector type, then an error shall
  7985. // occur. Implicit conversions between vector types are not permitted, per
  7986. // section 6.2.1.
  7987. if (getLangOpts().OpenCL &&
  7988. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  7989. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  7990. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  7991. << RHSType;
  7992. return QualType();
  7993. }
  7994. // If there is a vector type that is not a ExtVector and a scalar, we reach
  7995. // this point if scalar could not be converted to the vector's element type
  7996. // without truncation.
  7997. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  7998. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  7999. QualType Scalar = LHSVecType ? RHSType : LHSType;
  8000. QualType Vector = LHSVecType ? LHSType : RHSType;
  8001. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  8002. Diag(Loc,
  8003. diag::err_typecheck_vector_not_convertable_implict_truncation)
  8004. << ScalarOrVector << Scalar << Vector;
  8005. return QualType();
  8006. }
  8007. // Otherwise, use the generic diagnostic.
  8008. Diag(Loc, DiagID)
  8009. << LHSType << RHSType
  8010. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8011. return QualType();
  8012. }
  8013. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  8014. // expression. These are mainly cases where the null pointer is used as an
  8015. // integer instead of a pointer.
  8016. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8017. SourceLocation Loc, bool IsCompare) {
  8018. // The canonical way to check for a GNU null is with isNullPointerConstant,
  8019. // but we use a bit of a hack here for speed; this is a relatively
  8020. // hot path, and isNullPointerConstant is slow.
  8021. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  8022. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  8023. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  8024. // Avoid analyzing cases where the result will either be invalid (and
  8025. // diagnosed as such) or entirely valid and not something to warn about.
  8026. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  8027. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  8028. return;
  8029. // Comparison operations would not make sense with a null pointer no matter
  8030. // what the other expression is.
  8031. if (!IsCompare) {
  8032. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  8033. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  8034. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  8035. return;
  8036. }
  8037. // The rest of the operations only make sense with a null pointer
  8038. // if the other expression is a pointer.
  8039. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  8040. NonNullType->canDecayToPointerType())
  8041. return;
  8042. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  8043. << LHSNull /* LHS is NULL */ << NonNullType
  8044. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8045. }
  8046. static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
  8047. SourceLocation Loc) {
  8048. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  8049. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  8050. if (!LUE || !RUE)
  8051. return;
  8052. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  8053. RUE->getKind() != UETT_SizeOf)
  8054. return;
  8055. const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
  8056. QualType LHSTy = LHSArg->getType();
  8057. QualType RHSTy;
  8058. if (RUE->isArgumentType())
  8059. RHSTy = RUE->getArgumentType();
  8060. else
  8061. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  8062. if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
  8063. if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
  8064. return;
  8065. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  8066. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  8067. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  8068. S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
  8069. << LHSArgDecl;
  8070. }
  8071. } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
  8072. QualType ArrayElemTy = ArrayTy->getElementType();
  8073. if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
  8074. ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
  8075. S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
  8076. return;
  8077. S.Diag(Loc, diag::warn_division_sizeof_array)
  8078. << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
  8079. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  8080. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  8081. S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
  8082. << LHSArgDecl;
  8083. }
  8084. S.Diag(Loc, diag::note_precedence_silence) << RHS;
  8085. }
  8086. }
  8087. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  8088. ExprResult &RHS,
  8089. SourceLocation Loc, bool IsDiv) {
  8090. // Check for division/remainder by zero.
  8091. Expr::EvalResult RHSValue;
  8092. if (!RHS.get()->isValueDependent() &&
  8093. RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
  8094. RHSValue.Val.getInt() == 0)
  8095. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8096. S.PDiag(diag::warn_remainder_division_by_zero)
  8097. << IsDiv << RHS.get()->getSourceRange());
  8098. }
  8099. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  8100. SourceLocation Loc,
  8101. bool IsCompAssign, bool IsDiv) {
  8102. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8103. if (LHS.get()->getType()->isVectorType() ||
  8104. RHS.get()->getType()->isVectorType())
  8105. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8106. /*AllowBothBool*/getLangOpts().AltiVec,
  8107. /*AllowBoolConversions*/false);
  8108. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8109. if (LHS.isInvalid() || RHS.isInvalid())
  8110. return QualType();
  8111. if (compType.isNull() || !compType->isArithmeticType())
  8112. return InvalidOperands(Loc, LHS, RHS);
  8113. if (IsDiv) {
  8114. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  8115. DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
  8116. }
  8117. return compType;
  8118. }
  8119. QualType Sema::CheckRemainderOperands(
  8120. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  8121. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8122. if (LHS.get()->getType()->isVectorType() ||
  8123. RHS.get()->getType()->isVectorType()) {
  8124. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  8125. RHS.get()->getType()->hasIntegerRepresentation())
  8126. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8127. /*AllowBothBool*/getLangOpts().AltiVec,
  8128. /*AllowBoolConversions*/false);
  8129. return InvalidOperands(Loc, LHS, RHS);
  8130. }
  8131. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8132. if (LHS.isInvalid() || RHS.isInvalid())
  8133. return QualType();
  8134. if (compType.isNull() || !compType->isIntegerType())
  8135. return InvalidOperands(Loc, LHS, RHS);
  8136. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  8137. return compType;
  8138. }
  8139. /// Diagnose invalid arithmetic on two void pointers.
  8140. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  8141. Expr *LHSExpr, Expr *RHSExpr) {
  8142. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8143. ? diag::err_typecheck_pointer_arith_void_type
  8144. : diag::ext_gnu_void_ptr)
  8145. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  8146. << RHSExpr->getSourceRange();
  8147. }
  8148. /// Diagnose invalid arithmetic on a void pointer.
  8149. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  8150. Expr *Pointer) {
  8151. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8152. ? diag::err_typecheck_pointer_arith_void_type
  8153. : diag::ext_gnu_void_ptr)
  8154. << 0 /* one pointer */ << Pointer->getSourceRange();
  8155. }
  8156. /// Diagnose invalid arithmetic on a null pointer.
  8157. ///
  8158. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  8159. /// idiom, which we recognize as a GNU extension.
  8160. ///
  8161. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  8162. Expr *Pointer, bool IsGNUIdiom) {
  8163. if (IsGNUIdiom)
  8164. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  8165. << Pointer->getSourceRange();
  8166. else
  8167. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  8168. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  8169. }
  8170. /// Diagnose invalid arithmetic on two function pointers.
  8171. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  8172. Expr *LHS, Expr *RHS) {
  8173. assert(LHS->getType()->isAnyPointerType());
  8174. assert(RHS->getType()->isAnyPointerType());
  8175. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8176. ? diag::err_typecheck_pointer_arith_function_type
  8177. : diag::ext_gnu_ptr_func_arith)
  8178. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  8179. // We only show the second type if it differs from the first.
  8180. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  8181. RHS->getType())
  8182. << RHS->getType()->getPointeeType()
  8183. << LHS->getSourceRange() << RHS->getSourceRange();
  8184. }
  8185. /// Diagnose invalid arithmetic on a function pointer.
  8186. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  8187. Expr *Pointer) {
  8188. assert(Pointer->getType()->isAnyPointerType());
  8189. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8190. ? diag::err_typecheck_pointer_arith_function_type
  8191. : diag::ext_gnu_ptr_func_arith)
  8192. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  8193. << 0 /* one pointer, so only one type */
  8194. << Pointer->getSourceRange();
  8195. }
  8196. /// Emit error if Operand is incomplete pointer type
  8197. ///
  8198. /// \returns True if pointer has incomplete type
  8199. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  8200. Expr *Operand) {
  8201. QualType ResType = Operand->getType();
  8202. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8203. ResType = ResAtomicType->getValueType();
  8204. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  8205. QualType PointeeTy = ResType->getPointeeType();
  8206. return S.RequireCompleteType(Loc, PointeeTy,
  8207. diag::err_typecheck_arithmetic_incomplete_type,
  8208. PointeeTy, Operand->getSourceRange());
  8209. }
  8210. /// Check the validity of an arithmetic pointer operand.
  8211. ///
  8212. /// If the operand has pointer type, this code will check for pointer types
  8213. /// which are invalid in arithmetic operations. These will be diagnosed
  8214. /// appropriately, including whether or not the use is supported as an
  8215. /// extension.
  8216. ///
  8217. /// \returns True when the operand is valid to use (even if as an extension).
  8218. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  8219. Expr *Operand) {
  8220. QualType ResType = Operand->getType();
  8221. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8222. ResType = ResAtomicType->getValueType();
  8223. if (!ResType->isAnyPointerType()) return true;
  8224. QualType PointeeTy = ResType->getPointeeType();
  8225. if (PointeeTy->isVoidType()) {
  8226. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  8227. return !S.getLangOpts().CPlusPlus;
  8228. }
  8229. if (PointeeTy->isFunctionType()) {
  8230. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  8231. return !S.getLangOpts().CPlusPlus;
  8232. }
  8233. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  8234. return true;
  8235. }
  8236. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  8237. /// operands.
  8238. ///
  8239. /// This routine will diagnose any invalid arithmetic on pointer operands much
  8240. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  8241. /// for emitting a single diagnostic even for operations where both LHS and RHS
  8242. /// are (potentially problematic) pointers.
  8243. ///
  8244. /// \returns True when the operand is valid to use (even if as an extension).
  8245. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  8246. Expr *LHSExpr, Expr *RHSExpr) {
  8247. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  8248. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  8249. if (!isLHSPointer && !isRHSPointer) return true;
  8250. QualType LHSPointeeTy, RHSPointeeTy;
  8251. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  8252. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  8253. // if both are pointers check if operation is valid wrt address spaces
  8254. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  8255. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  8256. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  8257. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  8258. S.Diag(Loc,
  8259. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  8260. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  8261. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8262. return false;
  8263. }
  8264. }
  8265. // Check for arithmetic on pointers to incomplete types.
  8266. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  8267. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  8268. if (isLHSVoidPtr || isRHSVoidPtr) {
  8269. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  8270. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  8271. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  8272. return !S.getLangOpts().CPlusPlus;
  8273. }
  8274. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  8275. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  8276. if (isLHSFuncPtr || isRHSFuncPtr) {
  8277. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  8278. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  8279. RHSExpr);
  8280. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  8281. return !S.getLangOpts().CPlusPlus;
  8282. }
  8283. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  8284. return false;
  8285. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  8286. return false;
  8287. return true;
  8288. }
  8289. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  8290. /// literal.
  8291. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  8292. Expr *LHSExpr, Expr *RHSExpr) {
  8293. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  8294. Expr* IndexExpr = RHSExpr;
  8295. if (!StrExpr) {
  8296. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  8297. IndexExpr = LHSExpr;
  8298. }
  8299. bool IsStringPlusInt = StrExpr &&
  8300. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  8301. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  8302. return;
  8303. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8304. Self.Diag(OpLoc, diag::warn_string_plus_int)
  8305. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  8306. // Only print a fixit for "str" + int, not for int + "str".
  8307. if (IndexExpr == RHSExpr) {
  8308. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8309. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8310. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8311. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8312. << FixItHint::CreateInsertion(EndLoc, "]");
  8313. } else
  8314. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8315. }
  8316. /// Emit a warning when adding a char literal to a string.
  8317. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  8318. Expr *LHSExpr, Expr *RHSExpr) {
  8319. const Expr *StringRefExpr = LHSExpr;
  8320. const CharacterLiteral *CharExpr =
  8321. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  8322. if (!CharExpr) {
  8323. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  8324. StringRefExpr = RHSExpr;
  8325. }
  8326. if (!CharExpr || !StringRefExpr)
  8327. return;
  8328. const QualType StringType = StringRefExpr->getType();
  8329. // Return if not a PointerType.
  8330. if (!StringType->isAnyPointerType())
  8331. return;
  8332. // Return if not a CharacterType.
  8333. if (!StringType->getPointeeType()->isAnyCharacterType())
  8334. return;
  8335. ASTContext &Ctx = Self.getASTContext();
  8336. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8337. const QualType CharType = CharExpr->getType();
  8338. if (!CharType->isAnyCharacterType() &&
  8339. CharType->isIntegerType() &&
  8340. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  8341. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8342. << DiagRange << Ctx.CharTy;
  8343. } else {
  8344. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8345. << DiagRange << CharExpr->getType();
  8346. }
  8347. // Only print a fixit for str + char, not for char + str.
  8348. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  8349. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8350. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8351. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8352. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8353. << FixItHint::CreateInsertion(EndLoc, "]");
  8354. } else {
  8355. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8356. }
  8357. }
  8358. /// Emit error when two pointers are incompatible.
  8359. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  8360. Expr *LHSExpr, Expr *RHSExpr) {
  8361. assert(LHSExpr->getType()->isAnyPointerType());
  8362. assert(RHSExpr->getType()->isAnyPointerType());
  8363. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  8364. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  8365. << RHSExpr->getSourceRange();
  8366. }
  8367. // C99 6.5.6
  8368. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  8369. SourceLocation Loc, BinaryOperatorKind Opc,
  8370. QualType* CompLHSTy) {
  8371. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8372. if (LHS.get()->getType()->isVectorType() ||
  8373. RHS.get()->getType()->isVectorType()) {
  8374. QualType compType = CheckVectorOperands(
  8375. LHS, RHS, Loc, CompLHSTy,
  8376. /*AllowBothBool*/getLangOpts().AltiVec,
  8377. /*AllowBoolConversions*/getLangOpts().ZVector);
  8378. if (CompLHSTy) *CompLHSTy = compType;
  8379. return compType;
  8380. }
  8381. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8382. if (LHS.isInvalid() || RHS.isInvalid())
  8383. return QualType();
  8384. // Diagnose "string literal" '+' int and string '+' "char literal".
  8385. if (Opc == BO_Add) {
  8386. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  8387. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  8388. }
  8389. // handle the common case first (both operands are arithmetic).
  8390. if (!compType.isNull() && compType->isArithmeticType()) {
  8391. if (CompLHSTy) *CompLHSTy = compType;
  8392. return compType;
  8393. }
  8394. // Type-checking. Ultimately the pointer's going to be in PExp;
  8395. // note that we bias towards the LHS being the pointer.
  8396. Expr *PExp = LHS.get(), *IExp = RHS.get();
  8397. bool isObjCPointer;
  8398. if (PExp->getType()->isPointerType()) {
  8399. isObjCPointer = false;
  8400. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8401. isObjCPointer = true;
  8402. } else {
  8403. std::swap(PExp, IExp);
  8404. if (PExp->getType()->isPointerType()) {
  8405. isObjCPointer = false;
  8406. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8407. isObjCPointer = true;
  8408. } else {
  8409. return InvalidOperands(Loc, LHS, RHS);
  8410. }
  8411. }
  8412. assert(PExp->getType()->isAnyPointerType());
  8413. if (!IExp->getType()->isIntegerType())
  8414. return InvalidOperands(Loc, LHS, RHS);
  8415. // Adding to a null pointer results in undefined behavior.
  8416. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  8417. Context, Expr::NPC_ValueDependentIsNotNull)) {
  8418. // In C++ adding zero to a null pointer is defined.
  8419. Expr::EvalResult KnownVal;
  8420. if (!getLangOpts().CPlusPlus ||
  8421. (!IExp->isValueDependent() &&
  8422. (!IExp->EvaluateAsInt(KnownVal, Context) ||
  8423. KnownVal.Val.getInt() != 0))) {
  8424. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  8425. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  8426. Context, BO_Add, PExp, IExp);
  8427. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  8428. }
  8429. }
  8430. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  8431. return QualType();
  8432. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  8433. return QualType();
  8434. // Check array bounds for pointer arithemtic
  8435. CheckArrayAccess(PExp, IExp);
  8436. if (CompLHSTy) {
  8437. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  8438. if (LHSTy.isNull()) {
  8439. LHSTy = LHS.get()->getType();
  8440. if (LHSTy->isPromotableIntegerType())
  8441. LHSTy = Context.getPromotedIntegerType(LHSTy);
  8442. }
  8443. *CompLHSTy = LHSTy;
  8444. }
  8445. return PExp->getType();
  8446. }
  8447. // C99 6.5.6
  8448. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  8449. SourceLocation Loc,
  8450. QualType* CompLHSTy) {
  8451. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8452. if (LHS.get()->getType()->isVectorType() ||
  8453. RHS.get()->getType()->isVectorType()) {
  8454. QualType compType = CheckVectorOperands(
  8455. LHS, RHS, Loc, CompLHSTy,
  8456. /*AllowBothBool*/getLangOpts().AltiVec,
  8457. /*AllowBoolConversions*/getLangOpts().ZVector);
  8458. if (CompLHSTy) *CompLHSTy = compType;
  8459. return compType;
  8460. }
  8461. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8462. if (LHS.isInvalid() || RHS.isInvalid())
  8463. return QualType();
  8464. // Enforce type constraints: C99 6.5.6p3.
  8465. // Handle the common case first (both operands are arithmetic).
  8466. if (!compType.isNull() && compType->isArithmeticType()) {
  8467. if (CompLHSTy) *CompLHSTy = compType;
  8468. return compType;
  8469. }
  8470. // Either ptr - int or ptr - ptr.
  8471. if (LHS.get()->getType()->isAnyPointerType()) {
  8472. QualType lpointee = LHS.get()->getType()->getPointeeType();
  8473. // Diagnose bad cases where we step over interface counts.
  8474. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  8475. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  8476. return QualType();
  8477. // The result type of a pointer-int computation is the pointer type.
  8478. if (RHS.get()->getType()->isIntegerType()) {
  8479. // Subtracting from a null pointer should produce a warning.
  8480. // The last argument to the diagnose call says this doesn't match the
  8481. // GNU int-to-pointer idiom.
  8482. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  8483. Expr::NPC_ValueDependentIsNotNull)) {
  8484. // In C++ adding zero to a null pointer is defined.
  8485. Expr::EvalResult KnownVal;
  8486. if (!getLangOpts().CPlusPlus ||
  8487. (!RHS.get()->isValueDependent() &&
  8488. (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
  8489. KnownVal.Val.getInt() != 0))) {
  8490. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  8491. }
  8492. }
  8493. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  8494. return QualType();
  8495. // Check array bounds for pointer arithemtic
  8496. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  8497. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  8498. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8499. return LHS.get()->getType();
  8500. }
  8501. // Handle pointer-pointer subtractions.
  8502. if (const PointerType *RHSPTy
  8503. = RHS.get()->getType()->getAs<PointerType>()) {
  8504. QualType rpointee = RHSPTy->getPointeeType();
  8505. if (getLangOpts().CPlusPlus) {
  8506. // Pointee types must be the same: C++ [expr.add]
  8507. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  8508. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8509. }
  8510. } else {
  8511. // Pointee types must be compatible C99 6.5.6p3
  8512. if (!Context.typesAreCompatible(
  8513. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  8514. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  8515. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8516. return QualType();
  8517. }
  8518. }
  8519. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  8520. LHS.get(), RHS.get()))
  8521. return QualType();
  8522. // FIXME: Add warnings for nullptr - ptr.
  8523. // The pointee type may have zero size. As an extension, a structure or
  8524. // union may have zero size or an array may have zero length. In this
  8525. // case subtraction does not make sense.
  8526. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  8527. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  8528. if (ElementSize.isZero()) {
  8529. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  8530. << rpointee.getUnqualifiedType()
  8531. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8532. }
  8533. }
  8534. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8535. return Context.getPointerDiffType();
  8536. }
  8537. }
  8538. return InvalidOperands(Loc, LHS, RHS);
  8539. }
  8540. static bool isScopedEnumerationType(QualType T) {
  8541. if (const EnumType *ET = T->getAs<EnumType>())
  8542. return ET->getDecl()->isScoped();
  8543. return false;
  8544. }
  8545. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  8546. SourceLocation Loc, BinaryOperatorKind Opc,
  8547. QualType LHSType) {
  8548. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  8549. // so skip remaining warnings as we don't want to modify values within Sema.
  8550. if (S.getLangOpts().OpenCL)
  8551. return;
  8552. // Check right/shifter operand
  8553. Expr::EvalResult RHSResult;
  8554. if (RHS.get()->isValueDependent() ||
  8555. !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
  8556. return;
  8557. llvm::APSInt Right = RHSResult.Val.getInt();
  8558. if (Right.isNegative()) {
  8559. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8560. S.PDiag(diag::warn_shift_negative)
  8561. << RHS.get()->getSourceRange());
  8562. return;
  8563. }
  8564. llvm::APInt LeftBits(Right.getBitWidth(),
  8565. S.Context.getTypeSize(LHS.get()->getType()));
  8566. if (Right.uge(LeftBits)) {
  8567. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8568. S.PDiag(diag::warn_shift_gt_typewidth)
  8569. << RHS.get()->getSourceRange());
  8570. return;
  8571. }
  8572. if (Opc != BO_Shl)
  8573. return;
  8574. // When left shifting an ICE which is signed, we can check for overflow which
  8575. // according to C++ standards prior to C++2a has undefined behavior
  8576. // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
  8577. // more than the maximum value representable in the result type, so never
  8578. // warn for those. (FIXME: Unsigned left-shift overflow in a constant
  8579. // expression is still probably a bug.)
  8580. Expr::EvalResult LHSResult;
  8581. if (LHS.get()->isValueDependent() ||
  8582. LHSType->hasUnsignedIntegerRepresentation() ||
  8583. !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
  8584. return;
  8585. llvm::APSInt Left = LHSResult.Val.getInt();
  8586. // If LHS does not have a signed type and non-negative value
  8587. // then, the behavior is undefined before C++2a. Warn about it.
  8588. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
  8589. !S.getLangOpts().CPlusPlus2a) {
  8590. S.DiagRuntimeBehavior(Loc, LHS.get(),
  8591. S.PDiag(diag::warn_shift_lhs_negative)
  8592. << LHS.get()->getSourceRange());
  8593. return;
  8594. }
  8595. llvm::APInt ResultBits =
  8596. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  8597. if (LeftBits.uge(ResultBits))
  8598. return;
  8599. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8600. Result = Result.shl(Right);
  8601. // Print the bit representation of the signed integer as an unsigned
  8602. // hexadecimal number.
  8603. SmallString<40> HexResult;
  8604. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8605. // If we are only missing a sign bit, this is less likely to result in actual
  8606. // bugs -- if the result is cast back to an unsigned type, it will have the
  8607. // expected value. Thus we place this behind a different warning that can be
  8608. // turned off separately if needed.
  8609. if (LeftBits == ResultBits - 1) {
  8610. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8611. << HexResult << LHSType
  8612. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8613. return;
  8614. }
  8615. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8616. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8617. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8618. << RHS.get()->getSourceRange();
  8619. }
  8620. /// Return the resulting type when a vector is shifted
  8621. /// by a scalar or vector shift amount.
  8622. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8623. SourceLocation Loc, bool IsCompAssign) {
  8624. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8625. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8626. !LHS.get()->getType()->isVectorType()) {
  8627. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8628. << RHS.get()->getType() << LHS.get()->getType()
  8629. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8630. return QualType();
  8631. }
  8632. if (!IsCompAssign) {
  8633. LHS = S.UsualUnaryConversions(LHS.get());
  8634. if (LHS.isInvalid()) return QualType();
  8635. }
  8636. RHS = S.UsualUnaryConversions(RHS.get());
  8637. if (RHS.isInvalid()) return QualType();
  8638. QualType LHSType = LHS.get()->getType();
  8639. // Note that LHS might be a scalar because the routine calls not only in
  8640. // OpenCL case.
  8641. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8642. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8643. // Note that RHS might not be a vector.
  8644. QualType RHSType = RHS.get()->getType();
  8645. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8646. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8647. // The operands need to be integers.
  8648. if (!LHSEleType->isIntegerType()) {
  8649. S.Diag(Loc, diag::err_typecheck_expect_int)
  8650. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8651. return QualType();
  8652. }
  8653. if (!RHSEleType->isIntegerType()) {
  8654. S.Diag(Loc, diag::err_typecheck_expect_int)
  8655. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8656. return QualType();
  8657. }
  8658. if (!LHSVecTy) {
  8659. assert(RHSVecTy);
  8660. if (IsCompAssign)
  8661. return RHSType;
  8662. if (LHSEleType != RHSEleType) {
  8663. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8664. LHSEleType = RHSEleType;
  8665. }
  8666. QualType VecTy =
  8667. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8668. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8669. LHSType = VecTy;
  8670. } else if (RHSVecTy) {
  8671. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8672. // are applied component-wise. So if RHS is a vector, then ensure
  8673. // that the number of elements is the same as LHS...
  8674. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8675. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8676. << LHS.get()->getType() << RHS.get()->getType()
  8677. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8678. return QualType();
  8679. }
  8680. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8681. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8682. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8683. if (LHSBT != RHSBT &&
  8684. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8685. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8686. << LHS.get()->getType() << RHS.get()->getType()
  8687. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8688. }
  8689. }
  8690. } else {
  8691. // ...else expand RHS to match the number of elements in LHS.
  8692. QualType VecTy =
  8693. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8694. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8695. }
  8696. return LHSType;
  8697. }
  8698. // C99 6.5.7
  8699. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8700. SourceLocation Loc, BinaryOperatorKind Opc,
  8701. bool IsCompAssign) {
  8702. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8703. // Vector shifts promote their scalar inputs to vector type.
  8704. if (LHS.get()->getType()->isVectorType() ||
  8705. RHS.get()->getType()->isVectorType()) {
  8706. if (LangOpts.ZVector) {
  8707. // The shift operators for the z vector extensions work basically
  8708. // like general shifts, except that neither the LHS nor the RHS is
  8709. // allowed to be a "vector bool".
  8710. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8711. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8712. return InvalidOperands(Loc, LHS, RHS);
  8713. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8714. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8715. return InvalidOperands(Loc, LHS, RHS);
  8716. }
  8717. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8718. }
  8719. // Shifts don't perform usual arithmetic conversions, they just do integer
  8720. // promotions on each operand. C99 6.5.7p3
  8721. // For the LHS, do usual unary conversions, but then reset them away
  8722. // if this is a compound assignment.
  8723. ExprResult OldLHS = LHS;
  8724. LHS = UsualUnaryConversions(LHS.get());
  8725. if (LHS.isInvalid())
  8726. return QualType();
  8727. QualType LHSType = LHS.get()->getType();
  8728. if (IsCompAssign) LHS = OldLHS;
  8729. // The RHS is simpler.
  8730. RHS = UsualUnaryConversions(RHS.get());
  8731. if (RHS.isInvalid())
  8732. return QualType();
  8733. QualType RHSType = RHS.get()->getType();
  8734. // C99 6.5.7p2: Each of the operands shall have integer type.
  8735. if (!LHSType->hasIntegerRepresentation() ||
  8736. !RHSType->hasIntegerRepresentation())
  8737. return InvalidOperands(Loc, LHS, RHS);
  8738. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8739. // hasIntegerRepresentation() above instead of this.
  8740. if (isScopedEnumerationType(LHSType) ||
  8741. isScopedEnumerationType(RHSType)) {
  8742. return InvalidOperands(Loc, LHS, RHS);
  8743. }
  8744. // Sanity-check shift operands
  8745. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8746. // "The type of the result is that of the promoted left operand."
  8747. return LHSType;
  8748. }
  8749. /// If two different enums are compared, raise a warning.
  8750. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8751. Expr *RHS) {
  8752. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8753. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8754. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8755. if (!LHSEnumType)
  8756. return;
  8757. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8758. if (!RHSEnumType)
  8759. return;
  8760. // Ignore anonymous enums.
  8761. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8762. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8763. return;
  8764. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8765. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8766. return;
  8767. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8768. return;
  8769. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8770. << LHSStrippedType << RHSStrippedType
  8771. << LHS->getSourceRange() << RHS->getSourceRange();
  8772. }
  8773. /// Diagnose bad pointer comparisons.
  8774. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8775. ExprResult &LHS, ExprResult &RHS,
  8776. bool IsError) {
  8777. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8778. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8779. << LHS.get()->getType() << RHS.get()->getType()
  8780. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8781. }
  8782. /// Returns false if the pointers are converted to a composite type,
  8783. /// true otherwise.
  8784. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8785. ExprResult &LHS, ExprResult &RHS) {
  8786. // C++ [expr.rel]p2:
  8787. // [...] Pointer conversions (4.10) and qualification
  8788. // conversions (4.4) are performed on pointer operands (or on
  8789. // a pointer operand and a null pointer constant) to bring
  8790. // them to their composite pointer type. [...]
  8791. //
  8792. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8793. // comparisons of pointers.
  8794. QualType LHSType = LHS.get()->getType();
  8795. QualType RHSType = RHS.get()->getType();
  8796. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8797. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8798. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8799. if (T.isNull()) {
  8800. if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
  8801. (RHSType->isPointerType() || RHSType->isMemberPointerType()))
  8802. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8803. else
  8804. S.InvalidOperands(Loc, LHS, RHS);
  8805. return true;
  8806. }
  8807. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8808. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8809. return false;
  8810. }
  8811. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8812. ExprResult &LHS,
  8813. ExprResult &RHS,
  8814. bool IsError) {
  8815. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8816. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8817. << LHS.get()->getType() << RHS.get()->getType()
  8818. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8819. }
  8820. static bool isObjCObjectLiteral(ExprResult &E) {
  8821. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8822. case Stmt::ObjCArrayLiteralClass:
  8823. case Stmt::ObjCDictionaryLiteralClass:
  8824. case Stmt::ObjCStringLiteralClass:
  8825. case Stmt::ObjCBoxedExprClass:
  8826. return true;
  8827. default:
  8828. // Note that ObjCBoolLiteral is NOT an object literal!
  8829. return false;
  8830. }
  8831. }
  8832. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8833. const ObjCObjectPointerType *Type =
  8834. LHS->getType()->getAs<ObjCObjectPointerType>();
  8835. // If this is not actually an Objective-C object, bail out.
  8836. if (!Type)
  8837. return false;
  8838. // Get the LHS object's interface type.
  8839. QualType InterfaceType = Type->getPointeeType();
  8840. // If the RHS isn't an Objective-C object, bail out.
  8841. if (!RHS->getType()->isObjCObjectPointerType())
  8842. return false;
  8843. // Try to find the -isEqual: method.
  8844. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8845. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8846. InterfaceType,
  8847. /*IsInstance=*/true);
  8848. if (!Method) {
  8849. if (Type->isObjCIdType()) {
  8850. // For 'id', just check the global pool.
  8851. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8852. /*receiverId=*/true);
  8853. } else {
  8854. // Check protocols.
  8855. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8856. /*IsInstance=*/true);
  8857. }
  8858. }
  8859. if (!Method)
  8860. return false;
  8861. QualType T = Method->parameters()[0]->getType();
  8862. if (!T->isObjCObjectPointerType())
  8863. return false;
  8864. QualType R = Method->getReturnType();
  8865. if (!R->isScalarType())
  8866. return false;
  8867. return true;
  8868. }
  8869. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8870. FromE = FromE->IgnoreParenImpCasts();
  8871. switch (FromE->getStmtClass()) {
  8872. default:
  8873. break;
  8874. case Stmt::ObjCStringLiteralClass:
  8875. // "string literal"
  8876. return LK_String;
  8877. case Stmt::ObjCArrayLiteralClass:
  8878. // "array literal"
  8879. return LK_Array;
  8880. case Stmt::ObjCDictionaryLiteralClass:
  8881. // "dictionary literal"
  8882. return LK_Dictionary;
  8883. case Stmt::BlockExprClass:
  8884. return LK_Block;
  8885. case Stmt::ObjCBoxedExprClass: {
  8886. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8887. switch (Inner->getStmtClass()) {
  8888. case Stmt::IntegerLiteralClass:
  8889. case Stmt::FloatingLiteralClass:
  8890. case Stmt::CharacterLiteralClass:
  8891. case Stmt::ObjCBoolLiteralExprClass:
  8892. case Stmt::CXXBoolLiteralExprClass:
  8893. // "numeric literal"
  8894. return LK_Numeric;
  8895. case Stmt::ImplicitCastExprClass: {
  8896. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8897. // Boolean literals can be represented by implicit casts.
  8898. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8899. return LK_Numeric;
  8900. break;
  8901. }
  8902. default:
  8903. break;
  8904. }
  8905. return LK_Boxed;
  8906. }
  8907. }
  8908. return LK_None;
  8909. }
  8910. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8911. ExprResult &LHS, ExprResult &RHS,
  8912. BinaryOperator::Opcode Opc){
  8913. Expr *Literal;
  8914. Expr *Other;
  8915. if (isObjCObjectLiteral(LHS)) {
  8916. Literal = LHS.get();
  8917. Other = RHS.get();
  8918. } else {
  8919. Literal = RHS.get();
  8920. Other = LHS.get();
  8921. }
  8922. // Don't warn on comparisons against nil.
  8923. Other = Other->IgnoreParenCasts();
  8924. if (Other->isNullPointerConstant(S.getASTContext(),
  8925. Expr::NPC_ValueDependentIsNotNull))
  8926. return;
  8927. // This should be kept in sync with warn_objc_literal_comparison.
  8928. // LK_String should always be after the other literals, since it has its own
  8929. // warning flag.
  8930. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8931. assert(LiteralKind != Sema::LK_Block);
  8932. if (LiteralKind == Sema::LK_None) {
  8933. llvm_unreachable("Unknown Objective-C object literal kind");
  8934. }
  8935. if (LiteralKind == Sema::LK_String)
  8936. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8937. << Literal->getSourceRange();
  8938. else
  8939. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8940. << LiteralKind << Literal->getSourceRange();
  8941. if (BinaryOperator::isEqualityOp(Opc) &&
  8942. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8943. SourceLocation Start = LHS.get()->getBeginLoc();
  8944. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  8945. CharSourceRange OpRange =
  8946. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8947. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8948. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8949. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8950. << FixItHint::CreateInsertion(End, "]");
  8951. }
  8952. }
  8953. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8954. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8955. ExprResult &RHS, SourceLocation Loc,
  8956. BinaryOperatorKind Opc) {
  8957. // Check that left hand side is !something.
  8958. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8959. if (!UO || UO->getOpcode() != UO_LNot) return;
  8960. // Only check if the right hand side is non-bool arithmetic type.
  8961. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  8962. // Make sure that the something in !something is not bool.
  8963. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  8964. if (SubExpr->isKnownToHaveBooleanValue()) return;
  8965. // Emit warning.
  8966. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  8967. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  8968. << Loc << IsBitwiseOp;
  8969. // First note suggest !(x < y)
  8970. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  8971. SourceLocation FirstClose = RHS.get()->getEndLoc();
  8972. FirstClose = S.getLocForEndOfToken(FirstClose);
  8973. if (FirstClose.isInvalid())
  8974. FirstOpen = SourceLocation();
  8975. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  8976. << IsBitwiseOp
  8977. << FixItHint::CreateInsertion(FirstOpen, "(")
  8978. << FixItHint::CreateInsertion(FirstClose, ")");
  8979. // Second note suggests (!x) < y
  8980. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  8981. SourceLocation SecondClose = LHS.get()->getEndLoc();
  8982. SecondClose = S.getLocForEndOfToken(SecondClose);
  8983. if (SecondClose.isInvalid())
  8984. SecondOpen = SourceLocation();
  8985. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  8986. << FixItHint::CreateInsertion(SecondOpen, "(")
  8987. << FixItHint::CreateInsertion(SecondClose, ")");
  8988. }
  8989. // Returns true if E refers to a non-weak array.
  8990. static bool checkForArray(const Expr *E) {
  8991. const ValueDecl *D = nullptr;
  8992. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  8993. D = DR->getDecl();
  8994. } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  8995. if (Mem->isImplicitAccess())
  8996. D = Mem->getMemberDecl();
  8997. }
  8998. if (!D)
  8999. return false;
  9000. return D->getType()->isArrayType() && !D->isWeak();
  9001. }
  9002. /// Diagnose some forms of syntactically-obvious tautological comparison.
  9003. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  9004. Expr *LHS, Expr *RHS,
  9005. BinaryOperatorKind Opc) {
  9006. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  9007. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  9008. QualType LHSType = LHS->getType();
  9009. QualType RHSType = RHS->getType();
  9010. if (LHSType->hasFloatingRepresentation() ||
  9011. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  9012. LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
  9013. S.inTemplateInstantiation())
  9014. return;
  9015. // Comparisons between two array types are ill-formed for operator<=>, so
  9016. // we shouldn't emit any additional warnings about it.
  9017. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  9018. return;
  9019. // For non-floating point types, check for self-comparisons of the form
  9020. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9021. // often indicate logic errors in the program.
  9022. //
  9023. // NOTE: Don't warn about comparison expressions resulting from macro
  9024. // expansion. Also don't warn about comparisons which are only self
  9025. // comparisons within a template instantiation. The warnings should catch
  9026. // obvious cases in the definition of the template anyways. The idea is to
  9027. // warn when the typed comparison operator will always evaluate to the same
  9028. // result.
  9029. // Used for indexing into %select in warn_comparison_always
  9030. enum {
  9031. AlwaysConstant,
  9032. AlwaysTrue,
  9033. AlwaysFalse,
  9034. AlwaysEqual, // std::strong_ordering::equal from operator<=>
  9035. };
  9036. if (Expr::isSameComparisonOperand(LHS, RHS)) {
  9037. unsigned Result;
  9038. switch (Opc) {
  9039. case BO_EQ: case BO_LE: case BO_GE:
  9040. Result = AlwaysTrue;
  9041. break;
  9042. case BO_NE: case BO_LT: case BO_GT:
  9043. Result = AlwaysFalse;
  9044. break;
  9045. case BO_Cmp:
  9046. Result = AlwaysEqual;
  9047. break;
  9048. default:
  9049. Result = AlwaysConstant;
  9050. break;
  9051. }
  9052. S.DiagRuntimeBehavior(Loc, nullptr,
  9053. S.PDiag(diag::warn_comparison_always)
  9054. << 0 /*self-comparison*/
  9055. << Result);
  9056. } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
  9057. // What is it always going to evaluate to?
  9058. unsigned Result;
  9059. switch(Opc) {
  9060. case BO_EQ: // e.g. array1 == array2
  9061. Result = AlwaysFalse;
  9062. break;
  9063. case BO_NE: // e.g. array1 != array2
  9064. Result = AlwaysTrue;
  9065. break;
  9066. default: // e.g. array1 <= array2
  9067. // The best we can say is 'a constant'
  9068. Result = AlwaysConstant;
  9069. break;
  9070. }
  9071. S.DiagRuntimeBehavior(Loc, nullptr,
  9072. S.PDiag(diag::warn_comparison_always)
  9073. << 1 /*array comparison*/
  9074. << Result);
  9075. }
  9076. if (isa<CastExpr>(LHSStripped))
  9077. LHSStripped = LHSStripped->IgnoreParenCasts();
  9078. if (isa<CastExpr>(RHSStripped))
  9079. RHSStripped = RHSStripped->IgnoreParenCasts();
  9080. // Warn about comparisons against a string constant (unless the other
  9081. // operand is null); the user probably wants strcmp.
  9082. Expr *LiteralString = nullptr;
  9083. Expr *LiteralStringStripped = nullptr;
  9084. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  9085. !RHSStripped->isNullPointerConstant(S.Context,
  9086. Expr::NPC_ValueDependentIsNull)) {
  9087. LiteralString = LHS;
  9088. LiteralStringStripped = LHSStripped;
  9089. } else if ((isa<StringLiteral>(RHSStripped) ||
  9090. isa<ObjCEncodeExpr>(RHSStripped)) &&
  9091. !LHSStripped->isNullPointerConstant(S.Context,
  9092. Expr::NPC_ValueDependentIsNull)) {
  9093. LiteralString = RHS;
  9094. LiteralStringStripped = RHSStripped;
  9095. }
  9096. if (LiteralString) {
  9097. S.DiagRuntimeBehavior(Loc, nullptr,
  9098. S.PDiag(diag::warn_stringcompare)
  9099. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  9100. << LiteralString->getSourceRange());
  9101. }
  9102. }
  9103. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  9104. switch (CK) {
  9105. default: {
  9106. #ifndef NDEBUG
  9107. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  9108. << "\n";
  9109. #endif
  9110. llvm_unreachable("unhandled cast kind");
  9111. }
  9112. case CK_UserDefinedConversion:
  9113. return ICK_Identity;
  9114. case CK_LValueToRValue:
  9115. return ICK_Lvalue_To_Rvalue;
  9116. case CK_ArrayToPointerDecay:
  9117. return ICK_Array_To_Pointer;
  9118. case CK_FunctionToPointerDecay:
  9119. return ICK_Function_To_Pointer;
  9120. case CK_IntegralCast:
  9121. return ICK_Integral_Conversion;
  9122. case CK_FloatingCast:
  9123. return ICK_Floating_Conversion;
  9124. case CK_IntegralToFloating:
  9125. case CK_FloatingToIntegral:
  9126. return ICK_Floating_Integral;
  9127. case CK_IntegralComplexCast:
  9128. case CK_FloatingComplexCast:
  9129. case CK_FloatingComplexToIntegralComplex:
  9130. case CK_IntegralComplexToFloatingComplex:
  9131. return ICK_Complex_Conversion;
  9132. case CK_FloatingComplexToReal:
  9133. case CK_FloatingRealToComplex:
  9134. case CK_IntegralComplexToReal:
  9135. case CK_IntegralRealToComplex:
  9136. return ICK_Complex_Real;
  9137. }
  9138. }
  9139. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  9140. QualType FromType,
  9141. SourceLocation Loc) {
  9142. // Check for a narrowing implicit conversion.
  9143. StandardConversionSequence SCS;
  9144. SCS.setAsIdentityConversion();
  9145. SCS.setToType(0, FromType);
  9146. SCS.setToType(1, ToType);
  9147. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  9148. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  9149. APValue PreNarrowingValue;
  9150. QualType PreNarrowingType;
  9151. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  9152. PreNarrowingType,
  9153. /*IgnoreFloatToIntegralConversion*/ true)) {
  9154. case NK_Dependent_Narrowing:
  9155. // Implicit conversion to a narrower type, but the expression is
  9156. // value-dependent so we can't tell whether it's actually narrowing.
  9157. case NK_Not_Narrowing:
  9158. return false;
  9159. case NK_Constant_Narrowing:
  9160. // Implicit conversion to a narrower type, and the value is not a constant
  9161. // expression.
  9162. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9163. << /*Constant*/ 1
  9164. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  9165. return true;
  9166. case NK_Variable_Narrowing:
  9167. // Implicit conversion to a narrower type, and the value is not a constant
  9168. // expression.
  9169. case NK_Type_Narrowing:
  9170. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9171. << /*Constant*/ 0 << FromType << ToType;
  9172. // TODO: It's not a constant expression, but what if the user intended it
  9173. // to be? Can we produce notes to help them figure out why it isn't?
  9174. return true;
  9175. }
  9176. llvm_unreachable("unhandled case in switch");
  9177. }
  9178. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  9179. ExprResult &LHS,
  9180. ExprResult &RHS,
  9181. SourceLocation Loc) {
  9182. using CCT = ComparisonCategoryType;
  9183. QualType LHSType = LHS.get()->getType();
  9184. QualType RHSType = RHS.get()->getType();
  9185. // Dig out the original argument type and expression before implicit casts
  9186. // were applied. These are the types/expressions we need to check the
  9187. // [expr.spaceship] requirements against.
  9188. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  9189. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  9190. QualType LHSStrippedType = LHSStripped.get()->getType();
  9191. QualType RHSStrippedType = RHSStripped.get()->getType();
  9192. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  9193. // other is not, the program is ill-formed.
  9194. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  9195. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9196. return QualType();
  9197. }
  9198. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  9199. RHSStrippedType->isEnumeralType();
  9200. if (NumEnumArgs == 1) {
  9201. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  9202. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  9203. if (OtherTy->hasFloatingRepresentation()) {
  9204. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9205. return QualType();
  9206. }
  9207. }
  9208. if (NumEnumArgs == 2) {
  9209. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  9210. // type E, the operator yields the result of converting the operands
  9211. // to the underlying type of E and applying <=> to the converted operands.
  9212. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  9213. S.InvalidOperands(Loc, LHS, RHS);
  9214. return QualType();
  9215. }
  9216. QualType IntType =
  9217. LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
  9218. assert(IntType->isArithmeticType());
  9219. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  9220. // promote the boolean type, and all other promotable integer types, to
  9221. // avoid this.
  9222. if (IntType->isPromotableIntegerType())
  9223. IntType = S.Context.getPromotedIntegerType(IntType);
  9224. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  9225. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  9226. LHSType = RHSType = IntType;
  9227. }
  9228. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  9229. // usual arithmetic conversions are applied to the operands.
  9230. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9231. if (LHS.isInvalid() || RHS.isInvalid())
  9232. return QualType();
  9233. if (Type.isNull())
  9234. return S.InvalidOperands(Loc, LHS, RHS);
  9235. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9236. bool HasNarrowing = checkThreeWayNarrowingConversion(
  9237. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  9238. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  9239. RHS.get()->getBeginLoc());
  9240. if (HasNarrowing)
  9241. return QualType();
  9242. assert(!Type.isNull() && "composite type for <=> has not been set");
  9243. auto TypeKind = [&]() {
  9244. if (const ComplexType *CT = Type->getAs<ComplexType>()) {
  9245. if (CT->getElementType()->hasFloatingRepresentation())
  9246. return CCT::WeakEquality;
  9247. return CCT::StrongEquality;
  9248. }
  9249. if (Type->isIntegralOrEnumerationType())
  9250. return CCT::StrongOrdering;
  9251. if (Type->hasFloatingRepresentation())
  9252. return CCT::PartialOrdering;
  9253. llvm_unreachable("other types are unimplemented");
  9254. }();
  9255. return S.CheckComparisonCategoryType(TypeKind, Loc);
  9256. }
  9257. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  9258. ExprResult &RHS,
  9259. SourceLocation Loc,
  9260. BinaryOperatorKind Opc) {
  9261. if (Opc == BO_Cmp)
  9262. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  9263. // C99 6.5.8p3 / C99 6.5.9p4
  9264. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9265. if (LHS.isInvalid() || RHS.isInvalid())
  9266. return QualType();
  9267. if (Type.isNull())
  9268. return S.InvalidOperands(Loc, LHS, RHS);
  9269. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9270. checkEnumComparison(S, Loc, LHS.get(), RHS.get());
  9271. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  9272. return S.InvalidOperands(Loc, LHS, RHS);
  9273. // Check for comparisons of floating point operands using != and ==.
  9274. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  9275. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9276. // The result of comparisons is 'bool' in C++, 'int' in C.
  9277. return S.Context.getLogicalOperationType();
  9278. }
  9279. void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
  9280. if (!NullE.get()->getType()->isAnyPointerType())
  9281. return;
  9282. int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
  9283. if (!E.get()->getType()->isAnyPointerType() &&
  9284. E.get()->isNullPointerConstant(Context,
  9285. Expr::NPC_ValueDependentIsNotNull) ==
  9286. Expr::NPCK_ZeroExpression) {
  9287. if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
  9288. if (CL->getValue() == 0)
  9289. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  9290. << NullValue
  9291. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  9292. NullValue ? "NULL" : "(void *)0");
  9293. } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
  9294. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  9295. QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
  9296. if (T == Context.CharTy)
  9297. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  9298. << NullValue
  9299. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  9300. NullValue ? "NULL" : "(void *)0");
  9301. }
  9302. }
  9303. }
  9304. // C99 6.5.8, C++ [expr.rel]
  9305. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9306. SourceLocation Loc,
  9307. BinaryOperatorKind Opc) {
  9308. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  9309. bool IsThreeWay = Opc == BO_Cmp;
  9310. auto IsAnyPointerType = [](ExprResult E) {
  9311. QualType Ty = E.get()->getType();
  9312. return Ty->isPointerType() || Ty->isMemberPointerType();
  9313. };
  9314. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  9315. // type, array-to-pointer, ..., conversions are performed on both operands to
  9316. // bring them to their composite type.
  9317. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  9318. // any type-related checks.
  9319. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  9320. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  9321. if (LHS.isInvalid())
  9322. return QualType();
  9323. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  9324. if (RHS.isInvalid())
  9325. return QualType();
  9326. } else {
  9327. LHS = DefaultLvalueConversion(LHS.get());
  9328. if (LHS.isInvalid())
  9329. return QualType();
  9330. RHS = DefaultLvalueConversion(RHS.get());
  9331. if (RHS.isInvalid())
  9332. return QualType();
  9333. }
  9334. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
  9335. if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
  9336. CheckPtrComparisonWithNullChar(LHS, RHS);
  9337. CheckPtrComparisonWithNullChar(RHS, LHS);
  9338. }
  9339. // Handle vector comparisons separately.
  9340. if (LHS.get()->getType()->isVectorType() ||
  9341. RHS.get()->getType()->isVectorType())
  9342. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  9343. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9344. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9345. QualType LHSType = LHS.get()->getType();
  9346. QualType RHSType = RHS.get()->getType();
  9347. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  9348. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  9349. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  9350. const Expr::NullPointerConstantKind LHSNullKind =
  9351. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9352. const Expr::NullPointerConstantKind RHSNullKind =
  9353. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9354. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  9355. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  9356. auto computeResultTy = [&]() {
  9357. if (Opc != BO_Cmp)
  9358. return Context.getLogicalOperationType();
  9359. assert(getLangOpts().CPlusPlus);
  9360. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  9361. QualType CompositeTy = LHS.get()->getType();
  9362. assert(!CompositeTy->isReferenceType());
  9363. auto buildResultTy = [&](ComparisonCategoryType Kind) {
  9364. return CheckComparisonCategoryType(Kind, Loc);
  9365. };
  9366. // C++2a [expr.spaceship]p7: If the composite pointer type is a function
  9367. // pointer type, a pointer-to-member type, or std::nullptr_t, the
  9368. // result is of type std::strong_equality
  9369. if (CompositeTy->isFunctionPointerType() ||
  9370. CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
  9371. // FIXME: consider making the function pointer case produce
  9372. // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
  9373. // and direction polls
  9374. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9375. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  9376. // pointer type, p <=> q is of type std::strong_ordering.
  9377. if (CompositeTy->isPointerType()) {
  9378. // P0946R0: Comparisons between a null pointer constant and an object
  9379. // pointer result in std::strong_equality
  9380. if (LHSIsNull != RHSIsNull)
  9381. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9382. return buildResultTy(ComparisonCategoryType::StrongOrdering);
  9383. }
  9384. // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
  9385. // TODO: Extend support for operator<=> to ObjC types.
  9386. return InvalidOperands(Loc, LHS, RHS);
  9387. };
  9388. if (!IsRelational && LHSIsNull != RHSIsNull) {
  9389. bool IsEquality = Opc == BO_EQ;
  9390. if (RHSIsNull)
  9391. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  9392. RHS.get()->getSourceRange());
  9393. else
  9394. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  9395. LHS.get()->getSourceRange());
  9396. }
  9397. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  9398. (RHSType->isIntegerType() && !RHSIsNull)) {
  9399. // Skip normal pointer conversion checks in this case; we have better
  9400. // diagnostics for this below.
  9401. } else if (getLangOpts().CPlusPlus) {
  9402. // Equality comparison of a function pointer to a void pointer is invalid,
  9403. // but we allow it as an extension.
  9404. // FIXME: If we really want to allow this, should it be part of composite
  9405. // pointer type computation so it works in conditionals too?
  9406. if (!IsRelational &&
  9407. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  9408. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  9409. // This is a gcc extension compatibility comparison.
  9410. // In a SFINAE context, we treat this as a hard error to maintain
  9411. // conformance with the C++ standard.
  9412. diagnoseFunctionPointerToVoidComparison(
  9413. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  9414. if (isSFINAEContext())
  9415. return QualType();
  9416. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9417. return computeResultTy();
  9418. }
  9419. // C++ [expr.eq]p2:
  9420. // If at least one operand is a pointer [...] bring them to their
  9421. // composite pointer type.
  9422. // C++ [expr.spaceship]p6
  9423. // If at least one of the operands is of pointer type, [...] bring them
  9424. // to their composite pointer type.
  9425. // C++ [expr.rel]p2:
  9426. // If both operands are pointers, [...] bring them to their composite
  9427. // pointer type.
  9428. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  9429. (IsRelational ? 2 : 1) &&
  9430. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  9431. RHSType->isObjCObjectPointerType()))) {
  9432. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9433. return QualType();
  9434. return computeResultTy();
  9435. }
  9436. } else if (LHSType->isPointerType() &&
  9437. RHSType->isPointerType()) { // C99 6.5.8p2
  9438. // All of the following pointer-related warnings are GCC extensions, except
  9439. // when handling null pointer constants.
  9440. QualType LCanPointeeTy =
  9441. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9442. QualType RCanPointeeTy =
  9443. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9444. // C99 6.5.9p2 and C99 6.5.8p2
  9445. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  9446. RCanPointeeTy.getUnqualifiedType())) {
  9447. // Valid unless a relational comparison of function pointers
  9448. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  9449. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  9450. << LHSType << RHSType << LHS.get()->getSourceRange()
  9451. << RHS.get()->getSourceRange();
  9452. }
  9453. } else if (!IsRelational &&
  9454. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  9455. // Valid unless comparison between non-null pointer and function pointer
  9456. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  9457. && !LHSIsNull && !RHSIsNull)
  9458. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  9459. /*isError*/false);
  9460. } else {
  9461. // Invalid
  9462. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  9463. }
  9464. if (LCanPointeeTy != RCanPointeeTy) {
  9465. // Treat NULL constant as a special case in OpenCL.
  9466. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  9467. const PointerType *LHSPtr = LHSType->getAs<PointerType>();
  9468. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  9469. Diag(Loc,
  9470. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9471. << LHSType << RHSType << 0 /* comparison */
  9472. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9473. }
  9474. }
  9475. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  9476. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  9477. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  9478. : CK_BitCast;
  9479. if (LHSIsNull && !RHSIsNull)
  9480. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  9481. else
  9482. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  9483. }
  9484. return computeResultTy();
  9485. }
  9486. if (getLangOpts().CPlusPlus) {
  9487. // C++ [expr.eq]p4:
  9488. // Two operands of type std::nullptr_t or one operand of type
  9489. // std::nullptr_t and the other a null pointer constant compare equal.
  9490. if (!IsRelational && LHSIsNull && RHSIsNull) {
  9491. if (LHSType->isNullPtrType()) {
  9492. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9493. return computeResultTy();
  9494. }
  9495. if (RHSType->isNullPtrType()) {
  9496. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9497. return computeResultTy();
  9498. }
  9499. }
  9500. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  9501. // These aren't covered by the composite pointer type rules.
  9502. if (!IsRelational && RHSType->isNullPtrType() &&
  9503. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  9504. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9505. return computeResultTy();
  9506. }
  9507. if (!IsRelational && LHSType->isNullPtrType() &&
  9508. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  9509. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9510. return computeResultTy();
  9511. }
  9512. if (IsRelational &&
  9513. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  9514. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  9515. // HACK: Relational comparison of nullptr_t against a pointer type is
  9516. // invalid per DR583, but we allow it within std::less<> and friends,
  9517. // since otherwise common uses of it break.
  9518. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  9519. // friends to have std::nullptr_t overload candidates.
  9520. DeclContext *DC = CurContext;
  9521. if (isa<FunctionDecl>(DC))
  9522. DC = DC->getParent();
  9523. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  9524. if (CTSD->isInStdNamespace() &&
  9525. llvm::StringSwitch<bool>(CTSD->getName())
  9526. .Cases("less", "less_equal", "greater", "greater_equal", true)
  9527. .Default(false)) {
  9528. if (RHSType->isNullPtrType())
  9529. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9530. else
  9531. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9532. return computeResultTy();
  9533. }
  9534. }
  9535. }
  9536. // C++ [expr.eq]p2:
  9537. // If at least one operand is a pointer to member, [...] bring them to
  9538. // their composite pointer type.
  9539. if (!IsRelational &&
  9540. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  9541. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9542. return QualType();
  9543. else
  9544. return computeResultTy();
  9545. }
  9546. }
  9547. // Handle block pointer types.
  9548. if (!IsRelational && LHSType->isBlockPointerType() &&
  9549. RHSType->isBlockPointerType()) {
  9550. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  9551. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  9552. if (!LHSIsNull && !RHSIsNull &&
  9553. !Context.typesAreCompatible(lpointee, rpointee)) {
  9554. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9555. << LHSType << RHSType << LHS.get()->getSourceRange()
  9556. << RHS.get()->getSourceRange();
  9557. }
  9558. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9559. return computeResultTy();
  9560. }
  9561. // Allow block pointers to be compared with null pointer constants.
  9562. if (!IsRelational
  9563. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  9564. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  9565. if (!LHSIsNull && !RHSIsNull) {
  9566. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  9567. ->getPointeeType()->isVoidType())
  9568. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  9569. ->getPointeeType()->isVoidType())))
  9570. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9571. << LHSType << RHSType << LHS.get()->getSourceRange()
  9572. << RHS.get()->getSourceRange();
  9573. }
  9574. if (LHSIsNull && !RHSIsNull)
  9575. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9576. RHSType->isPointerType() ? CK_BitCast
  9577. : CK_AnyPointerToBlockPointerCast);
  9578. else
  9579. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9580. LHSType->isPointerType() ? CK_BitCast
  9581. : CK_AnyPointerToBlockPointerCast);
  9582. return computeResultTy();
  9583. }
  9584. if (LHSType->isObjCObjectPointerType() ||
  9585. RHSType->isObjCObjectPointerType()) {
  9586. const PointerType *LPT = LHSType->getAs<PointerType>();
  9587. const PointerType *RPT = RHSType->getAs<PointerType>();
  9588. if (LPT || RPT) {
  9589. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  9590. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  9591. if (!LPtrToVoid && !RPtrToVoid &&
  9592. !Context.typesAreCompatible(LHSType, RHSType)) {
  9593. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9594. /*isError*/false);
  9595. }
  9596. if (LHSIsNull && !RHSIsNull) {
  9597. Expr *E = LHS.get();
  9598. if (getLangOpts().ObjCAutoRefCount)
  9599. CheckObjCConversion(SourceRange(), RHSType, E,
  9600. CCK_ImplicitConversion);
  9601. LHS = ImpCastExprToType(E, RHSType,
  9602. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9603. }
  9604. else {
  9605. Expr *E = RHS.get();
  9606. if (getLangOpts().ObjCAutoRefCount)
  9607. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  9608. /*Diagnose=*/true,
  9609. /*DiagnoseCFAudited=*/false, Opc);
  9610. RHS = ImpCastExprToType(E, LHSType,
  9611. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9612. }
  9613. return computeResultTy();
  9614. }
  9615. if (LHSType->isObjCObjectPointerType() &&
  9616. RHSType->isObjCObjectPointerType()) {
  9617. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  9618. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9619. /*isError*/false);
  9620. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  9621. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  9622. if (LHSIsNull && !RHSIsNull)
  9623. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9624. else
  9625. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9626. return computeResultTy();
  9627. }
  9628. if (!IsRelational && LHSType->isBlockPointerType() &&
  9629. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  9630. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9631. CK_BlockPointerToObjCPointerCast);
  9632. return computeResultTy();
  9633. } else if (!IsRelational &&
  9634. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  9635. RHSType->isBlockPointerType()) {
  9636. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9637. CK_BlockPointerToObjCPointerCast);
  9638. return computeResultTy();
  9639. }
  9640. }
  9641. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  9642. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  9643. unsigned DiagID = 0;
  9644. bool isError = false;
  9645. if (LangOpts.DebuggerSupport) {
  9646. // Under a debugger, allow the comparison of pointers to integers,
  9647. // since users tend to want to compare addresses.
  9648. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  9649. (RHSIsNull && RHSType->isIntegerType())) {
  9650. if (IsRelational) {
  9651. isError = getLangOpts().CPlusPlus;
  9652. DiagID =
  9653. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  9654. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  9655. }
  9656. } else if (getLangOpts().CPlusPlus) {
  9657. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  9658. isError = true;
  9659. } else if (IsRelational)
  9660. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  9661. else
  9662. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  9663. if (DiagID) {
  9664. Diag(Loc, DiagID)
  9665. << LHSType << RHSType << LHS.get()->getSourceRange()
  9666. << RHS.get()->getSourceRange();
  9667. if (isError)
  9668. return QualType();
  9669. }
  9670. if (LHSType->isIntegerType())
  9671. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9672. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9673. else
  9674. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9675. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9676. return computeResultTy();
  9677. }
  9678. // Handle block pointers.
  9679. if (!IsRelational && RHSIsNull
  9680. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  9681. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9682. return computeResultTy();
  9683. }
  9684. if (!IsRelational && LHSIsNull
  9685. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  9686. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9687. return computeResultTy();
  9688. }
  9689. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  9690. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  9691. return computeResultTy();
  9692. }
  9693. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  9694. return computeResultTy();
  9695. }
  9696. if (LHSIsNull && RHSType->isQueueT()) {
  9697. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9698. return computeResultTy();
  9699. }
  9700. if (LHSType->isQueueT() && RHSIsNull) {
  9701. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9702. return computeResultTy();
  9703. }
  9704. }
  9705. return InvalidOperands(Loc, LHS, RHS);
  9706. }
  9707. // Return a signed ext_vector_type that is of identical size and number of
  9708. // elements. For floating point vectors, return an integer type of identical
  9709. // size and number of elements. In the non ext_vector_type case, search from
  9710. // the largest type to the smallest type to avoid cases where long long == long,
  9711. // where long gets picked over long long.
  9712. QualType Sema::GetSignedVectorType(QualType V) {
  9713. const VectorType *VTy = V->getAs<VectorType>();
  9714. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  9715. if (isa<ExtVectorType>(VTy)) {
  9716. if (TypeSize == Context.getTypeSize(Context.CharTy))
  9717. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  9718. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9719. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  9720. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9721. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  9722. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9723. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  9724. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  9725. "Unhandled vector element size in vector compare");
  9726. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  9727. }
  9728. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  9729. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  9730. VectorType::GenericVector);
  9731. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9732. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  9733. VectorType::GenericVector);
  9734. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9735. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  9736. VectorType::GenericVector);
  9737. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9738. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  9739. VectorType::GenericVector);
  9740. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  9741. "Unhandled vector element size in vector compare");
  9742. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  9743. VectorType::GenericVector);
  9744. }
  9745. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  9746. /// operates on extended vector types. Instead of producing an IntTy result,
  9747. /// like a scalar comparison, a vector comparison produces a vector of integer
  9748. /// types.
  9749. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9750. SourceLocation Loc,
  9751. BinaryOperatorKind Opc) {
  9752. // Check to make sure we're operating on vectors of the same type and width,
  9753. // Allowing one side to be a scalar of element type.
  9754. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  9755. /*AllowBothBool*/true,
  9756. /*AllowBoolConversions*/getLangOpts().ZVector);
  9757. if (vType.isNull())
  9758. return vType;
  9759. QualType LHSType = LHS.get()->getType();
  9760. // If AltiVec, the comparison results in a numeric type, i.e.
  9761. // bool for C++, int for C
  9762. if (getLangOpts().AltiVec &&
  9763. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  9764. return Context.getLogicalOperationType();
  9765. // For non-floating point types, check for self-comparisons of the form
  9766. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9767. // often indicate logic errors in the program.
  9768. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9769. // Check for comparisons of floating point operands using != and ==.
  9770. if (BinaryOperator::isEqualityOp(Opc) &&
  9771. LHSType->hasFloatingRepresentation()) {
  9772. assert(RHS.get()->getType()->hasFloatingRepresentation());
  9773. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9774. }
  9775. // Return a signed type for the vector.
  9776. return GetSignedVectorType(vType);
  9777. }
  9778. static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
  9779. const ExprResult &XorRHS,
  9780. const SourceLocation Loc) {
  9781. // Do not diagnose macros.
  9782. if (Loc.isMacroID())
  9783. return;
  9784. bool Negative = false;
  9785. bool ExplicitPlus = false;
  9786. const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
  9787. const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
  9788. if (!LHSInt)
  9789. return;
  9790. if (!RHSInt) {
  9791. // Check negative literals.
  9792. if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
  9793. UnaryOperatorKind Opc = UO->getOpcode();
  9794. if (Opc != UO_Minus && Opc != UO_Plus)
  9795. return;
  9796. RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
  9797. if (!RHSInt)
  9798. return;
  9799. Negative = (Opc == UO_Minus);
  9800. ExplicitPlus = !Negative;
  9801. } else {
  9802. return;
  9803. }
  9804. }
  9805. const llvm::APInt &LeftSideValue = LHSInt->getValue();
  9806. llvm::APInt RightSideValue = RHSInt->getValue();
  9807. if (LeftSideValue != 2 && LeftSideValue != 10)
  9808. return;
  9809. if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
  9810. return;
  9811. CharSourceRange ExprRange = CharSourceRange::getCharRange(
  9812. LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
  9813. llvm::StringRef ExprStr =
  9814. Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
  9815. CharSourceRange XorRange =
  9816. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  9817. llvm::StringRef XorStr =
  9818. Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
  9819. // Do not diagnose if xor keyword/macro is used.
  9820. if (XorStr == "xor")
  9821. return;
  9822. std::string LHSStr = Lexer::getSourceText(
  9823. CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
  9824. S.getSourceManager(), S.getLangOpts());
  9825. std::string RHSStr = Lexer::getSourceText(
  9826. CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
  9827. S.getSourceManager(), S.getLangOpts());
  9828. if (Negative) {
  9829. RightSideValue = -RightSideValue;
  9830. RHSStr = "-" + RHSStr;
  9831. } else if (ExplicitPlus) {
  9832. RHSStr = "+" + RHSStr;
  9833. }
  9834. StringRef LHSStrRef = LHSStr;
  9835. StringRef RHSStrRef = RHSStr;
  9836. // Do not diagnose literals with digit separators, binary, hexadecimal, octal
  9837. // literals.
  9838. if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
  9839. RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
  9840. LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
  9841. RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
  9842. (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
  9843. (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
  9844. LHSStrRef.find('\'') != StringRef::npos ||
  9845. RHSStrRef.find('\'') != StringRef::npos)
  9846. return;
  9847. bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
  9848. const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
  9849. int64_t RightSideIntValue = RightSideValue.getSExtValue();
  9850. if (LeftSideValue == 2 && RightSideIntValue >= 0) {
  9851. std::string SuggestedExpr = "1 << " + RHSStr;
  9852. bool Overflow = false;
  9853. llvm::APInt One = (LeftSideValue - 1);
  9854. llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
  9855. if (Overflow) {
  9856. if (RightSideIntValue < 64)
  9857. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  9858. << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
  9859. << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
  9860. else if (RightSideIntValue == 64)
  9861. S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
  9862. else
  9863. return;
  9864. } else {
  9865. S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
  9866. << ExprStr << XorValue.toString(10, true) << SuggestedExpr
  9867. << PowValue.toString(10, true)
  9868. << FixItHint::CreateReplacement(
  9869. ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
  9870. }
  9871. S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
  9872. } else if (LeftSideValue == 10) {
  9873. std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
  9874. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  9875. << ExprStr << XorValue.toString(10, true) << SuggestedValue
  9876. << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
  9877. S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
  9878. }
  9879. }
  9880. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9881. SourceLocation Loc) {
  9882. // Ensure that either both operands are of the same vector type, or
  9883. // one operand is of a vector type and the other is of its element type.
  9884. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  9885. /*AllowBothBool*/true,
  9886. /*AllowBoolConversions*/false);
  9887. if (vType.isNull())
  9888. return InvalidOperands(Loc, LHS, RHS);
  9889. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  9890. !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
  9891. return InvalidOperands(Loc, LHS, RHS);
  9892. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  9893. // usage of the logical operators && and || with vectors in C. This
  9894. // check could be notionally dropped.
  9895. if (!getLangOpts().CPlusPlus &&
  9896. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  9897. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  9898. return GetSignedVectorType(LHS.get()->getType());
  9899. }
  9900. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  9901. SourceLocation Loc,
  9902. BinaryOperatorKind Opc) {
  9903. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9904. bool IsCompAssign =
  9905. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  9906. if (LHS.get()->getType()->isVectorType() ||
  9907. RHS.get()->getType()->isVectorType()) {
  9908. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9909. RHS.get()->getType()->hasIntegerRepresentation())
  9910. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9911. /*AllowBothBool*/true,
  9912. /*AllowBoolConversions*/getLangOpts().ZVector);
  9913. return InvalidOperands(Loc, LHS, RHS);
  9914. }
  9915. if (Opc == BO_And)
  9916. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9917. ExprResult LHSResult = LHS, RHSResult = RHS;
  9918. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  9919. IsCompAssign);
  9920. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  9921. return QualType();
  9922. LHS = LHSResult.get();
  9923. RHS = RHSResult.get();
  9924. if (Opc == BO_Xor)
  9925. diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
  9926. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  9927. return compType;
  9928. return InvalidOperands(Loc, LHS, RHS);
  9929. }
  9930. // C99 6.5.[13,14]
  9931. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9932. SourceLocation Loc,
  9933. BinaryOperatorKind Opc) {
  9934. // Check vector operands differently.
  9935. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  9936. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  9937. bool EnumConstantInBoolContext = false;
  9938. for (const ExprResult &HS : {LHS, RHS}) {
  9939. if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
  9940. const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
  9941. if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
  9942. EnumConstantInBoolContext = true;
  9943. }
  9944. }
  9945. if (EnumConstantInBoolContext)
  9946. Diag(Loc, diag::warn_enum_constant_in_bool_context);
  9947. // Diagnose cases where the user write a logical and/or but probably meant a
  9948. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  9949. // is a constant.
  9950. if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
  9951. !LHS.get()->getType()->isBooleanType() &&
  9952. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  9953. // Don't warn in macros or template instantiations.
  9954. !Loc.isMacroID() && !inTemplateInstantiation()) {
  9955. // If the RHS can be constant folded, and if it constant folds to something
  9956. // that isn't 0 or 1 (which indicate a potential logical operation that
  9957. // happened to fold to true/false) then warn.
  9958. // Parens on the RHS are ignored.
  9959. Expr::EvalResult EVResult;
  9960. if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
  9961. llvm::APSInt Result = EVResult.Val.getInt();
  9962. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  9963. !RHS.get()->getExprLoc().isMacroID()) ||
  9964. (Result != 0 && Result != 1)) {
  9965. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  9966. << RHS.get()->getSourceRange()
  9967. << (Opc == BO_LAnd ? "&&" : "||");
  9968. // Suggest replacing the logical operator with the bitwise version
  9969. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  9970. << (Opc == BO_LAnd ? "&" : "|")
  9971. << FixItHint::CreateReplacement(SourceRange(
  9972. Loc, getLocForEndOfToken(Loc)),
  9973. Opc == BO_LAnd ? "&" : "|");
  9974. if (Opc == BO_LAnd)
  9975. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  9976. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  9977. << FixItHint::CreateRemoval(
  9978. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  9979. RHS.get()->getEndLoc()));
  9980. }
  9981. }
  9982. }
  9983. if (!Context.getLangOpts().CPlusPlus) {
  9984. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  9985. // not operate on the built-in scalar and vector float types.
  9986. if (Context.getLangOpts().OpenCL &&
  9987. Context.getLangOpts().OpenCLVersion < 120) {
  9988. if (LHS.get()->getType()->isFloatingType() ||
  9989. RHS.get()->getType()->isFloatingType())
  9990. return InvalidOperands(Loc, LHS, RHS);
  9991. }
  9992. LHS = UsualUnaryConversions(LHS.get());
  9993. if (LHS.isInvalid())
  9994. return QualType();
  9995. RHS = UsualUnaryConversions(RHS.get());
  9996. if (RHS.isInvalid())
  9997. return QualType();
  9998. if (!LHS.get()->getType()->isScalarType() ||
  9999. !RHS.get()->getType()->isScalarType())
  10000. return InvalidOperands(Loc, LHS, RHS);
  10001. return Context.IntTy;
  10002. }
  10003. // The following is safe because we only use this method for
  10004. // non-overloadable operands.
  10005. // C++ [expr.log.and]p1
  10006. // C++ [expr.log.or]p1
  10007. // The operands are both contextually converted to type bool.
  10008. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  10009. if (LHSRes.isInvalid())
  10010. return InvalidOperands(Loc, LHS, RHS);
  10011. LHS = LHSRes;
  10012. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  10013. if (RHSRes.isInvalid())
  10014. return InvalidOperands(Loc, LHS, RHS);
  10015. RHS = RHSRes;
  10016. // C++ [expr.log.and]p2
  10017. // C++ [expr.log.or]p2
  10018. // The result is a bool.
  10019. return Context.BoolTy;
  10020. }
  10021. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  10022. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  10023. if (!ME) return false;
  10024. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  10025. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  10026. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  10027. if (!Base) return false;
  10028. return Base->getMethodDecl() != nullptr;
  10029. }
  10030. /// Is the given expression (which must be 'const') a reference to a
  10031. /// variable which was originally non-const, but which has become
  10032. /// 'const' due to being captured within a block?
  10033. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  10034. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  10035. assert(E->isLValue() && E->getType().isConstQualified());
  10036. E = E->IgnoreParens();
  10037. // Must be a reference to a declaration from an enclosing scope.
  10038. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  10039. if (!DRE) return NCCK_None;
  10040. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  10041. // The declaration must be a variable which is not declared 'const'.
  10042. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  10043. if (!var) return NCCK_None;
  10044. if (var->getType().isConstQualified()) return NCCK_None;
  10045. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  10046. // Decide whether the first capture was for a block or a lambda.
  10047. DeclContext *DC = S.CurContext, *Prev = nullptr;
  10048. // Decide whether the first capture was for a block or a lambda.
  10049. while (DC) {
  10050. // For init-capture, it is possible that the variable belongs to the
  10051. // template pattern of the current context.
  10052. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  10053. if (var->isInitCapture() &&
  10054. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  10055. break;
  10056. if (DC == var->getDeclContext())
  10057. break;
  10058. Prev = DC;
  10059. DC = DC->getParent();
  10060. }
  10061. // Unless we have an init-capture, we've gone one step too far.
  10062. if (!var->isInitCapture())
  10063. DC = Prev;
  10064. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  10065. }
  10066. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  10067. Ty = Ty.getNonReferenceType();
  10068. if (IsDereference && Ty->isPointerType())
  10069. Ty = Ty->getPointeeType();
  10070. return !Ty.isConstQualified();
  10071. }
  10072. // Update err_typecheck_assign_const and note_typecheck_assign_const
  10073. // when this enum is changed.
  10074. enum {
  10075. ConstFunction,
  10076. ConstVariable,
  10077. ConstMember,
  10078. ConstMethod,
  10079. NestedConstMember,
  10080. ConstUnknown, // Keep as last element
  10081. };
  10082. /// Emit the "read-only variable not assignable" error and print notes to give
  10083. /// more information about why the variable is not assignable, such as pointing
  10084. /// to the declaration of a const variable, showing that a method is const, or
  10085. /// that the function is returning a const reference.
  10086. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  10087. SourceLocation Loc) {
  10088. SourceRange ExprRange = E->getSourceRange();
  10089. // Only emit one error on the first const found. All other consts will emit
  10090. // a note to the error.
  10091. bool DiagnosticEmitted = false;
  10092. // Track if the current expression is the result of a dereference, and if the
  10093. // next checked expression is the result of a dereference.
  10094. bool IsDereference = false;
  10095. bool NextIsDereference = false;
  10096. // Loop to process MemberExpr chains.
  10097. while (true) {
  10098. IsDereference = NextIsDereference;
  10099. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  10100. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10101. NextIsDereference = ME->isArrow();
  10102. const ValueDecl *VD = ME->getMemberDecl();
  10103. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  10104. // Mutable fields can be modified even if the class is const.
  10105. if (Field->isMutable()) {
  10106. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  10107. break;
  10108. }
  10109. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  10110. if (!DiagnosticEmitted) {
  10111. S.Diag(Loc, diag::err_typecheck_assign_const)
  10112. << ExprRange << ConstMember << false /*static*/ << Field
  10113. << Field->getType();
  10114. DiagnosticEmitted = true;
  10115. }
  10116. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10117. << ConstMember << false /*static*/ << Field << Field->getType()
  10118. << Field->getSourceRange();
  10119. }
  10120. E = ME->getBase();
  10121. continue;
  10122. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  10123. if (VDecl->getType().isConstQualified()) {
  10124. if (!DiagnosticEmitted) {
  10125. S.Diag(Loc, diag::err_typecheck_assign_const)
  10126. << ExprRange << ConstMember << true /*static*/ << VDecl
  10127. << VDecl->getType();
  10128. DiagnosticEmitted = true;
  10129. }
  10130. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10131. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  10132. << VDecl->getSourceRange();
  10133. }
  10134. // Static fields do not inherit constness from parents.
  10135. break;
  10136. }
  10137. break; // End MemberExpr
  10138. } else if (const ArraySubscriptExpr *ASE =
  10139. dyn_cast<ArraySubscriptExpr>(E)) {
  10140. E = ASE->getBase()->IgnoreParenImpCasts();
  10141. continue;
  10142. } else if (const ExtVectorElementExpr *EVE =
  10143. dyn_cast<ExtVectorElementExpr>(E)) {
  10144. E = EVE->getBase()->IgnoreParenImpCasts();
  10145. continue;
  10146. }
  10147. break;
  10148. }
  10149. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  10150. // Function calls
  10151. const FunctionDecl *FD = CE->getDirectCallee();
  10152. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  10153. if (!DiagnosticEmitted) {
  10154. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  10155. << ConstFunction << FD;
  10156. DiagnosticEmitted = true;
  10157. }
  10158. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  10159. diag::note_typecheck_assign_const)
  10160. << ConstFunction << FD << FD->getReturnType()
  10161. << FD->getReturnTypeSourceRange();
  10162. }
  10163. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10164. // Point to variable declaration.
  10165. if (const ValueDecl *VD = DRE->getDecl()) {
  10166. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  10167. if (!DiagnosticEmitted) {
  10168. S.Diag(Loc, diag::err_typecheck_assign_const)
  10169. << ExprRange << ConstVariable << VD << VD->getType();
  10170. DiagnosticEmitted = true;
  10171. }
  10172. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10173. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  10174. }
  10175. }
  10176. } else if (isa<CXXThisExpr>(E)) {
  10177. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  10178. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  10179. if (MD->isConst()) {
  10180. if (!DiagnosticEmitted) {
  10181. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  10182. << ConstMethod << MD;
  10183. DiagnosticEmitted = true;
  10184. }
  10185. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  10186. << ConstMethod << MD << MD->getSourceRange();
  10187. }
  10188. }
  10189. }
  10190. }
  10191. if (DiagnosticEmitted)
  10192. return;
  10193. // Can't determine a more specific message, so display the generic error.
  10194. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  10195. }
  10196. enum OriginalExprKind {
  10197. OEK_Variable,
  10198. OEK_Member,
  10199. OEK_LValue
  10200. };
  10201. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  10202. const RecordType *Ty,
  10203. SourceLocation Loc, SourceRange Range,
  10204. OriginalExprKind OEK,
  10205. bool &DiagnosticEmitted) {
  10206. std::vector<const RecordType *> RecordTypeList;
  10207. RecordTypeList.push_back(Ty);
  10208. unsigned NextToCheckIndex = 0;
  10209. // We walk the record hierarchy breadth-first to ensure that we print
  10210. // diagnostics in field nesting order.
  10211. while (RecordTypeList.size() > NextToCheckIndex) {
  10212. bool IsNested = NextToCheckIndex > 0;
  10213. for (const FieldDecl *Field :
  10214. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  10215. // First, check every field for constness.
  10216. QualType FieldTy = Field->getType();
  10217. if (FieldTy.isConstQualified()) {
  10218. if (!DiagnosticEmitted) {
  10219. S.Diag(Loc, diag::err_typecheck_assign_const)
  10220. << Range << NestedConstMember << OEK << VD
  10221. << IsNested << Field;
  10222. DiagnosticEmitted = true;
  10223. }
  10224. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  10225. << NestedConstMember << IsNested << Field
  10226. << FieldTy << Field->getSourceRange();
  10227. }
  10228. // Then we append it to the list to check next in order.
  10229. FieldTy = FieldTy.getCanonicalType();
  10230. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  10231. if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
  10232. RecordTypeList.push_back(FieldRecTy);
  10233. }
  10234. }
  10235. ++NextToCheckIndex;
  10236. }
  10237. }
  10238. /// Emit an error for the case where a record we are trying to assign to has a
  10239. /// const-qualified field somewhere in its hierarchy.
  10240. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  10241. SourceLocation Loc) {
  10242. QualType Ty = E->getType();
  10243. assert(Ty->isRecordType() && "lvalue was not record?");
  10244. SourceRange Range = E->getSourceRange();
  10245. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  10246. bool DiagEmitted = false;
  10247. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  10248. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  10249. Range, OEK_Member, DiagEmitted);
  10250. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10251. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  10252. Range, OEK_Variable, DiagEmitted);
  10253. else
  10254. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  10255. Range, OEK_LValue, DiagEmitted);
  10256. if (!DiagEmitted)
  10257. DiagnoseConstAssignment(S, E, Loc);
  10258. }
  10259. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  10260. /// emit an error and return true. If so, return false.
  10261. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  10262. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  10263. S.CheckShadowingDeclModification(E, Loc);
  10264. SourceLocation OrigLoc = Loc;
  10265. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  10266. &Loc);
  10267. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  10268. IsLV = Expr::MLV_InvalidMessageExpression;
  10269. if (IsLV == Expr::MLV_Valid)
  10270. return false;
  10271. unsigned DiagID = 0;
  10272. bool NeedType = false;
  10273. switch (IsLV) { // C99 6.5.16p2
  10274. case Expr::MLV_ConstQualified:
  10275. // Use a specialized diagnostic when we're assigning to an object
  10276. // from an enclosing function or block.
  10277. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  10278. if (NCCK == NCCK_Block)
  10279. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  10280. else
  10281. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  10282. break;
  10283. }
  10284. // In ARC, use some specialized diagnostics for occasions where we
  10285. // infer 'const'. These are always pseudo-strong variables.
  10286. if (S.getLangOpts().ObjCAutoRefCount) {
  10287. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  10288. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  10289. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  10290. // Use the normal diagnostic if it's pseudo-__strong but the
  10291. // user actually wrote 'const'.
  10292. if (var->isARCPseudoStrong() &&
  10293. (!var->getTypeSourceInfo() ||
  10294. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  10295. // There are three pseudo-strong cases:
  10296. // - self
  10297. ObjCMethodDecl *method = S.getCurMethodDecl();
  10298. if (method && var == method->getSelfDecl()) {
  10299. DiagID = method->isClassMethod()
  10300. ? diag::err_typecheck_arc_assign_self_class_method
  10301. : diag::err_typecheck_arc_assign_self;
  10302. // - Objective-C externally_retained attribute.
  10303. } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
  10304. isa<ParmVarDecl>(var)) {
  10305. DiagID = diag::err_typecheck_arc_assign_externally_retained;
  10306. // - fast enumeration variables
  10307. } else {
  10308. DiagID = diag::err_typecheck_arr_assign_enumeration;
  10309. }
  10310. SourceRange Assign;
  10311. if (Loc != OrigLoc)
  10312. Assign = SourceRange(OrigLoc, OrigLoc);
  10313. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10314. // We need to preserve the AST regardless, so migration tool
  10315. // can do its job.
  10316. return false;
  10317. }
  10318. }
  10319. }
  10320. // If none of the special cases above are triggered, then this is a
  10321. // simple const assignment.
  10322. if (DiagID == 0) {
  10323. DiagnoseConstAssignment(S, E, Loc);
  10324. return true;
  10325. }
  10326. break;
  10327. case Expr::MLV_ConstAddrSpace:
  10328. DiagnoseConstAssignment(S, E, Loc);
  10329. return true;
  10330. case Expr::MLV_ConstQualifiedField:
  10331. DiagnoseRecursiveConstFields(S, E, Loc);
  10332. return true;
  10333. case Expr::MLV_ArrayType:
  10334. case Expr::MLV_ArrayTemporary:
  10335. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  10336. NeedType = true;
  10337. break;
  10338. case Expr::MLV_NotObjectType:
  10339. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  10340. NeedType = true;
  10341. break;
  10342. case Expr::MLV_LValueCast:
  10343. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  10344. break;
  10345. case Expr::MLV_Valid:
  10346. llvm_unreachable("did not take early return for MLV_Valid");
  10347. case Expr::MLV_InvalidExpression:
  10348. case Expr::MLV_MemberFunction:
  10349. case Expr::MLV_ClassTemporary:
  10350. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  10351. break;
  10352. case Expr::MLV_IncompleteType:
  10353. case Expr::MLV_IncompleteVoidType:
  10354. return S.RequireCompleteType(Loc, E->getType(),
  10355. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  10356. case Expr::MLV_DuplicateVectorComponents:
  10357. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  10358. break;
  10359. case Expr::MLV_NoSetterProperty:
  10360. llvm_unreachable("readonly properties should be processed differently");
  10361. case Expr::MLV_InvalidMessageExpression:
  10362. DiagID = diag::err_readonly_message_assignment;
  10363. break;
  10364. case Expr::MLV_SubObjCPropertySetting:
  10365. DiagID = diag::err_no_subobject_property_setting;
  10366. break;
  10367. }
  10368. SourceRange Assign;
  10369. if (Loc != OrigLoc)
  10370. Assign = SourceRange(OrigLoc, OrigLoc);
  10371. if (NeedType)
  10372. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  10373. else
  10374. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10375. return true;
  10376. }
  10377. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  10378. SourceLocation Loc,
  10379. Sema &Sema) {
  10380. if (Sema.inTemplateInstantiation())
  10381. return;
  10382. if (Sema.isUnevaluatedContext())
  10383. return;
  10384. if (Loc.isInvalid() || Loc.isMacroID())
  10385. return;
  10386. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  10387. return;
  10388. // C / C++ fields
  10389. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  10390. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  10391. if (ML && MR) {
  10392. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  10393. return;
  10394. const ValueDecl *LHSDecl =
  10395. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  10396. const ValueDecl *RHSDecl =
  10397. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  10398. if (LHSDecl != RHSDecl)
  10399. return;
  10400. if (LHSDecl->getType().isVolatileQualified())
  10401. return;
  10402. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10403. if (RefTy->getPointeeType().isVolatileQualified())
  10404. return;
  10405. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  10406. }
  10407. // Objective-C instance variables
  10408. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  10409. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  10410. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  10411. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  10412. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  10413. if (RL && RR && RL->getDecl() == RR->getDecl())
  10414. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  10415. }
  10416. }
  10417. // C99 6.5.16.1
  10418. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  10419. SourceLocation Loc,
  10420. QualType CompoundType) {
  10421. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  10422. // Verify that LHS is a modifiable lvalue, and emit error if not.
  10423. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  10424. return QualType();
  10425. QualType LHSType = LHSExpr->getType();
  10426. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  10427. CompoundType;
  10428. // OpenCL v1.2 s6.1.1.1 p2:
  10429. // The half data type can only be used to declare a pointer to a buffer that
  10430. // contains half values
  10431. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  10432. LHSType->isHalfType()) {
  10433. Diag(Loc, diag::err_opencl_half_load_store) << 1
  10434. << LHSType.getUnqualifiedType();
  10435. return QualType();
  10436. }
  10437. AssignConvertType ConvTy;
  10438. if (CompoundType.isNull()) {
  10439. Expr *RHSCheck = RHS.get();
  10440. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  10441. QualType LHSTy(LHSType);
  10442. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  10443. if (RHS.isInvalid())
  10444. return QualType();
  10445. // Special case of NSObject attributes on c-style pointer types.
  10446. if (ConvTy == IncompatiblePointer &&
  10447. ((Context.isObjCNSObjectType(LHSType) &&
  10448. RHSType->isObjCObjectPointerType()) ||
  10449. (Context.isObjCNSObjectType(RHSType) &&
  10450. LHSType->isObjCObjectPointerType())))
  10451. ConvTy = Compatible;
  10452. if (ConvTy == Compatible &&
  10453. LHSType->isObjCObjectType())
  10454. Diag(Loc, diag::err_objc_object_assignment)
  10455. << LHSType;
  10456. // If the RHS is a unary plus or minus, check to see if they = and + are
  10457. // right next to each other. If so, the user may have typo'd "x =+ 4"
  10458. // instead of "x += 4".
  10459. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  10460. RHSCheck = ICE->getSubExpr();
  10461. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  10462. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  10463. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  10464. // Only if the two operators are exactly adjacent.
  10465. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  10466. // And there is a space or other character before the subexpr of the
  10467. // unary +/-. We don't want to warn on "x=-1".
  10468. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  10469. UO->getSubExpr()->getBeginLoc().isFileID()) {
  10470. Diag(Loc, diag::warn_not_compound_assign)
  10471. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  10472. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  10473. }
  10474. }
  10475. if (ConvTy == Compatible) {
  10476. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  10477. // Warn about retain cycles where a block captures the LHS, but
  10478. // not if the LHS is a simple variable into which the block is
  10479. // being stored...unless that variable can be captured by reference!
  10480. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  10481. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  10482. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  10483. checkRetainCycles(LHSExpr, RHS.get());
  10484. }
  10485. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  10486. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  10487. // It is safe to assign a weak reference into a strong variable.
  10488. // Although this code can still have problems:
  10489. // id x = self.weakProp;
  10490. // id y = self.weakProp;
  10491. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10492. // paths through the function. This should be revisited if
  10493. // -Wrepeated-use-of-weak is made flow-sensitive.
  10494. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  10495. // variable, which will be valid for the current autorelease scope.
  10496. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10497. RHS.get()->getBeginLoc()))
  10498. getCurFunction()->markSafeWeakUse(RHS.get());
  10499. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  10500. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  10501. }
  10502. }
  10503. } else {
  10504. // Compound assignment "x += y"
  10505. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  10506. }
  10507. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  10508. RHS.get(), AA_Assigning))
  10509. return QualType();
  10510. CheckForNullPointerDereference(*this, LHSExpr);
  10511. // C99 6.5.16p3: The type of an assignment expression is the type of the
  10512. // left operand unless the left operand has qualified type, in which case
  10513. // it is the unqualified version of the type of the left operand.
  10514. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  10515. // is converted to the type of the assignment expression (above).
  10516. // C++ 5.17p1: the type of the assignment expression is that of its left
  10517. // operand.
  10518. return (getLangOpts().CPlusPlus
  10519. ? LHSType : LHSType.getUnqualifiedType());
  10520. }
  10521. // Only ignore explicit casts to void.
  10522. static bool IgnoreCommaOperand(const Expr *E) {
  10523. E = E->IgnoreParens();
  10524. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  10525. if (CE->getCastKind() == CK_ToVoid) {
  10526. return true;
  10527. }
  10528. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  10529. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  10530. CE->getSubExpr()->getType()->isDependentType()) {
  10531. return true;
  10532. }
  10533. }
  10534. return false;
  10535. }
  10536. // Look for instances where it is likely the comma operator is confused with
  10537. // another operator. There is a whitelist of acceptable expressions for the
  10538. // left hand side of the comma operator, otherwise emit a warning.
  10539. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  10540. // No warnings in macros
  10541. if (Loc.isMacroID())
  10542. return;
  10543. // Don't warn in template instantiations.
  10544. if (inTemplateInstantiation())
  10545. return;
  10546. // Scope isn't fine-grained enough to whitelist the specific cases, so
  10547. // instead, skip more than needed, then call back into here with the
  10548. // CommaVisitor in SemaStmt.cpp.
  10549. // The whitelisted locations are the initialization and increment portions
  10550. // of a for loop. The additional checks are on the condition of
  10551. // if statements, do/while loops, and for loops.
  10552. // Differences in scope flags for C89 mode requires the extra logic.
  10553. const unsigned ForIncrementFlags =
  10554. getLangOpts().C99 || getLangOpts().CPlusPlus
  10555. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  10556. : Scope::ContinueScope | Scope::BreakScope;
  10557. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  10558. const unsigned ScopeFlags = getCurScope()->getFlags();
  10559. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  10560. (ScopeFlags & ForInitFlags) == ForInitFlags)
  10561. return;
  10562. // If there are multiple comma operators used together, get the RHS of the
  10563. // of the comma operator as the LHS.
  10564. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  10565. if (BO->getOpcode() != BO_Comma)
  10566. break;
  10567. LHS = BO->getRHS();
  10568. }
  10569. // Only allow some expressions on LHS to not warn.
  10570. if (IgnoreCommaOperand(LHS))
  10571. return;
  10572. Diag(Loc, diag::warn_comma_operator);
  10573. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  10574. << LHS->getSourceRange()
  10575. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  10576. LangOpts.CPlusPlus ? "static_cast<void>("
  10577. : "(void)(")
  10578. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  10579. ")");
  10580. }
  10581. // C99 6.5.17
  10582. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  10583. SourceLocation Loc) {
  10584. LHS = S.CheckPlaceholderExpr(LHS.get());
  10585. RHS = S.CheckPlaceholderExpr(RHS.get());
  10586. if (LHS.isInvalid() || RHS.isInvalid())
  10587. return QualType();
  10588. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  10589. // operands, but not unary promotions.
  10590. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  10591. // So we treat the LHS as a ignored value, and in C++ we allow the
  10592. // containing site to determine what should be done with the RHS.
  10593. LHS = S.IgnoredValueConversions(LHS.get());
  10594. if (LHS.isInvalid())
  10595. return QualType();
  10596. S.DiagnoseUnusedExprResult(LHS.get());
  10597. if (!S.getLangOpts().CPlusPlus) {
  10598. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  10599. if (RHS.isInvalid())
  10600. return QualType();
  10601. if (!RHS.get()->getType()->isVoidType())
  10602. S.RequireCompleteType(Loc, RHS.get()->getType(),
  10603. diag::err_incomplete_type);
  10604. }
  10605. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  10606. S.DiagnoseCommaOperator(LHS.get(), Loc);
  10607. return RHS.get()->getType();
  10608. }
  10609. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  10610. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  10611. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  10612. ExprValueKind &VK,
  10613. ExprObjectKind &OK,
  10614. SourceLocation OpLoc,
  10615. bool IsInc, bool IsPrefix) {
  10616. if (Op->isTypeDependent())
  10617. return S.Context.DependentTy;
  10618. QualType ResType = Op->getType();
  10619. // Atomic types can be used for increment / decrement where the non-atomic
  10620. // versions can, so ignore the _Atomic() specifier for the purpose of
  10621. // checking.
  10622. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  10623. ResType = ResAtomicType->getValueType();
  10624. assert(!ResType.isNull() && "no type for increment/decrement expression");
  10625. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  10626. // Decrement of bool is not allowed.
  10627. if (!IsInc) {
  10628. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  10629. return QualType();
  10630. }
  10631. // Increment of bool sets it to true, but is deprecated.
  10632. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  10633. : diag::warn_increment_bool)
  10634. << Op->getSourceRange();
  10635. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  10636. // Error on enum increments and decrements in C++ mode
  10637. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  10638. return QualType();
  10639. } else if (ResType->isRealType()) {
  10640. // OK!
  10641. } else if (ResType->isPointerType()) {
  10642. // C99 6.5.2.4p2, 6.5.6p2
  10643. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  10644. return QualType();
  10645. } else if (ResType->isObjCObjectPointerType()) {
  10646. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  10647. // Otherwise, we just need a complete type.
  10648. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  10649. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  10650. return QualType();
  10651. } else if (ResType->isAnyComplexType()) {
  10652. // C99 does not support ++/-- on complex types, we allow as an extension.
  10653. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  10654. << ResType << Op->getSourceRange();
  10655. } else if (ResType->isPlaceholderType()) {
  10656. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10657. if (PR.isInvalid()) return QualType();
  10658. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  10659. IsInc, IsPrefix);
  10660. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  10661. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  10662. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  10663. (ResType->getAs<VectorType>()->getVectorKind() !=
  10664. VectorType::AltiVecBool)) {
  10665. // The z vector extensions allow ++ and -- for non-bool vectors.
  10666. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  10667. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  10668. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  10669. } else {
  10670. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  10671. << ResType << int(IsInc) << Op->getSourceRange();
  10672. return QualType();
  10673. }
  10674. // At this point, we know we have a real, complex or pointer type.
  10675. // Now make sure the operand is a modifiable lvalue.
  10676. if (CheckForModifiableLvalue(Op, OpLoc, S))
  10677. return QualType();
  10678. // In C++, a prefix increment is the same type as the operand. Otherwise
  10679. // (in C or with postfix), the increment is the unqualified type of the
  10680. // operand.
  10681. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  10682. VK = VK_LValue;
  10683. OK = Op->getObjectKind();
  10684. return ResType;
  10685. } else {
  10686. VK = VK_RValue;
  10687. return ResType.getUnqualifiedType();
  10688. }
  10689. }
  10690. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  10691. /// This routine allows us to typecheck complex/recursive expressions
  10692. /// where the declaration is needed for type checking. We only need to
  10693. /// handle cases when the expression references a function designator
  10694. /// or is an lvalue. Here are some examples:
  10695. /// - &(x) => x
  10696. /// - &*****f => f for f a function designator.
  10697. /// - &s.xx => s
  10698. /// - &s.zz[1].yy -> s, if zz is an array
  10699. /// - *(x + 1) -> x, if x is an array
  10700. /// - &"123"[2] -> 0
  10701. /// - & __real__ x -> x
  10702. static ValueDecl *getPrimaryDecl(Expr *E) {
  10703. switch (E->getStmtClass()) {
  10704. case Stmt::DeclRefExprClass:
  10705. return cast<DeclRefExpr>(E)->getDecl();
  10706. case Stmt::MemberExprClass:
  10707. // If this is an arrow operator, the address is an offset from
  10708. // the base's value, so the object the base refers to is
  10709. // irrelevant.
  10710. if (cast<MemberExpr>(E)->isArrow())
  10711. return nullptr;
  10712. // Otherwise, the expression refers to a part of the base
  10713. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  10714. case Stmt::ArraySubscriptExprClass: {
  10715. // FIXME: This code shouldn't be necessary! We should catch the implicit
  10716. // promotion of register arrays earlier.
  10717. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  10718. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  10719. if (ICE->getSubExpr()->getType()->isArrayType())
  10720. return getPrimaryDecl(ICE->getSubExpr());
  10721. }
  10722. return nullptr;
  10723. }
  10724. case Stmt::UnaryOperatorClass: {
  10725. UnaryOperator *UO = cast<UnaryOperator>(E);
  10726. switch(UO->getOpcode()) {
  10727. case UO_Real:
  10728. case UO_Imag:
  10729. case UO_Extension:
  10730. return getPrimaryDecl(UO->getSubExpr());
  10731. default:
  10732. return nullptr;
  10733. }
  10734. }
  10735. case Stmt::ParenExprClass:
  10736. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  10737. case Stmt::ImplicitCastExprClass:
  10738. // If the result of an implicit cast is an l-value, we care about
  10739. // the sub-expression; otherwise, the result here doesn't matter.
  10740. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  10741. default:
  10742. return nullptr;
  10743. }
  10744. }
  10745. namespace {
  10746. enum {
  10747. AO_Bit_Field = 0,
  10748. AO_Vector_Element = 1,
  10749. AO_Property_Expansion = 2,
  10750. AO_Register_Variable = 3,
  10751. AO_No_Error = 4
  10752. };
  10753. }
  10754. /// Diagnose invalid operand for address of operations.
  10755. ///
  10756. /// \param Type The type of operand which cannot have its address taken.
  10757. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  10758. Expr *E, unsigned Type) {
  10759. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  10760. }
  10761. /// CheckAddressOfOperand - The operand of & must be either a function
  10762. /// designator or an lvalue designating an object. If it is an lvalue, the
  10763. /// object cannot be declared with storage class register or be a bit field.
  10764. /// Note: The usual conversions are *not* applied to the operand of the &
  10765. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  10766. /// In C++, the operand might be an overloaded function name, in which case
  10767. /// we allow the '&' but retain the overloaded-function type.
  10768. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  10769. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  10770. if (PTy->getKind() == BuiltinType::Overload) {
  10771. Expr *E = OrigOp.get()->IgnoreParens();
  10772. if (!isa<OverloadExpr>(E)) {
  10773. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  10774. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  10775. << OrigOp.get()->getSourceRange();
  10776. return QualType();
  10777. }
  10778. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  10779. if (isa<UnresolvedMemberExpr>(Ovl))
  10780. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  10781. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10782. << OrigOp.get()->getSourceRange();
  10783. return QualType();
  10784. }
  10785. return Context.OverloadTy;
  10786. }
  10787. if (PTy->getKind() == BuiltinType::UnknownAny)
  10788. return Context.UnknownAnyTy;
  10789. if (PTy->getKind() == BuiltinType::BoundMember) {
  10790. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10791. << OrigOp.get()->getSourceRange();
  10792. return QualType();
  10793. }
  10794. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  10795. if (OrigOp.isInvalid()) return QualType();
  10796. }
  10797. if (OrigOp.get()->isTypeDependent())
  10798. return Context.DependentTy;
  10799. assert(!OrigOp.get()->getType()->isPlaceholderType());
  10800. // Make sure to ignore parentheses in subsequent checks
  10801. Expr *op = OrigOp.get()->IgnoreParens();
  10802. // In OpenCL captures for blocks called as lambda functions
  10803. // are located in the private address space. Blocks used in
  10804. // enqueue_kernel can be located in a different address space
  10805. // depending on a vendor implementation. Thus preventing
  10806. // taking an address of the capture to avoid invalid AS casts.
  10807. if (LangOpts.OpenCL) {
  10808. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  10809. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  10810. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  10811. return QualType();
  10812. }
  10813. }
  10814. if (getLangOpts().C99) {
  10815. // Implement C99-only parts of addressof rules.
  10816. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  10817. if (uOp->getOpcode() == UO_Deref)
  10818. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  10819. // (assuming the deref expression is valid).
  10820. return uOp->getSubExpr()->getType();
  10821. }
  10822. // Technically, there should be a check for array subscript
  10823. // expressions here, but the result of one is always an lvalue anyway.
  10824. }
  10825. ValueDecl *dcl = getPrimaryDecl(op);
  10826. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  10827. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10828. op->getBeginLoc()))
  10829. return QualType();
  10830. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  10831. unsigned AddressOfError = AO_No_Error;
  10832. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  10833. bool sfinae = (bool)isSFINAEContext();
  10834. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  10835. : diag::ext_typecheck_addrof_temporary)
  10836. << op->getType() << op->getSourceRange();
  10837. if (sfinae)
  10838. return QualType();
  10839. // Materialize the temporary as an lvalue so that we can take its address.
  10840. OrigOp = op =
  10841. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  10842. } else if (isa<ObjCSelectorExpr>(op)) {
  10843. return Context.getPointerType(op->getType());
  10844. } else if (lval == Expr::LV_MemberFunction) {
  10845. // If it's an instance method, make a member pointer.
  10846. // The expression must have exactly the form &A::foo.
  10847. // If the underlying expression isn't a decl ref, give up.
  10848. if (!isa<DeclRefExpr>(op)) {
  10849. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10850. << OrigOp.get()->getSourceRange();
  10851. return QualType();
  10852. }
  10853. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  10854. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  10855. // The id-expression was parenthesized.
  10856. if (OrigOp.get() != DRE) {
  10857. Diag(OpLoc, diag::err_parens_pointer_member_function)
  10858. << OrigOp.get()->getSourceRange();
  10859. // The method was named without a qualifier.
  10860. } else if (!DRE->getQualifier()) {
  10861. if (MD->getParent()->getName().empty())
  10862. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10863. << op->getSourceRange();
  10864. else {
  10865. SmallString<32> Str;
  10866. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  10867. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10868. << op->getSourceRange()
  10869. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  10870. }
  10871. }
  10872. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  10873. if (isa<CXXDestructorDecl>(MD))
  10874. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  10875. QualType MPTy = Context.getMemberPointerType(
  10876. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  10877. // Under the MS ABI, lock down the inheritance model now.
  10878. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10879. (void)isCompleteType(OpLoc, MPTy);
  10880. return MPTy;
  10881. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  10882. // C99 6.5.3.2p1
  10883. // The operand must be either an l-value or a function designator
  10884. if (!op->getType()->isFunctionType()) {
  10885. // Use a special diagnostic for loads from property references.
  10886. if (isa<PseudoObjectExpr>(op)) {
  10887. AddressOfError = AO_Property_Expansion;
  10888. } else {
  10889. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  10890. << op->getType() << op->getSourceRange();
  10891. return QualType();
  10892. }
  10893. }
  10894. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  10895. // The operand cannot be a bit-field
  10896. AddressOfError = AO_Bit_Field;
  10897. } else if (op->getObjectKind() == OK_VectorComponent) {
  10898. // The operand cannot be an element of a vector
  10899. AddressOfError = AO_Vector_Element;
  10900. } else if (dcl) { // C99 6.5.3.2p1
  10901. // We have an lvalue with a decl. Make sure the decl is not declared
  10902. // with the register storage-class specifier.
  10903. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  10904. // in C++ it is not error to take address of a register
  10905. // variable (c++03 7.1.1P3)
  10906. if (vd->getStorageClass() == SC_Register &&
  10907. !getLangOpts().CPlusPlus) {
  10908. AddressOfError = AO_Register_Variable;
  10909. }
  10910. } else if (isa<MSPropertyDecl>(dcl)) {
  10911. AddressOfError = AO_Property_Expansion;
  10912. } else if (isa<FunctionTemplateDecl>(dcl)) {
  10913. return Context.OverloadTy;
  10914. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  10915. // Okay: we can take the address of a field.
  10916. // Could be a pointer to member, though, if there is an explicit
  10917. // scope qualifier for the class.
  10918. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  10919. DeclContext *Ctx = dcl->getDeclContext();
  10920. if (Ctx && Ctx->isRecord()) {
  10921. if (dcl->getType()->isReferenceType()) {
  10922. Diag(OpLoc,
  10923. diag::err_cannot_form_pointer_to_member_of_reference_type)
  10924. << dcl->getDeclName() << dcl->getType();
  10925. return QualType();
  10926. }
  10927. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  10928. Ctx = Ctx->getParent();
  10929. QualType MPTy = Context.getMemberPointerType(
  10930. op->getType(),
  10931. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  10932. // Under the MS ABI, lock down the inheritance model now.
  10933. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10934. (void)isCompleteType(OpLoc, MPTy);
  10935. return MPTy;
  10936. }
  10937. }
  10938. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  10939. !isa<BindingDecl>(dcl))
  10940. llvm_unreachable("Unknown/unexpected decl type");
  10941. }
  10942. if (AddressOfError != AO_No_Error) {
  10943. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  10944. return QualType();
  10945. }
  10946. if (lval == Expr::LV_IncompleteVoidType) {
  10947. // Taking the address of a void variable is technically illegal, but we
  10948. // allow it in cases which are otherwise valid.
  10949. // Example: "extern void x; void* y = &x;".
  10950. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  10951. }
  10952. // If the operand has type "type", the result has type "pointer to type".
  10953. if (op->getType()->isObjCObjectType())
  10954. return Context.getObjCObjectPointerType(op->getType());
  10955. CheckAddressOfPackedMember(op);
  10956. return Context.getPointerType(op->getType());
  10957. }
  10958. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  10959. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  10960. if (!DRE)
  10961. return;
  10962. const Decl *D = DRE->getDecl();
  10963. if (!D)
  10964. return;
  10965. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  10966. if (!Param)
  10967. return;
  10968. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  10969. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  10970. return;
  10971. if (FunctionScopeInfo *FD = S.getCurFunction())
  10972. if (!FD->ModifiedNonNullParams.count(Param))
  10973. FD->ModifiedNonNullParams.insert(Param);
  10974. }
  10975. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  10976. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  10977. SourceLocation OpLoc) {
  10978. if (Op->isTypeDependent())
  10979. return S.Context.DependentTy;
  10980. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  10981. if (ConvResult.isInvalid())
  10982. return QualType();
  10983. Op = ConvResult.get();
  10984. QualType OpTy = Op->getType();
  10985. QualType Result;
  10986. if (isa<CXXReinterpretCastExpr>(Op)) {
  10987. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  10988. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  10989. Op->getSourceRange());
  10990. }
  10991. if (const PointerType *PT = OpTy->getAs<PointerType>())
  10992. {
  10993. Result = PT->getPointeeType();
  10994. }
  10995. else if (const ObjCObjectPointerType *OPT =
  10996. OpTy->getAs<ObjCObjectPointerType>())
  10997. Result = OPT->getPointeeType();
  10998. else {
  10999. ExprResult PR = S.CheckPlaceholderExpr(Op);
  11000. if (PR.isInvalid()) return QualType();
  11001. if (PR.get() != Op)
  11002. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  11003. }
  11004. if (Result.isNull()) {
  11005. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  11006. << OpTy << Op->getSourceRange();
  11007. return QualType();
  11008. }
  11009. // Note that per both C89 and C99, indirection is always legal, even if Result
  11010. // is an incomplete type or void. It would be possible to warn about
  11011. // dereferencing a void pointer, but it's completely well-defined, and such a
  11012. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  11013. // for pointers to 'void' but is fine for any other pointer type:
  11014. //
  11015. // C++ [expr.unary.op]p1:
  11016. // [...] the expression to which [the unary * operator] is applied shall
  11017. // be a pointer to an object type, or a pointer to a function type
  11018. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  11019. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  11020. << OpTy << Op->getSourceRange();
  11021. // Dereferences are usually l-values...
  11022. VK = VK_LValue;
  11023. // ...except that certain expressions are never l-values in C.
  11024. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  11025. VK = VK_RValue;
  11026. return Result;
  11027. }
  11028. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  11029. BinaryOperatorKind Opc;
  11030. switch (Kind) {
  11031. default: llvm_unreachable("Unknown binop!");
  11032. case tok::periodstar: Opc = BO_PtrMemD; break;
  11033. case tok::arrowstar: Opc = BO_PtrMemI; break;
  11034. case tok::star: Opc = BO_Mul; break;
  11035. case tok::slash: Opc = BO_Div; break;
  11036. case tok::percent: Opc = BO_Rem; break;
  11037. case tok::plus: Opc = BO_Add; break;
  11038. case tok::minus: Opc = BO_Sub; break;
  11039. case tok::lessless: Opc = BO_Shl; break;
  11040. case tok::greatergreater: Opc = BO_Shr; break;
  11041. case tok::lessequal: Opc = BO_LE; break;
  11042. case tok::less: Opc = BO_LT; break;
  11043. case tok::greaterequal: Opc = BO_GE; break;
  11044. case tok::greater: Opc = BO_GT; break;
  11045. case tok::exclaimequal: Opc = BO_NE; break;
  11046. case tok::equalequal: Opc = BO_EQ; break;
  11047. case tok::spaceship: Opc = BO_Cmp; break;
  11048. case tok::amp: Opc = BO_And; break;
  11049. case tok::caret: Opc = BO_Xor; break;
  11050. case tok::pipe: Opc = BO_Or; break;
  11051. case tok::ampamp: Opc = BO_LAnd; break;
  11052. case tok::pipepipe: Opc = BO_LOr; break;
  11053. case tok::equal: Opc = BO_Assign; break;
  11054. case tok::starequal: Opc = BO_MulAssign; break;
  11055. case tok::slashequal: Opc = BO_DivAssign; break;
  11056. case tok::percentequal: Opc = BO_RemAssign; break;
  11057. case tok::plusequal: Opc = BO_AddAssign; break;
  11058. case tok::minusequal: Opc = BO_SubAssign; break;
  11059. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  11060. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  11061. case tok::ampequal: Opc = BO_AndAssign; break;
  11062. case tok::caretequal: Opc = BO_XorAssign; break;
  11063. case tok::pipeequal: Opc = BO_OrAssign; break;
  11064. case tok::comma: Opc = BO_Comma; break;
  11065. }
  11066. return Opc;
  11067. }
  11068. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  11069. tok::TokenKind Kind) {
  11070. UnaryOperatorKind Opc;
  11071. switch (Kind) {
  11072. default: llvm_unreachable("Unknown unary op!");
  11073. case tok::plusplus: Opc = UO_PreInc; break;
  11074. case tok::minusminus: Opc = UO_PreDec; break;
  11075. case tok::amp: Opc = UO_AddrOf; break;
  11076. case tok::star: Opc = UO_Deref; break;
  11077. case tok::plus: Opc = UO_Plus; break;
  11078. case tok::minus: Opc = UO_Minus; break;
  11079. case tok::tilde: Opc = UO_Not; break;
  11080. case tok::exclaim: Opc = UO_LNot; break;
  11081. case tok::kw___real: Opc = UO_Real; break;
  11082. case tok::kw___imag: Opc = UO_Imag; break;
  11083. case tok::kw___extension__: Opc = UO_Extension; break;
  11084. }
  11085. return Opc;
  11086. }
  11087. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  11088. /// This warning suppressed in the event of macro expansions.
  11089. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  11090. SourceLocation OpLoc, bool IsBuiltin) {
  11091. if (S.inTemplateInstantiation())
  11092. return;
  11093. if (S.isUnevaluatedContext())
  11094. return;
  11095. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  11096. return;
  11097. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  11098. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  11099. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  11100. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  11101. if (!LHSDeclRef || !RHSDeclRef ||
  11102. LHSDeclRef->getLocation().isMacroID() ||
  11103. RHSDeclRef->getLocation().isMacroID())
  11104. return;
  11105. const ValueDecl *LHSDecl =
  11106. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  11107. const ValueDecl *RHSDecl =
  11108. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  11109. if (LHSDecl != RHSDecl)
  11110. return;
  11111. if (LHSDecl->getType().isVolatileQualified())
  11112. return;
  11113. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  11114. if (RefTy->getPointeeType().isVolatileQualified())
  11115. return;
  11116. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  11117. : diag::warn_self_assignment_overloaded)
  11118. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  11119. << RHSExpr->getSourceRange();
  11120. }
  11121. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  11122. /// is usually indicative of introspection within the Objective-C pointer.
  11123. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  11124. SourceLocation OpLoc) {
  11125. if (!S.getLangOpts().ObjC)
  11126. return;
  11127. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  11128. const Expr *LHS = L.get();
  11129. const Expr *RHS = R.get();
  11130. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  11131. ObjCPointerExpr = LHS;
  11132. OtherExpr = RHS;
  11133. }
  11134. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  11135. ObjCPointerExpr = RHS;
  11136. OtherExpr = LHS;
  11137. }
  11138. // This warning is deliberately made very specific to reduce false
  11139. // positives with logic that uses '&' for hashing. This logic mainly
  11140. // looks for code trying to introspect into tagged pointers, which
  11141. // code should generally never do.
  11142. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  11143. unsigned Diag = diag::warn_objc_pointer_masking;
  11144. // Determine if we are introspecting the result of performSelectorXXX.
  11145. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  11146. // Special case messages to -performSelector and friends, which
  11147. // can return non-pointer values boxed in a pointer value.
  11148. // Some clients may wish to silence warnings in this subcase.
  11149. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  11150. Selector S = ME->getSelector();
  11151. StringRef SelArg0 = S.getNameForSlot(0);
  11152. if (SelArg0.startswith("performSelector"))
  11153. Diag = diag::warn_objc_pointer_masking_performSelector;
  11154. }
  11155. S.Diag(OpLoc, Diag)
  11156. << ObjCPointerExpr->getSourceRange();
  11157. }
  11158. }
  11159. static NamedDecl *getDeclFromExpr(Expr *E) {
  11160. if (!E)
  11161. return nullptr;
  11162. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  11163. return DRE->getDecl();
  11164. if (auto *ME = dyn_cast<MemberExpr>(E))
  11165. return ME->getMemberDecl();
  11166. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  11167. return IRE->getDecl();
  11168. return nullptr;
  11169. }
  11170. // This helper function promotes a binary operator's operands (which are of a
  11171. // half vector type) to a vector of floats and then truncates the result to
  11172. // a vector of either half or short.
  11173. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  11174. BinaryOperatorKind Opc, QualType ResultTy,
  11175. ExprValueKind VK, ExprObjectKind OK,
  11176. bool IsCompAssign, SourceLocation OpLoc,
  11177. FPOptions FPFeatures) {
  11178. auto &Context = S.getASTContext();
  11179. assert((isVector(ResultTy, Context.HalfTy) ||
  11180. isVector(ResultTy, Context.ShortTy)) &&
  11181. "Result must be a vector of half or short");
  11182. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  11183. isVector(RHS.get()->getType(), Context.HalfTy) &&
  11184. "both operands expected to be a half vector");
  11185. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  11186. QualType BinOpResTy = RHS.get()->getType();
  11187. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  11188. // change BinOpResTy to a vector of ints.
  11189. if (isVector(ResultTy, Context.ShortTy))
  11190. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  11191. if (IsCompAssign)
  11192. return new (Context) CompoundAssignOperator(
  11193. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  11194. OpLoc, FPFeatures);
  11195. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  11196. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  11197. VK, OK, OpLoc, FPFeatures);
  11198. return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
  11199. }
  11200. static std::pair<ExprResult, ExprResult>
  11201. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  11202. Expr *RHSExpr) {
  11203. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11204. if (!S.getLangOpts().CPlusPlus) {
  11205. // C cannot handle TypoExpr nodes on either side of a binop because it
  11206. // doesn't handle dependent types properly, so make sure any TypoExprs have
  11207. // been dealt with before checking the operands.
  11208. LHS = S.CorrectDelayedTyposInExpr(LHS);
  11209. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  11210. if (Opc != BO_Assign)
  11211. return ExprResult(E);
  11212. // Avoid correcting the RHS to the same Expr as the LHS.
  11213. Decl *D = getDeclFromExpr(E);
  11214. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  11215. });
  11216. }
  11217. return std::make_pair(LHS, RHS);
  11218. }
  11219. /// Returns true if conversion between vectors of halfs and vectors of floats
  11220. /// is needed.
  11221. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  11222. QualType SrcType) {
  11223. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  11224. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  11225. isVector(SrcType, Ctx.HalfTy);
  11226. }
  11227. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  11228. /// operator @p Opc at location @c TokLoc. This routine only supports
  11229. /// built-in operations; ActOnBinOp handles overloaded operators.
  11230. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  11231. BinaryOperatorKind Opc,
  11232. Expr *LHSExpr, Expr *RHSExpr) {
  11233. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  11234. // The syntax only allows initializer lists on the RHS of assignment,
  11235. // so we don't need to worry about accepting invalid code for
  11236. // non-assignment operators.
  11237. // C++11 5.17p9:
  11238. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  11239. // of x = {} is x = T().
  11240. InitializationKind Kind = InitializationKind::CreateDirectList(
  11241. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11242. InitializedEntity Entity =
  11243. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  11244. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  11245. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  11246. if (Init.isInvalid())
  11247. return Init;
  11248. RHSExpr = Init.get();
  11249. }
  11250. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11251. QualType ResultTy; // Result type of the binary operator.
  11252. // The following two variables are used for compound assignment operators
  11253. QualType CompLHSTy; // Type of LHS after promotions for computation
  11254. QualType CompResultTy; // Type of computation result
  11255. ExprValueKind VK = VK_RValue;
  11256. ExprObjectKind OK = OK_Ordinary;
  11257. bool ConvertHalfVec = false;
  11258. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11259. if (!LHS.isUsable() || !RHS.isUsable())
  11260. return ExprError();
  11261. if (getLangOpts().OpenCL) {
  11262. QualType LHSTy = LHSExpr->getType();
  11263. QualType RHSTy = RHSExpr->getType();
  11264. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  11265. // the ATOMIC_VAR_INIT macro.
  11266. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  11267. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11268. if (BO_Assign == Opc)
  11269. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  11270. else
  11271. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11272. return ExprError();
  11273. }
  11274. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11275. // only with a builtin functions and therefore should be disallowed here.
  11276. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  11277. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  11278. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  11279. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  11280. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11281. return ExprError();
  11282. }
  11283. }
  11284. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11285. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11286. if (Opc != BO_Assign && Opc != BO_Comma) {
  11287. checkOpenMPDeviceExpr(LHSExpr);
  11288. checkOpenMPDeviceExpr(RHSExpr);
  11289. }
  11290. }
  11291. switch (Opc) {
  11292. case BO_Assign:
  11293. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  11294. if (getLangOpts().CPlusPlus &&
  11295. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  11296. VK = LHS.get()->getValueKind();
  11297. OK = LHS.get()->getObjectKind();
  11298. }
  11299. if (!ResultTy.isNull()) {
  11300. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11301. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  11302. // Avoid copying a block to the heap if the block is assigned to a local
  11303. // auto variable that is declared in the same scope as the block. This
  11304. // optimization is unsafe if the local variable is declared in an outer
  11305. // scope. For example:
  11306. //
  11307. // BlockTy b;
  11308. // {
  11309. // b = ^{...};
  11310. // }
  11311. // // It is unsafe to invoke the block here if it wasn't copied to the
  11312. // // heap.
  11313. // b();
  11314. if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
  11315. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
  11316. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  11317. if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
  11318. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  11319. if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11320. checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
  11321. NTCUC_Assignment, NTCUK_Copy);
  11322. }
  11323. RecordModifiableNonNullParam(*this, LHS.get());
  11324. break;
  11325. case BO_PtrMemD:
  11326. case BO_PtrMemI:
  11327. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  11328. Opc == BO_PtrMemI);
  11329. break;
  11330. case BO_Mul:
  11331. case BO_Div:
  11332. ConvertHalfVec = true;
  11333. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  11334. Opc == BO_Div);
  11335. break;
  11336. case BO_Rem:
  11337. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  11338. break;
  11339. case BO_Add:
  11340. ConvertHalfVec = true;
  11341. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  11342. break;
  11343. case BO_Sub:
  11344. ConvertHalfVec = true;
  11345. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  11346. break;
  11347. case BO_Shl:
  11348. case BO_Shr:
  11349. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  11350. break;
  11351. case BO_LE:
  11352. case BO_LT:
  11353. case BO_GE:
  11354. case BO_GT:
  11355. ConvertHalfVec = true;
  11356. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11357. break;
  11358. case BO_EQ:
  11359. case BO_NE:
  11360. ConvertHalfVec = true;
  11361. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11362. break;
  11363. case BO_Cmp:
  11364. ConvertHalfVec = true;
  11365. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11366. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  11367. break;
  11368. case BO_And:
  11369. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  11370. LLVM_FALLTHROUGH;
  11371. case BO_Xor:
  11372. case BO_Or:
  11373. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11374. break;
  11375. case BO_LAnd:
  11376. case BO_LOr:
  11377. ConvertHalfVec = true;
  11378. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  11379. break;
  11380. case BO_MulAssign:
  11381. case BO_DivAssign:
  11382. ConvertHalfVec = true;
  11383. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  11384. Opc == BO_DivAssign);
  11385. CompLHSTy = CompResultTy;
  11386. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11387. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11388. break;
  11389. case BO_RemAssign:
  11390. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  11391. CompLHSTy = CompResultTy;
  11392. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11393. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11394. break;
  11395. case BO_AddAssign:
  11396. ConvertHalfVec = true;
  11397. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  11398. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11399. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11400. break;
  11401. case BO_SubAssign:
  11402. ConvertHalfVec = true;
  11403. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  11404. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11405. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11406. break;
  11407. case BO_ShlAssign:
  11408. case BO_ShrAssign:
  11409. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  11410. CompLHSTy = CompResultTy;
  11411. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11412. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11413. break;
  11414. case BO_AndAssign:
  11415. case BO_OrAssign: // fallthrough
  11416. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11417. LLVM_FALLTHROUGH;
  11418. case BO_XorAssign:
  11419. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11420. CompLHSTy = CompResultTy;
  11421. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11422. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11423. break;
  11424. case BO_Comma:
  11425. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  11426. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  11427. VK = RHS.get()->getValueKind();
  11428. OK = RHS.get()->getObjectKind();
  11429. }
  11430. break;
  11431. }
  11432. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  11433. return ExprError();
  11434. // Some of the binary operations require promoting operands of half vector to
  11435. // float vectors and truncating the result back to half vector. For now, we do
  11436. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  11437. // arm64).
  11438. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  11439. isVector(LHS.get()->getType(), Context.HalfTy) &&
  11440. "both sides are half vectors or neither sides are");
  11441. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  11442. LHS.get()->getType());
  11443. // Check for array bounds violations for both sides of the BinaryOperator
  11444. CheckArrayAccess(LHS.get());
  11445. CheckArrayAccess(RHS.get());
  11446. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  11447. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  11448. &Context.Idents.get("object_setClass"),
  11449. SourceLocation(), LookupOrdinaryName);
  11450. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  11451. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  11452. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  11453. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  11454. "object_setClass(")
  11455. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  11456. ",")
  11457. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  11458. }
  11459. else
  11460. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  11461. }
  11462. else if (const ObjCIvarRefExpr *OIRE =
  11463. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  11464. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  11465. // Opc is not a compound assignment if CompResultTy is null.
  11466. if (CompResultTy.isNull()) {
  11467. if (ConvertHalfVec)
  11468. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  11469. OpLoc, FPFeatures);
  11470. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  11471. OK, OpLoc, FPFeatures);
  11472. }
  11473. // Handle compound assignments.
  11474. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  11475. OK_ObjCProperty) {
  11476. VK = VK_LValue;
  11477. OK = LHS.get()->getObjectKind();
  11478. }
  11479. if (ConvertHalfVec)
  11480. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  11481. OpLoc, FPFeatures);
  11482. return new (Context) CompoundAssignOperator(
  11483. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  11484. OpLoc, FPFeatures);
  11485. }
  11486. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  11487. /// operators are mixed in a way that suggests that the programmer forgot that
  11488. /// comparison operators have higher precedence. The most typical example of
  11489. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  11490. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  11491. SourceLocation OpLoc, Expr *LHSExpr,
  11492. Expr *RHSExpr) {
  11493. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  11494. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  11495. // Check that one of the sides is a comparison operator and the other isn't.
  11496. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  11497. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  11498. if (isLeftComp == isRightComp)
  11499. return;
  11500. // Bitwise operations are sometimes used as eager logical ops.
  11501. // Don't diagnose this.
  11502. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  11503. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  11504. if (isLeftBitwise || isRightBitwise)
  11505. return;
  11506. SourceRange DiagRange = isLeftComp
  11507. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  11508. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  11509. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  11510. SourceRange ParensRange =
  11511. isLeftComp
  11512. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  11513. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  11514. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  11515. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  11516. SuggestParentheses(Self, OpLoc,
  11517. Self.PDiag(diag::note_precedence_silence) << OpStr,
  11518. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  11519. SuggestParentheses(Self, OpLoc,
  11520. Self.PDiag(diag::note_precedence_bitwise_first)
  11521. << BinaryOperator::getOpcodeStr(Opc),
  11522. ParensRange);
  11523. }
  11524. /// It accepts a '&&' expr that is inside a '||' one.
  11525. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  11526. /// in parentheses.
  11527. static void
  11528. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  11529. BinaryOperator *Bop) {
  11530. assert(Bop->getOpcode() == BO_LAnd);
  11531. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  11532. << Bop->getSourceRange() << OpLoc;
  11533. SuggestParentheses(Self, Bop->getOperatorLoc(),
  11534. Self.PDiag(diag::note_precedence_silence)
  11535. << Bop->getOpcodeStr(),
  11536. Bop->getSourceRange());
  11537. }
  11538. /// Returns true if the given expression can be evaluated as a constant
  11539. /// 'true'.
  11540. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  11541. bool Res;
  11542. return !E->isValueDependent() &&
  11543. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  11544. }
  11545. /// Returns true if the given expression can be evaluated as a constant
  11546. /// 'false'.
  11547. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  11548. bool Res;
  11549. return !E->isValueDependent() &&
  11550. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  11551. }
  11552. /// Look for '&&' in the left hand of a '||' expr.
  11553. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  11554. Expr *LHSExpr, Expr *RHSExpr) {
  11555. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  11556. if (Bop->getOpcode() == BO_LAnd) {
  11557. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  11558. if (EvaluatesAsFalse(S, RHSExpr))
  11559. return;
  11560. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  11561. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  11562. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11563. } else if (Bop->getOpcode() == BO_LOr) {
  11564. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  11565. // If it's "a || b && 1 || c" we didn't warn earlier for
  11566. // "a || b && 1", but warn now.
  11567. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  11568. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  11569. }
  11570. }
  11571. }
  11572. }
  11573. /// Look for '&&' in the right hand of a '||' expr.
  11574. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  11575. Expr *LHSExpr, Expr *RHSExpr) {
  11576. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  11577. if (Bop->getOpcode() == BO_LAnd) {
  11578. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  11579. if (EvaluatesAsFalse(S, LHSExpr))
  11580. return;
  11581. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  11582. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  11583. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11584. }
  11585. }
  11586. }
  11587. /// Look for bitwise op in the left or right hand of a bitwise op with
  11588. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  11589. /// the '&' expression in parentheses.
  11590. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  11591. SourceLocation OpLoc, Expr *SubExpr) {
  11592. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11593. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  11594. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  11595. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  11596. << Bop->getSourceRange() << OpLoc;
  11597. SuggestParentheses(S, Bop->getOperatorLoc(),
  11598. S.PDiag(diag::note_precedence_silence)
  11599. << Bop->getOpcodeStr(),
  11600. Bop->getSourceRange());
  11601. }
  11602. }
  11603. }
  11604. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  11605. Expr *SubExpr, StringRef Shift) {
  11606. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11607. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  11608. StringRef Op = Bop->getOpcodeStr();
  11609. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  11610. << Bop->getSourceRange() << OpLoc << Shift << Op;
  11611. SuggestParentheses(S, Bop->getOperatorLoc(),
  11612. S.PDiag(diag::note_precedence_silence) << Op,
  11613. Bop->getSourceRange());
  11614. }
  11615. }
  11616. }
  11617. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  11618. Expr *LHSExpr, Expr *RHSExpr) {
  11619. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  11620. if (!OCE)
  11621. return;
  11622. FunctionDecl *FD = OCE->getDirectCallee();
  11623. if (!FD || !FD->isOverloadedOperator())
  11624. return;
  11625. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  11626. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  11627. return;
  11628. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  11629. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  11630. << (Kind == OO_LessLess);
  11631. SuggestParentheses(S, OCE->getOperatorLoc(),
  11632. S.PDiag(diag::note_precedence_silence)
  11633. << (Kind == OO_LessLess ? "<<" : ">>"),
  11634. OCE->getSourceRange());
  11635. SuggestParentheses(
  11636. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  11637. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  11638. }
  11639. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  11640. /// precedence.
  11641. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  11642. SourceLocation OpLoc, Expr *LHSExpr,
  11643. Expr *RHSExpr){
  11644. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  11645. if (BinaryOperator::isBitwiseOp(Opc))
  11646. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  11647. // Diagnose "arg1 & arg2 | arg3"
  11648. if ((Opc == BO_Or || Opc == BO_Xor) &&
  11649. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11650. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  11651. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  11652. }
  11653. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  11654. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  11655. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11656. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  11657. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  11658. }
  11659. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  11660. || Opc == BO_Shr) {
  11661. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  11662. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  11663. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  11664. }
  11665. // Warn on overloaded shift operators and comparisons, such as:
  11666. // cout << 5 == 4;
  11667. if (BinaryOperator::isComparisonOp(Opc))
  11668. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  11669. }
  11670. // Binary Operators. 'Tok' is the token for the operator.
  11671. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  11672. tok::TokenKind Kind,
  11673. Expr *LHSExpr, Expr *RHSExpr) {
  11674. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  11675. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  11676. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  11677. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  11678. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  11679. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  11680. }
  11681. /// Build an overloaded binary operator expression in the given scope.
  11682. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  11683. BinaryOperatorKind Opc,
  11684. Expr *LHS, Expr *RHS) {
  11685. switch (Opc) {
  11686. case BO_Assign:
  11687. case BO_DivAssign:
  11688. case BO_RemAssign:
  11689. case BO_SubAssign:
  11690. case BO_AndAssign:
  11691. case BO_OrAssign:
  11692. case BO_XorAssign:
  11693. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  11694. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  11695. break;
  11696. default:
  11697. break;
  11698. }
  11699. // Find all of the overloaded operators visible from this
  11700. // point. We perform both an operator-name lookup from the local
  11701. // scope and an argument-dependent lookup based on the types of
  11702. // the arguments.
  11703. UnresolvedSet<16> Functions;
  11704. OverloadedOperatorKind OverOp
  11705. = BinaryOperator::getOverloadedOperator(Opc);
  11706. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  11707. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  11708. RHS->getType(), Functions);
  11709. // Build the (potentially-overloaded, potentially-dependent)
  11710. // binary operation.
  11711. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  11712. }
  11713. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  11714. BinaryOperatorKind Opc,
  11715. Expr *LHSExpr, Expr *RHSExpr) {
  11716. ExprResult LHS, RHS;
  11717. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11718. if (!LHS.isUsable() || !RHS.isUsable())
  11719. return ExprError();
  11720. LHSExpr = LHS.get();
  11721. RHSExpr = RHS.get();
  11722. // We want to end up calling one of checkPseudoObjectAssignment
  11723. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  11724. // both expressions are overloadable or either is type-dependent),
  11725. // or CreateBuiltinBinOp (in any other case). We also want to get
  11726. // any placeholder types out of the way.
  11727. // Handle pseudo-objects in the LHS.
  11728. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  11729. // Assignments with a pseudo-object l-value need special analysis.
  11730. if (pty->getKind() == BuiltinType::PseudoObject &&
  11731. BinaryOperator::isAssignmentOp(Opc))
  11732. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  11733. // Don't resolve overloads if the other type is overloadable.
  11734. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  11735. // We can't actually test that if we still have a placeholder,
  11736. // though. Fortunately, none of the exceptions we see in that
  11737. // code below are valid when the LHS is an overload set. Note
  11738. // that an overload set can be dependently-typed, but it never
  11739. // instantiates to having an overloadable type.
  11740. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11741. if (resolvedRHS.isInvalid()) return ExprError();
  11742. RHSExpr = resolvedRHS.get();
  11743. if (RHSExpr->isTypeDependent() ||
  11744. RHSExpr->getType()->isOverloadableType())
  11745. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11746. }
  11747. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  11748. // template, diagnose the missing 'template' keyword instead of diagnosing
  11749. // an invalid use of a bound member function.
  11750. //
  11751. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  11752. // to C++1z [over.over]/1.4, but we already checked for that case above.
  11753. if (Opc == BO_LT && inTemplateInstantiation() &&
  11754. (pty->getKind() == BuiltinType::BoundMember ||
  11755. pty->getKind() == BuiltinType::Overload)) {
  11756. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  11757. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  11758. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  11759. return isa<FunctionTemplateDecl>(ND);
  11760. })) {
  11761. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  11762. : OE->getNameLoc(),
  11763. diag::err_template_kw_missing)
  11764. << OE->getName().getAsString() << "";
  11765. return ExprError();
  11766. }
  11767. }
  11768. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  11769. if (LHS.isInvalid()) return ExprError();
  11770. LHSExpr = LHS.get();
  11771. }
  11772. // Handle pseudo-objects in the RHS.
  11773. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  11774. // An overload in the RHS can potentially be resolved by the type
  11775. // being assigned to.
  11776. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  11777. if (getLangOpts().CPlusPlus &&
  11778. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  11779. LHSExpr->getType()->isOverloadableType()))
  11780. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11781. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11782. }
  11783. // Don't resolve overloads if the other type is overloadable.
  11784. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  11785. LHSExpr->getType()->isOverloadableType())
  11786. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11787. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11788. if (!resolvedRHS.isUsable()) return ExprError();
  11789. RHSExpr = resolvedRHS.get();
  11790. }
  11791. if (getLangOpts().CPlusPlus) {
  11792. // If either expression is type-dependent, always build an
  11793. // overloaded op.
  11794. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  11795. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11796. // Otherwise, build an overloaded op if either expression has an
  11797. // overloadable type.
  11798. if (LHSExpr->getType()->isOverloadableType() ||
  11799. RHSExpr->getType()->isOverloadableType())
  11800. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11801. }
  11802. // Build a built-in binary operation.
  11803. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11804. }
  11805. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  11806. if (T.isNull() || T->isDependentType())
  11807. return false;
  11808. if (!T->isPromotableIntegerType())
  11809. return true;
  11810. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  11811. }
  11812. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  11813. UnaryOperatorKind Opc,
  11814. Expr *InputExpr) {
  11815. ExprResult Input = InputExpr;
  11816. ExprValueKind VK = VK_RValue;
  11817. ExprObjectKind OK = OK_Ordinary;
  11818. QualType resultType;
  11819. bool CanOverflow = false;
  11820. bool ConvertHalfVec = false;
  11821. if (getLangOpts().OpenCL) {
  11822. QualType Ty = InputExpr->getType();
  11823. // The only legal unary operation for atomics is '&'.
  11824. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  11825. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11826. // only with a builtin functions and therefore should be disallowed here.
  11827. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  11828. || Ty->isBlockPointerType())) {
  11829. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11830. << InputExpr->getType()
  11831. << Input.get()->getSourceRange());
  11832. }
  11833. }
  11834. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11835. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11836. if (UnaryOperator::isIncrementDecrementOp(Opc) ||
  11837. UnaryOperator::isArithmeticOp(Opc))
  11838. checkOpenMPDeviceExpr(InputExpr);
  11839. }
  11840. switch (Opc) {
  11841. case UO_PreInc:
  11842. case UO_PreDec:
  11843. case UO_PostInc:
  11844. case UO_PostDec:
  11845. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  11846. OpLoc,
  11847. Opc == UO_PreInc ||
  11848. Opc == UO_PostInc,
  11849. Opc == UO_PreInc ||
  11850. Opc == UO_PreDec);
  11851. CanOverflow = isOverflowingIntegerType(Context, resultType);
  11852. break;
  11853. case UO_AddrOf:
  11854. resultType = CheckAddressOfOperand(Input, OpLoc);
  11855. CheckAddressOfNoDeref(InputExpr);
  11856. RecordModifiableNonNullParam(*this, InputExpr);
  11857. break;
  11858. case UO_Deref: {
  11859. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11860. if (Input.isInvalid()) return ExprError();
  11861. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  11862. break;
  11863. }
  11864. case UO_Plus:
  11865. case UO_Minus:
  11866. CanOverflow = Opc == UO_Minus &&
  11867. isOverflowingIntegerType(Context, Input.get()->getType());
  11868. Input = UsualUnaryConversions(Input.get());
  11869. if (Input.isInvalid()) return ExprError();
  11870. // Unary plus and minus require promoting an operand of half vector to a
  11871. // float vector and truncating the result back to a half vector. For now, we
  11872. // do this only when HalfArgsAndReturns is set (that is, when the target is
  11873. // arm or arm64).
  11874. ConvertHalfVec =
  11875. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  11876. // If the operand is a half vector, promote it to a float vector.
  11877. if (ConvertHalfVec)
  11878. Input = convertVector(Input.get(), Context.FloatTy, *this);
  11879. resultType = Input.get()->getType();
  11880. if (resultType->isDependentType())
  11881. break;
  11882. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  11883. break;
  11884. else if (resultType->isVectorType() &&
  11885. // The z vector extensions don't allow + or - with bool vectors.
  11886. (!Context.getLangOpts().ZVector ||
  11887. resultType->getAs<VectorType>()->getVectorKind() !=
  11888. VectorType::AltiVecBool))
  11889. break;
  11890. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  11891. Opc == UO_Plus &&
  11892. resultType->isPointerType())
  11893. break;
  11894. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11895. << resultType << Input.get()->getSourceRange());
  11896. case UO_Not: // bitwise complement
  11897. Input = UsualUnaryConversions(Input.get());
  11898. if (Input.isInvalid())
  11899. return ExprError();
  11900. resultType = Input.get()->getType();
  11901. if (resultType->isDependentType())
  11902. break;
  11903. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  11904. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  11905. // C99 does not support '~' for complex conjugation.
  11906. Diag(OpLoc, diag::ext_integer_complement_complex)
  11907. << resultType << Input.get()->getSourceRange();
  11908. else if (resultType->hasIntegerRepresentation())
  11909. break;
  11910. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  11911. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  11912. // on vector float types.
  11913. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11914. if (!T->isIntegerType())
  11915. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11916. << resultType << Input.get()->getSourceRange());
  11917. } else {
  11918. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11919. << resultType << Input.get()->getSourceRange());
  11920. }
  11921. break;
  11922. case UO_LNot: // logical negation
  11923. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  11924. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11925. if (Input.isInvalid()) return ExprError();
  11926. resultType = Input.get()->getType();
  11927. // Though we still have to promote half FP to float...
  11928. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  11929. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  11930. resultType = Context.FloatTy;
  11931. }
  11932. if (resultType->isDependentType())
  11933. break;
  11934. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  11935. // C99 6.5.3.3p1: ok, fallthrough;
  11936. if (Context.getLangOpts().CPlusPlus) {
  11937. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  11938. // operand contextually converted to bool.
  11939. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  11940. ScalarTypeToBooleanCastKind(resultType));
  11941. } else if (Context.getLangOpts().OpenCL &&
  11942. Context.getLangOpts().OpenCLVersion < 120) {
  11943. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11944. // operate on scalar float types.
  11945. if (!resultType->isIntegerType() && !resultType->isPointerType())
  11946. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11947. << resultType << Input.get()->getSourceRange());
  11948. }
  11949. } else if (resultType->isExtVectorType()) {
  11950. if (Context.getLangOpts().OpenCL &&
  11951. Context.getLangOpts().OpenCLVersion < 120 &&
  11952. !Context.getLangOpts().OpenCLCPlusPlus) {
  11953. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11954. // operate on vector float types.
  11955. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11956. if (!T->isIntegerType())
  11957. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11958. << resultType << Input.get()->getSourceRange());
  11959. }
  11960. // Vector logical not returns the signed variant of the operand type.
  11961. resultType = GetSignedVectorType(resultType);
  11962. break;
  11963. } else {
  11964. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  11965. // type in C++. We should allow that here too.
  11966. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11967. << resultType << Input.get()->getSourceRange());
  11968. }
  11969. // LNot always has type int. C99 6.5.3.3p5.
  11970. // In C++, it's bool. C++ 5.3.1p8
  11971. resultType = Context.getLogicalOperationType();
  11972. break;
  11973. case UO_Real:
  11974. case UO_Imag:
  11975. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  11976. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  11977. // complex l-values to ordinary l-values and all other values to r-values.
  11978. if (Input.isInvalid()) return ExprError();
  11979. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  11980. if (Input.get()->getValueKind() != VK_RValue &&
  11981. Input.get()->getObjectKind() == OK_Ordinary)
  11982. VK = Input.get()->getValueKind();
  11983. } else if (!getLangOpts().CPlusPlus) {
  11984. // In C, a volatile scalar is read by __imag. In C++, it is not.
  11985. Input = DefaultLvalueConversion(Input.get());
  11986. }
  11987. break;
  11988. case UO_Extension:
  11989. resultType = Input.get()->getType();
  11990. VK = Input.get()->getValueKind();
  11991. OK = Input.get()->getObjectKind();
  11992. break;
  11993. case UO_Coawait:
  11994. // It's unnecessary to represent the pass-through operator co_await in the
  11995. // AST; just return the input expression instead.
  11996. assert(!Input.get()->getType()->isDependentType() &&
  11997. "the co_await expression must be non-dependant before "
  11998. "building operator co_await");
  11999. return Input;
  12000. }
  12001. if (resultType.isNull() || Input.isInvalid())
  12002. return ExprError();
  12003. // Check for array bounds violations in the operand of the UnaryOperator,
  12004. // except for the '*' and '&' operators that have to be handled specially
  12005. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  12006. // that are explicitly defined as valid by the standard).
  12007. if (Opc != UO_AddrOf && Opc != UO_Deref)
  12008. CheckArrayAccess(Input.get());
  12009. auto *UO = new (Context)
  12010. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
  12011. if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
  12012. !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
  12013. ExprEvalContexts.back().PossibleDerefs.insert(UO);
  12014. // Convert the result back to a half vector.
  12015. if (ConvertHalfVec)
  12016. return convertVector(UO, Context.HalfTy, *this);
  12017. return UO;
  12018. }
  12019. /// Determine whether the given expression is a qualified member
  12020. /// access expression, of a form that could be turned into a pointer to member
  12021. /// with the address-of operator.
  12022. bool Sema::isQualifiedMemberAccess(Expr *E) {
  12023. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  12024. if (!DRE->getQualifier())
  12025. return false;
  12026. ValueDecl *VD = DRE->getDecl();
  12027. if (!VD->isCXXClassMember())
  12028. return false;
  12029. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  12030. return true;
  12031. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  12032. return Method->isInstance();
  12033. return false;
  12034. }
  12035. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  12036. if (!ULE->getQualifier())
  12037. return false;
  12038. for (NamedDecl *D : ULE->decls()) {
  12039. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  12040. if (Method->isInstance())
  12041. return true;
  12042. } else {
  12043. // Overload set does not contain methods.
  12044. break;
  12045. }
  12046. }
  12047. return false;
  12048. }
  12049. return false;
  12050. }
  12051. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  12052. UnaryOperatorKind Opc, Expr *Input) {
  12053. // First things first: handle placeholders so that the
  12054. // overloaded-operator check considers the right type.
  12055. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  12056. // Increment and decrement of pseudo-object references.
  12057. if (pty->getKind() == BuiltinType::PseudoObject &&
  12058. UnaryOperator::isIncrementDecrementOp(Opc))
  12059. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  12060. // extension is always a builtin operator.
  12061. if (Opc == UO_Extension)
  12062. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12063. // & gets special logic for several kinds of placeholder.
  12064. // The builtin code knows what to do.
  12065. if (Opc == UO_AddrOf &&
  12066. (pty->getKind() == BuiltinType::Overload ||
  12067. pty->getKind() == BuiltinType::UnknownAny ||
  12068. pty->getKind() == BuiltinType::BoundMember))
  12069. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12070. // Anything else needs to be handled now.
  12071. ExprResult Result = CheckPlaceholderExpr(Input);
  12072. if (Result.isInvalid()) return ExprError();
  12073. Input = Result.get();
  12074. }
  12075. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  12076. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  12077. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  12078. // Find all of the overloaded operators visible from this
  12079. // point. We perform both an operator-name lookup from the local
  12080. // scope and an argument-dependent lookup based on the types of
  12081. // the arguments.
  12082. UnresolvedSet<16> Functions;
  12083. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  12084. if (S && OverOp != OO_None)
  12085. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  12086. Functions);
  12087. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  12088. }
  12089. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12090. }
  12091. // Unary Operators. 'Tok' is the token for the operator.
  12092. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  12093. tok::TokenKind Op, Expr *Input) {
  12094. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  12095. }
  12096. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  12097. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  12098. LabelDecl *TheDecl) {
  12099. TheDecl->markUsed(Context);
  12100. // Create the AST node. The address of a label always has type 'void*'.
  12101. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  12102. Context.getPointerType(Context.VoidTy));
  12103. }
  12104. void Sema::ActOnStartStmtExpr() {
  12105. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  12106. }
  12107. void Sema::ActOnStmtExprError() {
  12108. // Note that function is also called by TreeTransform when leaving a
  12109. // StmtExpr scope without rebuilding anything.
  12110. DiscardCleanupsInEvaluationContext();
  12111. PopExpressionEvaluationContext();
  12112. }
  12113. ExprResult
  12114. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  12115. SourceLocation RPLoc) { // "({..})"
  12116. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  12117. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  12118. if (hasAnyUnrecoverableErrorsInThisFunction())
  12119. DiscardCleanupsInEvaluationContext();
  12120. assert(!Cleanup.exprNeedsCleanups() &&
  12121. "cleanups within StmtExpr not correctly bound!");
  12122. PopExpressionEvaluationContext();
  12123. // FIXME: there are a variety of strange constraints to enforce here, for
  12124. // example, it is not possible to goto into a stmt expression apparently.
  12125. // More semantic analysis is needed.
  12126. // If there are sub-stmts in the compound stmt, take the type of the last one
  12127. // as the type of the stmtexpr.
  12128. QualType Ty = Context.VoidTy;
  12129. bool StmtExprMayBindToTemp = false;
  12130. if (!Compound->body_empty()) {
  12131. // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
  12132. if (const auto *LastStmt =
  12133. dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
  12134. if (const Expr *Value = LastStmt->getExprStmt()) {
  12135. StmtExprMayBindToTemp = true;
  12136. Ty = Value->getType();
  12137. }
  12138. }
  12139. }
  12140. // FIXME: Check that expression type is complete/non-abstract; statement
  12141. // expressions are not lvalues.
  12142. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  12143. if (StmtExprMayBindToTemp)
  12144. return MaybeBindToTemporary(ResStmtExpr);
  12145. return ResStmtExpr;
  12146. }
  12147. ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
  12148. if (ER.isInvalid())
  12149. return ExprError();
  12150. // Do function/array conversion on the last expression, but not
  12151. // lvalue-to-rvalue. However, initialize an unqualified type.
  12152. ER = DefaultFunctionArrayConversion(ER.get());
  12153. if (ER.isInvalid())
  12154. return ExprError();
  12155. Expr *E = ER.get();
  12156. if (E->isTypeDependent())
  12157. return E;
  12158. // In ARC, if the final expression ends in a consume, splice
  12159. // the consume out and bind it later. In the alternate case
  12160. // (when dealing with a retainable type), the result
  12161. // initialization will create a produce. In both cases the
  12162. // result will be +1, and we'll need to balance that out with
  12163. // a bind.
  12164. auto *Cast = dyn_cast<ImplicitCastExpr>(E);
  12165. if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
  12166. return Cast->getSubExpr();
  12167. // FIXME: Provide a better location for the initialization.
  12168. return PerformCopyInitialization(
  12169. InitializedEntity::InitializeStmtExprResult(
  12170. E->getBeginLoc(), E->getType().getUnqualifiedType()),
  12171. SourceLocation(), E);
  12172. }
  12173. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  12174. TypeSourceInfo *TInfo,
  12175. ArrayRef<OffsetOfComponent> Components,
  12176. SourceLocation RParenLoc) {
  12177. QualType ArgTy = TInfo->getType();
  12178. bool Dependent = ArgTy->isDependentType();
  12179. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  12180. // We must have at least one component that refers to the type, and the first
  12181. // one is known to be a field designator. Verify that the ArgTy represents
  12182. // a struct/union/class.
  12183. if (!Dependent && !ArgTy->isRecordType())
  12184. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  12185. << ArgTy << TypeRange);
  12186. // Type must be complete per C99 7.17p3 because a declaring a variable
  12187. // with an incomplete type would be ill-formed.
  12188. if (!Dependent
  12189. && RequireCompleteType(BuiltinLoc, ArgTy,
  12190. diag::err_offsetof_incomplete_type, TypeRange))
  12191. return ExprError();
  12192. bool DidWarnAboutNonPOD = false;
  12193. QualType CurrentType = ArgTy;
  12194. SmallVector<OffsetOfNode, 4> Comps;
  12195. SmallVector<Expr*, 4> Exprs;
  12196. for (const OffsetOfComponent &OC : Components) {
  12197. if (OC.isBrackets) {
  12198. // Offset of an array sub-field. TODO: Should we allow vector elements?
  12199. if (!CurrentType->isDependentType()) {
  12200. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  12201. if(!AT)
  12202. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  12203. << CurrentType);
  12204. CurrentType = AT->getElementType();
  12205. } else
  12206. CurrentType = Context.DependentTy;
  12207. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  12208. if (IdxRval.isInvalid())
  12209. return ExprError();
  12210. Expr *Idx = IdxRval.get();
  12211. // The expression must be an integral expression.
  12212. // FIXME: An integral constant expression?
  12213. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  12214. !Idx->getType()->isIntegerType())
  12215. return ExprError(
  12216. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  12217. << Idx->getSourceRange());
  12218. // Record this array index.
  12219. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  12220. Exprs.push_back(Idx);
  12221. continue;
  12222. }
  12223. // Offset of a field.
  12224. if (CurrentType->isDependentType()) {
  12225. // We have the offset of a field, but we can't look into the dependent
  12226. // type. Just record the identifier of the field.
  12227. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  12228. CurrentType = Context.DependentTy;
  12229. continue;
  12230. }
  12231. // We need to have a complete type to look into.
  12232. if (RequireCompleteType(OC.LocStart, CurrentType,
  12233. diag::err_offsetof_incomplete_type))
  12234. return ExprError();
  12235. // Look for the designated field.
  12236. const RecordType *RC = CurrentType->getAs<RecordType>();
  12237. if (!RC)
  12238. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  12239. << CurrentType);
  12240. RecordDecl *RD = RC->getDecl();
  12241. // C++ [lib.support.types]p5:
  12242. // The macro offsetof accepts a restricted set of type arguments in this
  12243. // International Standard. type shall be a POD structure or a POD union
  12244. // (clause 9).
  12245. // C++11 [support.types]p4:
  12246. // If type is not a standard-layout class (Clause 9), the results are
  12247. // undefined.
  12248. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  12249. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  12250. unsigned DiagID =
  12251. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  12252. : diag::ext_offsetof_non_pod_type;
  12253. if (!IsSafe && !DidWarnAboutNonPOD &&
  12254. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  12255. PDiag(DiagID)
  12256. << SourceRange(Components[0].LocStart, OC.LocEnd)
  12257. << CurrentType))
  12258. DidWarnAboutNonPOD = true;
  12259. }
  12260. // Look for the field.
  12261. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  12262. LookupQualifiedName(R, RD);
  12263. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  12264. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  12265. if (!MemberDecl) {
  12266. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  12267. MemberDecl = IndirectMemberDecl->getAnonField();
  12268. }
  12269. if (!MemberDecl)
  12270. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  12271. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  12272. OC.LocEnd));
  12273. // C99 7.17p3:
  12274. // (If the specified member is a bit-field, the behavior is undefined.)
  12275. //
  12276. // We diagnose this as an error.
  12277. if (MemberDecl->isBitField()) {
  12278. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  12279. << MemberDecl->getDeclName()
  12280. << SourceRange(BuiltinLoc, RParenLoc);
  12281. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  12282. return ExprError();
  12283. }
  12284. RecordDecl *Parent = MemberDecl->getParent();
  12285. if (IndirectMemberDecl)
  12286. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  12287. // If the member was found in a base class, introduce OffsetOfNodes for
  12288. // the base class indirections.
  12289. CXXBasePaths Paths;
  12290. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  12291. Paths)) {
  12292. if (Paths.getDetectedVirtual()) {
  12293. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  12294. << MemberDecl->getDeclName()
  12295. << SourceRange(BuiltinLoc, RParenLoc);
  12296. return ExprError();
  12297. }
  12298. CXXBasePath &Path = Paths.front();
  12299. for (const CXXBasePathElement &B : Path)
  12300. Comps.push_back(OffsetOfNode(B.Base));
  12301. }
  12302. if (IndirectMemberDecl) {
  12303. for (auto *FI : IndirectMemberDecl->chain()) {
  12304. assert(isa<FieldDecl>(FI));
  12305. Comps.push_back(OffsetOfNode(OC.LocStart,
  12306. cast<FieldDecl>(FI), OC.LocEnd));
  12307. }
  12308. } else
  12309. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  12310. CurrentType = MemberDecl->getType().getNonReferenceType();
  12311. }
  12312. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  12313. Comps, Exprs, RParenLoc);
  12314. }
  12315. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  12316. SourceLocation BuiltinLoc,
  12317. SourceLocation TypeLoc,
  12318. ParsedType ParsedArgTy,
  12319. ArrayRef<OffsetOfComponent> Components,
  12320. SourceLocation RParenLoc) {
  12321. TypeSourceInfo *ArgTInfo;
  12322. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  12323. if (ArgTy.isNull())
  12324. return ExprError();
  12325. if (!ArgTInfo)
  12326. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  12327. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  12328. }
  12329. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  12330. Expr *CondExpr,
  12331. Expr *LHSExpr, Expr *RHSExpr,
  12332. SourceLocation RPLoc) {
  12333. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  12334. ExprValueKind VK = VK_RValue;
  12335. ExprObjectKind OK = OK_Ordinary;
  12336. QualType resType;
  12337. bool ValueDependent = false;
  12338. bool CondIsTrue = false;
  12339. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  12340. resType = Context.DependentTy;
  12341. ValueDependent = true;
  12342. } else {
  12343. // The conditional expression is required to be a constant expression.
  12344. llvm::APSInt condEval(32);
  12345. ExprResult CondICE
  12346. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  12347. diag::err_typecheck_choose_expr_requires_constant, false);
  12348. if (CondICE.isInvalid())
  12349. return ExprError();
  12350. CondExpr = CondICE.get();
  12351. CondIsTrue = condEval.getZExtValue();
  12352. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  12353. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  12354. resType = ActiveExpr->getType();
  12355. ValueDependent = ActiveExpr->isValueDependent();
  12356. VK = ActiveExpr->getValueKind();
  12357. OK = ActiveExpr->getObjectKind();
  12358. }
  12359. return new (Context)
  12360. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  12361. CondIsTrue, resType->isDependentType(), ValueDependent);
  12362. }
  12363. //===----------------------------------------------------------------------===//
  12364. // Clang Extensions.
  12365. //===----------------------------------------------------------------------===//
  12366. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  12367. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  12368. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  12369. if (LangOpts.CPlusPlus) {
  12370. Decl *ManglingContextDecl;
  12371. if (MangleNumberingContext *MCtx =
  12372. getCurrentMangleNumberContext(Block->getDeclContext(),
  12373. ManglingContextDecl)) {
  12374. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  12375. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  12376. }
  12377. }
  12378. PushBlockScope(CurScope, Block);
  12379. CurContext->addDecl(Block);
  12380. if (CurScope)
  12381. PushDeclContext(CurScope, Block);
  12382. else
  12383. CurContext = Block;
  12384. getCurBlock()->HasImplicitReturnType = true;
  12385. // Enter a new evaluation context to insulate the block from any
  12386. // cleanups from the enclosing full-expression.
  12387. PushExpressionEvaluationContext(
  12388. ExpressionEvaluationContext::PotentiallyEvaluated);
  12389. }
  12390. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  12391. Scope *CurScope) {
  12392. assert(ParamInfo.getIdentifier() == nullptr &&
  12393. "block-id should have no identifier!");
  12394. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
  12395. BlockScopeInfo *CurBlock = getCurBlock();
  12396. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  12397. QualType T = Sig->getType();
  12398. // FIXME: We should allow unexpanded parameter packs here, but that would,
  12399. // in turn, make the block expression contain unexpanded parameter packs.
  12400. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  12401. // Drop the parameters.
  12402. FunctionProtoType::ExtProtoInfo EPI;
  12403. EPI.HasTrailingReturn = false;
  12404. EPI.TypeQuals.addConst();
  12405. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  12406. Sig = Context.getTrivialTypeSourceInfo(T);
  12407. }
  12408. // GetTypeForDeclarator always produces a function type for a block
  12409. // literal signature. Furthermore, it is always a FunctionProtoType
  12410. // unless the function was written with a typedef.
  12411. assert(T->isFunctionType() &&
  12412. "GetTypeForDeclarator made a non-function block signature");
  12413. // Look for an explicit signature in that function type.
  12414. FunctionProtoTypeLoc ExplicitSignature;
  12415. if ((ExplicitSignature = Sig->getTypeLoc()
  12416. .getAsAdjusted<FunctionProtoTypeLoc>())) {
  12417. // Check whether that explicit signature was synthesized by
  12418. // GetTypeForDeclarator. If so, don't save that as part of the
  12419. // written signature.
  12420. if (ExplicitSignature.getLocalRangeBegin() ==
  12421. ExplicitSignature.getLocalRangeEnd()) {
  12422. // This would be much cheaper if we stored TypeLocs instead of
  12423. // TypeSourceInfos.
  12424. TypeLoc Result = ExplicitSignature.getReturnLoc();
  12425. unsigned Size = Result.getFullDataSize();
  12426. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  12427. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  12428. ExplicitSignature = FunctionProtoTypeLoc();
  12429. }
  12430. }
  12431. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  12432. CurBlock->FunctionType = T;
  12433. const FunctionType *Fn = T->getAs<FunctionType>();
  12434. QualType RetTy = Fn->getReturnType();
  12435. bool isVariadic =
  12436. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  12437. CurBlock->TheDecl->setIsVariadic(isVariadic);
  12438. // Context.DependentTy is used as a placeholder for a missing block
  12439. // return type. TODO: what should we do with declarators like:
  12440. // ^ * { ... }
  12441. // If the answer is "apply template argument deduction"....
  12442. if (RetTy != Context.DependentTy) {
  12443. CurBlock->ReturnType = RetTy;
  12444. CurBlock->TheDecl->setBlockMissingReturnType(false);
  12445. CurBlock->HasImplicitReturnType = false;
  12446. }
  12447. // Push block parameters from the declarator if we had them.
  12448. SmallVector<ParmVarDecl*, 8> Params;
  12449. if (ExplicitSignature) {
  12450. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  12451. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  12452. if (Param->getIdentifier() == nullptr &&
  12453. !Param->isImplicit() &&
  12454. !Param->isInvalidDecl() &&
  12455. !getLangOpts().CPlusPlus)
  12456. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  12457. Params.push_back(Param);
  12458. }
  12459. // Fake up parameter variables if we have a typedef, like
  12460. // ^ fntype { ... }
  12461. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  12462. for (const auto &I : Fn->param_types()) {
  12463. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  12464. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  12465. Params.push_back(Param);
  12466. }
  12467. }
  12468. // Set the parameters on the block decl.
  12469. if (!Params.empty()) {
  12470. CurBlock->TheDecl->setParams(Params);
  12471. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  12472. /*CheckParameterNames=*/false);
  12473. }
  12474. // Finally we can process decl attributes.
  12475. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  12476. // Put the parameter variables in scope.
  12477. for (auto AI : CurBlock->TheDecl->parameters()) {
  12478. AI->setOwningFunction(CurBlock->TheDecl);
  12479. // If this has an identifier, add it to the scope stack.
  12480. if (AI->getIdentifier()) {
  12481. CheckShadow(CurBlock->TheScope, AI);
  12482. PushOnScopeChains(AI, CurBlock->TheScope);
  12483. }
  12484. }
  12485. }
  12486. /// ActOnBlockError - If there is an error parsing a block, this callback
  12487. /// is invoked to pop the information about the block from the action impl.
  12488. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  12489. // Leave the expression-evaluation context.
  12490. DiscardCleanupsInEvaluationContext();
  12491. PopExpressionEvaluationContext();
  12492. // Pop off CurBlock, handle nested blocks.
  12493. PopDeclContext();
  12494. PopFunctionScopeInfo();
  12495. }
  12496. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  12497. /// literal was successfully completed. ^(int x){...}
  12498. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  12499. Stmt *Body, Scope *CurScope) {
  12500. // If blocks are disabled, emit an error.
  12501. if (!LangOpts.Blocks)
  12502. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  12503. // Leave the expression-evaluation context.
  12504. if (hasAnyUnrecoverableErrorsInThisFunction())
  12505. DiscardCleanupsInEvaluationContext();
  12506. assert(!Cleanup.exprNeedsCleanups() &&
  12507. "cleanups within block not correctly bound!");
  12508. PopExpressionEvaluationContext();
  12509. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  12510. BlockDecl *BD = BSI->TheDecl;
  12511. if (BSI->HasImplicitReturnType)
  12512. deduceClosureReturnType(*BSI);
  12513. QualType RetTy = Context.VoidTy;
  12514. if (!BSI->ReturnType.isNull())
  12515. RetTy = BSI->ReturnType;
  12516. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  12517. QualType BlockTy;
  12518. // If the user wrote a function type in some form, try to use that.
  12519. if (!BSI->FunctionType.isNull()) {
  12520. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  12521. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  12522. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  12523. // Turn protoless block types into nullary block types.
  12524. if (isa<FunctionNoProtoType>(FTy)) {
  12525. FunctionProtoType::ExtProtoInfo EPI;
  12526. EPI.ExtInfo = Ext;
  12527. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12528. // Otherwise, if we don't need to change anything about the function type,
  12529. // preserve its sugar structure.
  12530. } else if (FTy->getReturnType() == RetTy &&
  12531. (!NoReturn || FTy->getNoReturnAttr())) {
  12532. BlockTy = BSI->FunctionType;
  12533. // Otherwise, make the minimal modifications to the function type.
  12534. } else {
  12535. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  12536. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  12537. EPI.TypeQuals = Qualifiers();
  12538. EPI.ExtInfo = Ext;
  12539. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  12540. }
  12541. // If we don't have a function type, just build one from nothing.
  12542. } else {
  12543. FunctionProtoType::ExtProtoInfo EPI;
  12544. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  12545. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12546. }
  12547. DiagnoseUnusedParameters(BD->parameters());
  12548. BlockTy = Context.getBlockPointerType(BlockTy);
  12549. // If needed, diagnose invalid gotos and switches in the block.
  12550. if (getCurFunction()->NeedsScopeChecking() &&
  12551. !PP.isCodeCompletionEnabled())
  12552. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  12553. BD->setBody(cast<CompoundStmt>(Body));
  12554. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12555. DiagnoseUnguardedAvailabilityViolations(BD);
  12556. // Try to apply the named return value optimization. We have to check again
  12557. // if we can do this, though, because blocks keep return statements around
  12558. // to deduce an implicit return type.
  12559. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  12560. !BD->isDependentContext())
  12561. computeNRVO(Body, BSI);
  12562. if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
  12563. RetTy.hasNonTrivialToPrimitiveCopyCUnion())
  12564. checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
  12565. NTCUK_Destruct|NTCUK_Copy);
  12566. PopDeclContext();
  12567. // Pop the block scope now but keep it alive to the end of this function.
  12568. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12569. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
  12570. // Set the captured variables on the block.
  12571. SmallVector<BlockDecl::Capture, 4> Captures;
  12572. for (Capture &Cap : BSI->Captures) {
  12573. if (Cap.isInvalid() || Cap.isThisCapture())
  12574. continue;
  12575. VarDecl *Var = Cap.getVariable();
  12576. Expr *CopyExpr = nullptr;
  12577. if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
  12578. if (const RecordType *Record =
  12579. Cap.getCaptureType()->getAs<RecordType>()) {
  12580. // The capture logic needs the destructor, so make sure we mark it.
  12581. // Usually this is unnecessary because most local variables have
  12582. // their destructors marked at declaration time, but parameters are
  12583. // an exception because it's technically only the call site that
  12584. // actually requires the destructor.
  12585. if (isa<ParmVarDecl>(Var))
  12586. FinalizeVarWithDestructor(Var, Record);
  12587. // Enter a separate potentially-evaluated context while building block
  12588. // initializers to isolate their cleanups from those of the block
  12589. // itself.
  12590. // FIXME: Is this appropriate even when the block itself occurs in an
  12591. // unevaluated operand?
  12592. EnterExpressionEvaluationContext EvalContext(
  12593. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12594. SourceLocation Loc = Cap.getLocation();
  12595. ExprResult Result = BuildDeclarationNameExpr(
  12596. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  12597. // According to the blocks spec, the capture of a variable from
  12598. // the stack requires a const copy constructor. This is not true
  12599. // of the copy/move done to move a __block variable to the heap.
  12600. if (!Result.isInvalid() &&
  12601. !Result.get()->getType().isConstQualified()) {
  12602. Result = ImpCastExprToType(Result.get(),
  12603. Result.get()->getType().withConst(),
  12604. CK_NoOp, VK_LValue);
  12605. }
  12606. if (!Result.isInvalid()) {
  12607. Result = PerformCopyInitialization(
  12608. InitializedEntity::InitializeBlock(Var->getLocation(),
  12609. Cap.getCaptureType(), false),
  12610. Loc, Result.get());
  12611. }
  12612. // Build a full-expression copy expression if initialization
  12613. // succeeded and used a non-trivial constructor. Recover from
  12614. // errors by pretending that the copy isn't necessary.
  12615. if (!Result.isInvalid() &&
  12616. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  12617. ->isTrivial()) {
  12618. Result = MaybeCreateExprWithCleanups(Result);
  12619. CopyExpr = Result.get();
  12620. }
  12621. }
  12622. }
  12623. BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
  12624. CopyExpr);
  12625. Captures.push_back(NewCap);
  12626. }
  12627. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  12628. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  12629. // If the block isn't obviously global, i.e. it captures anything at
  12630. // all, then we need to do a few things in the surrounding context:
  12631. if (Result->getBlockDecl()->hasCaptures()) {
  12632. // First, this expression has a new cleanup object.
  12633. ExprCleanupObjects.push_back(Result->getBlockDecl());
  12634. Cleanup.setExprNeedsCleanups(true);
  12635. // It also gets a branch-protected scope if any of the captured
  12636. // variables needs destruction.
  12637. for (const auto &CI : Result->getBlockDecl()->captures()) {
  12638. const VarDecl *var = CI.getVariable();
  12639. if (var->getType().isDestructedType() != QualType::DK_none) {
  12640. setFunctionHasBranchProtectedScope();
  12641. break;
  12642. }
  12643. }
  12644. }
  12645. if (getCurFunction())
  12646. getCurFunction()->addBlock(BD);
  12647. return Result;
  12648. }
  12649. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  12650. SourceLocation RPLoc) {
  12651. TypeSourceInfo *TInfo;
  12652. GetTypeFromParser(Ty, &TInfo);
  12653. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  12654. }
  12655. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  12656. Expr *E, TypeSourceInfo *TInfo,
  12657. SourceLocation RPLoc) {
  12658. Expr *OrigExpr = E;
  12659. bool IsMS = false;
  12660. // CUDA device code does not support varargs.
  12661. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  12662. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  12663. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  12664. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  12665. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  12666. }
  12667. }
  12668. // NVPTX does not support va_arg expression.
  12669. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  12670. Context.getTargetInfo().getTriple().isNVPTX())
  12671. targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
  12672. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  12673. // as Microsoft ABI on an actual Microsoft platform, where
  12674. // __builtin_ms_va_list and __builtin_va_list are the same.)
  12675. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  12676. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  12677. QualType MSVaListType = Context.getBuiltinMSVaListType();
  12678. if (Context.hasSameType(MSVaListType, E->getType())) {
  12679. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12680. return ExprError();
  12681. IsMS = true;
  12682. }
  12683. }
  12684. // Get the va_list type
  12685. QualType VaListType = Context.getBuiltinVaListType();
  12686. if (!IsMS) {
  12687. if (VaListType->isArrayType()) {
  12688. // Deal with implicit array decay; for example, on x86-64,
  12689. // va_list is an array, but it's supposed to decay to
  12690. // a pointer for va_arg.
  12691. VaListType = Context.getArrayDecayedType(VaListType);
  12692. // Make sure the input expression also decays appropriately.
  12693. ExprResult Result = UsualUnaryConversions(E);
  12694. if (Result.isInvalid())
  12695. return ExprError();
  12696. E = Result.get();
  12697. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  12698. // If va_list is a record type and we are compiling in C++ mode,
  12699. // check the argument using reference binding.
  12700. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  12701. Context, Context.getLValueReferenceType(VaListType), false);
  12702. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  12703. if (Init.isInvalid())
  12704. return ExprError();
  12705. E = Init.getAs<Expr>();
  12706. } else {
  12707. // Otherwise, the va_list argument must be an l-value because
  12708. // it is modified by va_arg.
  12709. if (!E->isTypeDependent() &&
  12710. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12711. return ExprError();
  12712. }
  12713. }
  12714. if (!IsMS && !E->isTypeDependent() &&
  12715. !Context.hasSameType(VaListType, E->getType()))
  12716. return ExprError(
  12717. Diag(E->getBeginLoc(),
  12718. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  12719. << OrigExpr->getType() << E->getSourceRange());
  12720. if (!TInfo->getType()->isDependentType()) {
  12721. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  12722. diag::err_second_parameter_to_va_arg_incomplete,
  12723. TInfo->getTypeLoc()))
  12724. return ExprError();
  12725. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  12726. TInfo->getType(),
  12727. diag::err_second_parameter_to_va_arg_abstract,
  12728. TInfo->getTypeLoc()))
  12729. return ExprError();
  12730. if (!TInfo->getType().isPODType(Context)) {
  12731. Diag(TInfo->getTypeLoc().getBeginLoc(),
  12732. TInfo->getType()->isObjCLifetimeType()
  12733. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  12734. : diag::warn_second_parameter_to_va_arg_not_pod)
  12735. << TInfo->getType()
  12736. << TInfo->getTypeLoc().getSourceRange();
  12737. }
  12738. // Check for va_arg where arguments of the given type will be promoted
  12739. // (i.e. this va_arg is guaranteed to have undefined behavior).
  12740. QualType PromoteType;
  12741. if (TInfo->getType()->isPromotableIntegerType()) {
  12742. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  12743. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  12744. PromoteType = QualType();
  12745. }
  12746. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  12747. PromoteType = Context.DoubleTy;
  12748. if (!PromoteType.isNull())
  12749. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  12750. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  12751. << TInfo->getType()
  12752. << PromoteType
  12753. << TInfo->getTypeLoc().getSourceRange());
  12754. }
  12755. QualType T = TInfo->getType().getNonLValueExprType(Context);
  12756. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  12757. }
  12758. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  12759. // The type of __null will be int or long, depending on the size of
  12760. // pointers on the target.
  12761. QualType Ty;
  12762. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  12763. if (pw == Context.getTargetInfo().getIntWidth())
  12764. Ty = Context.IntTy;
  12765. else if (pw == Context.getTargetInfo().getLongWidth())
  12766. Ty = Context.LongTy;
  12767. else if (pw == Context.getTargetInfo().getLongLongWidth())
  12768. Ty = Context.LongLongTy;
  12769. else {
  12770. llvm_unreachable("I don't know size of pointer!");
  12771. }
  12772. return new (Context) GNUNullExpr(Ty, TokenLoc);
  12773. }
  12774. ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12775. SourceLocation BuiltinLoc,
  12776. SourceLocation RPLoc) {
  12777. return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
  12778. }
  12779. ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12780. SourceLocation BuiltinLoc,
  12781. SourceLocation RPLoc,
  12782. DeclContext *ParentContext) {
  12783. return new (Context)
  12784. SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
  12785. }
  12786. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  12787. bool Diagnose) {
  12788. if (!getLangOpts().ObjC)
  12789. return false;
  12790. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  12791. if (!PT)
  12792. return false;
  12793. if (!PT->isObjCIdType()) {
  12794. // Check if the destination is the 'NSString' interface.
  12795. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  12796. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  12797. return false;
  12798. }
  12799. // Ignore any parens, implicit casts (should only be
  12800. // array-to-pointer decays), and not-so-opaque values. The last is
  12801. // important for making this trigger for property assignments.
  12802. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  12803. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  12804. if (OV->getSourceExpr())
  12805. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  12806. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  12807. if (!SL || !SL->isAscii())
  12808. return false;
  12809. if (Diagnose) {
  12810. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  12811. << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  12812. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  12813. }
  12814. return true;
  12815. }
  12816. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  12817. const Expr *SrcExpr) {
  12818. if (!DstType->isFunctionPointerType() ||
  12819. !SrcExpr->getType()->isFunctionType())
  12820. return false;
  12821. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  12822. if (!DRE)
  12823. return false;
  12824. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  12825. if (!FD)
  12826. return false;
  12827. return !S.checkAddressOfFunctionIsAvailable(FD,
  12828. /*Complain=*/true,
  12829. SrcExpr->getBeginLoc());
  12830. }
  12831. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  12832. SourceLocation Loc,
  12833. QualType DstType, QualType SrcType,
  12834. Expr *SrcExpr, AssignmentAction Action,
  12835. bool *Complained) {
  12836. if (Complained)
  12837. *Complained = false;
  12838. // Decode the result (notice that AST's are still created for extensions).
  12839. bool CheckInferredResultType = false;
  12840. bool isInvalid = false;
  12841. unsigned DiagKind = 0;
  12842. FixItHint Hint;
  12843. ConversionFixItGenerator ConvHints;
  12844. bool MayHaveConvFixit = false;
  12845. bool MayHaveFunctionDiff = false;
  12846. const ObjCInterfaceDecl *IFace = nullptr;
  12847. const ObjCProtocolDecl *PDecl = nullptr;
  12848. switch (ConvTy) {
  12849. case Compatible:
  12850. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  12851. return false;
  12852. case PointerToInt:
  12853. DiagKind = diag::ext_typecheck_convert_pointer_int;
  12854. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12855. MayHaveConvFixit = true;
  12856. break;
  12857. case IntToPointer:
  12858. DiagKind = diag::ext_typecheck_convert_int_pointer;
  12859. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12860. MayHaveConvFixit = true;
  12861. break;
  12862. case IncompatiblePointer:
  12863. if (Action == AA_Passing_CFAudited)
  12864. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  12865. else if (SrcType->isFunctionPointerType() &&
  12866. DstType->isFunctionPointerType())
  12867. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  12868. else
  12869. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  12870. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  12871. SrcType->isObjCObjectPointerType();
  12872. if (Hint.isNull() && !CheckInferredResultType) {
  12873. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12874. }
  12875. else if (CheckInferredResultType) {
  12876. SrcType = SrcType.getUnqualifiedType();
  12877. DstType = DstType.getUnqualifiedType();
  12878. }
  12879. MayHaveConvFixit = true;
  12880. break;
  12881. case IncompatiblePointerSign:
  12882. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  12883. break;
  12884. case FunctionVoidPointer:
  12885. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  12886. break;
  12887. case IncompatiblePointerDiscardsQualifiers: {
  12888. // Perform array-to-pointer decay if necessary.
  12889. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  12890. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  12891. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  12892. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  12893. DiagKind = diag::err_typecheck_incompatible_address_space;
  12894. break;
  12895. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  12896. DiagKind = diag::err_typecheck_incompatible_ownership;
  12897. break;
  12898. }
  12899. llvm_unreachable("unknown error case for discarding qualifiers!");
  12900. // fallthrough
  12901. }
  12902. case CompatiblePointerDiscardsQualifiers:
  12903. // If the qualifiers lost were because we were applying the
  12904. // (deprecated) C++ conversion from a string literal to a char*
  12905. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  12906. // Ideally, this check would be performed in
  12907. // checkPointerTypesForAssignment. However, that would require a
  12908. // bit of refactoring (so that the second argument is an
  12909. // expression, rather than a type), which should be done as part
  12910. // of a larger effort to fix checkPointerTypesForAssignment for
  12911. // C++ semantics.
  12912. if (getLangOpts().CPlusPlus &&
  12913. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  12914. return false;
  12915. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  12916. break;
  12917. case IncompatibleNestedPointerQualifiers:
  12918. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  12919. break;
  12920. case IncompatibleNestedPointerAddressSpaceMismatch:
  12921. DiagKind = diag::err_typecheck_incompatible_nested_address_space;
  12922. break;
  12923. case IntToBlockPointer:
  12924. DiagKind = diag::err_int_to_block_pointer;
  12925. break;
  12926. case IncompatibleBlockPointer:
  12927. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  12928. break;
  12929. case IncompatibleObjCQualifiedId: {
  12930. if (SrcType->isObjCQualifiedIdType()) {
  12931. const ObjCObjectPointerType *srcOPT =
  12932. SrcType->getAs<ObjCObjectPointerType>();
  12933. for (auto *srcProto : srcOPT->quals()) {
  12934. PDecl = srcProto;
  12935. break;
  12936. }
  12937. if (const ObjCInterfaceType *IFaceT =
  12938. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12939. IFace = IFaceT->getDecl();
  12940. }
  12941. else if (DstType->isObjCQualifiedIdType()) {
  12942. const ObjCObjectPointerType *dstOPT =
  12943. DstType->getAs<ObjCObjectPointerType>();
  12944. for (auto *dstProto : dstOPT->quals()) {
  12945. PDecl = dstProto;
  12946. break;
  12947. }
  12948. if (const ObjCInterfaceType *IFaceT =
  12949. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12950. IFace = IFaceT->getDecl();
  12951. }
  12952. DiagKind = diag::warn_incompatible_qualified_id;
  12953. break;
  12954. }
  12955. case IncompatibleVectors:
  12956. DiagKind = diag::warn_incompatible_vectors;
  12957. break;
  12958. case IncompatibleObjCWeakRef:
  12959. DiagKind = diag::err_arc_weak_unavailable_assign;
  12960. break;
  12961. case Incompatible:
  12962. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  12963. if (Complained)
  12964. *Complained = true;
  12965. return true;
  12966. }
  12967. DiagKind = diag::err_typecheck_convert_incompatible;
  12968. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12969. MayHaveConvFixit = true;
  12970. isInvalid = true;
  12971. MayHaveFunctionDiff = true;
  12972. break;
  12973. }
  12974. QualType FirstType, SecondType;
  12975. switch (Action) {
  12976. case AA_Assigning:
  12977. case AA_Initializing:
  12978. // The destination type comes first.
  12979. FirstType = DstType;
  12980. SecondType = SrcType;
  12981. break;
  12982. case AA_Returning:
  12983. case AA_Passing:
  12984. case AA_Passing_CFAudited:
  12985. case AA_Converting:
  12986. case AA_Sending:
  12987. case AA_Casting:
  12988. // The source type comes first.
  12989. FirstType = SrcType;
  12990. SecondType = DstType;
  12991. break;
  12992. }
  12993. PartialDiagnostic FDiag = PDiag(DiagKind);
  12994. if (Action == AA_Passing_CFAudited)
  12995. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  12996. else
  12997. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  12998. // If we can fix the conversion, suggest the FixIts.
  12999. assert(ConvHints.isNull() || Hint.isNull());
  13000. if (!ConvHints.isNull()) {
  13001. for (FixItHint &H : ConvHints.Hints)
  13002. FDiag << H;
  13003. } else {
  13004. FDiag << Hint;
  13005. }
  13006. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  13007. if (MayHaveFunctionDiff)
  13008. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  13009. Diag(Loc, FDiag);
  13010. if (DiagKind == diag::warn_incompatible_qualified_id &&
  13011. PDecl && IFace && !IFace->hasDefinition())
  13012. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  13013. << IFace << PDecl;
  13014. if (SecondType == Context.OverloadTy)
  13015. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  13016. FirstType, /*TakingAddress=*/true);
  13017. if (CheckInferredResultType)
  13018. EmitRelatedResultTypeNote(SrcExpr);
  13019. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  13020. EmitRelatedResultTypeNoteForReturn(DstType);
  13021. if (Complained)
  13022. *Complained = true;
  13023. return isInvalid;
  13024. }
  13025. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  13026. llvm::APSInt *Result) {
  13027. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  13028. public:
  13029. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  13030. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  13031. }
  13032. } Diagnoser;
  13033. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  13034. }
  13035. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  13036. llvm::APSInt *Result,
  13037. unsigned DiagID,
  13038. bool AllowFold) {
  13039. class IDDiagnoser : public VerifyICEDiagnoser {
  13040. unsigned DiagID;
  13041. public:
  13042. IDDiagnoser(unsigned DiagID)
  13043. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  13044. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  13045. S.Diag(Loc, DiagID) << SR;
  13046. }
  13047. } Diagnoser(DiagID);
  13048. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  13049. }
  13050. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  13051. SourceRange SR) {
  13052. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  13053. }
  13054. ExprResult
  13055. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  13056. VerifyICEDiagnoser &Diagnoser,
  13057. bool AllowFold) {
  13058. SourceLocation DiagLoc = E->getBeginLoc();
  13059. if (getLangOpts().CPlusPlus11) {
  13060. // C++11 [expr.const]p5:
  13061. // If an expression of literal class type is used in a context where an
  13062. // integral constant expression is required, then that class type shall
  13063. // have a single non-explicit conversion function to an integral or
  13064. // unscoped enumeration type
  13065. ExprResult Converted;
  13066. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  13067. public:
  13068. CXX11ConvertDiagnoser(bool Silent)
  13069. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  13070. Silent, true) {}
  13071. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  13072. QualType T) override {
  13073. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  13074. }
  13075. SemaDiagnosticBuilder diagnoseIncomplete(
  13076. Sema &S, SourceLocation Loc, QualType T) override {
  13077. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  13078. }
  13079. SemaDiagnosticBuilder diagnoseExplicitConv(
  13080. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  13081. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  13082. }
  13083. SemaDiagnosticBuilder noteExplicitConv(
  13084. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  13085. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  13086. << ConvTy->isEnumeralType() << ConvTy;
  13087. }
  13088. SemaDiagnosticBuilder diagnoseAmbiguous(
  13089. Sema &S, SourceLocation Loc, QualType T) override {
  13090. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  13091. }
  13092. SemaDiagnosticBuilder noteAmbiguous(
  13093. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  13094. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  13095. << ConvTy->isEnumeralType() << ConvTy;
  13096. }
  13097. SemaDiagnosticBuilder diagnoseConversion(
  13098. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  13099. llvm_unreachable("conversion functions are permitted");
  13100. }
  13101. } ConvertDiagnoser(Diagnoser.Suppress);
  13102. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  13103. ConvertDiagnoser);
  13104. if (Converted.isInvalid())
  13105. return Converted;
  13106. E = Converted.get();
  13107. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  13108. return ExprError();
  13109. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  13110. // An ICE must be of integral or unscoped enumeration type.
  13111. if (!Diagnoser.Suppress)
  13112. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  13113. return ExprError();
  13114. }
  13115. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  13116. // in the non-ICE case.
  13117. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  13118. if (Result)
  13119. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  13120. if (!isa<ConstantExpr>(E))
  13121. E = ConstantExpr::Create(Context, E);
  13122. return E;
  13123. }
  13124. Expr::EvalResult EvalResult;
  13125. SmallVector<PartialDiagnosticAt, 8> Notes;
  13126. EvalResult.Diag = &Notes;
  13127. // Try to evaluate the expression, and produce diagnostics explaining why it's
  13128. // not a constant expression as a side-effect.
  13129. bool Folded =
  13130. E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
  13131. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  13132. if (!isa<ConstantExpr>(E))
  13133. E = ConstantExpr::Create(Context, E, EvalResult.Val);
  13134. // In C++11, we can rely on diagnostics being produced for any expression
  13135. // which is not a constant expression. If no diagnostics were produced, then
  13136. // this is a constant expression.
  13137. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  13138. if (Result)
  13139. *Result = EvalResult.Val.getInt();
  13140. return E;
  13141. }
  13142. // If our only note is the usual "invalid subexpression" note, just point
  13143. // the caret at its location rather than producing an essentially
  13144. // redundant note.
  13145. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  13146. diag::note_invalid_subexpr_in_const_expr) {
  13147. DiagLoc = Notes[0].first;
  13148. Notes.clear();
  13149. }
  13150. if (!Folded || !AllowFold) {
  13151. if (!Diagnoser.Suppress) {
  13152. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  13153. for (const PartialDiagnosticAt &Note : Notes)
  13154. Diag(Note.first, Note.second);
  13155. }
  13156. return ExprError();
  13157. }
  13158. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  13159. for (const PartialDiagnosticAt &Note : Notes)
  13160. Diag(Note.first, Note.second);
  13161. if (Result)
  13162. *Result = EvalResult.Val.getInt();
  13163. return E;
  13164. }
  13165. namespace {
  13166. // Handle the case where we conclude a expression which we speculatively
  13167. // considered to be unevaluated is actually evaluated.
  13168. class TransformToPE : public TreeTransform<TransformToPE> {
  13169. typedef TreeTransform<TransformToPE> BaseTransform;
  13170. public:
  13171. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  13172. // Make sure we redo semantic analysis
  13173. bool AlwaysRebuild() { return true; }
  13174. bool ReplacingOriginal() { return true; }
  13175. // We need to special-case DeclRefExprs referring to FieldDecls which
  13176. // are not part of a member pointer formation; normal TreeTransforming
  13177. // doesn't catch this case because of the way we represent them in the AST.
  13178. // FIXME: This is a bit ugly; is it really the best way to handle this
  13179. // case?
  13180. //
  13181. // Error on DeclRefExprs referring to FieldDecls.
  13182. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  13183. if (isa<FieldDecl>(E->getDecl()) &&
  13184. !SemaRef.isUnevaluatedContext())
  13185. return SemaRef.Diag(E->getLocation(),
  13186. diag::err_invalid_non_static_member_use)
  13187. << E->getDecl() << E->getSourceRange();
  13188. return BaseTransform::TransformDeclRefExpr(E);
  13189. }
  13190. // Exception: filter out member pointer formation
  13191. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  13192. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  13193. return E;
  13194. return BaseTransform::TransformUnaryOperator(E);
  13195. }
  13196. // The body of a lambda-expression is in a separate expression evaluation
  13197. // context so never needs to be transformed.
  13198. // FIXME: Ideally we wouldn't transform the closure type either, and would
  13199. // just recreate the capture expressions and lambda expression.
  13200. StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
  13201. return SkipLambdaBody(E, Body);
  13202. }
  13203. };
  13204. }
  13205. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  13206. assert(isUnevaluatedContext() &&
  13207. "Should only transform unevaluated expressions");
  13208. ExprEvalContexts.back().Context =
  13209. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  13210. if (isUnevaluatedContext())
  13211. return E;
  13212. return TransformToPE(*this).TransformExpr(E);
  13213. }
  13214. void
  13215. Sema::PushExpressionEvaluationContext(
  13216. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  13217. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  13218. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  13219. LambdaContextDecl, ExprContext);
  13220. Cleanup.reset();
  13221. if (!MaybeODRUseExprs.empty())
  13222. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  13223. }
  13224. void
  13225. Sema::PushExpressionEvaluationContext(
  13226. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  13227. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  13228. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  13229. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  13230. }
  13231. namespace {
  13232. const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
  13233. PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
  13234. if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
  13235. if (E->getOpcode() == UO_Deref)
  13236. return CheckPossibleDeref(S, E->getSubExpr());
  13237. } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
  13238. return CheckPossibleDeref(S, E->getBase());
  13239. } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
  13240. return CheckPossibleDeref(S, E->getBase());
  13241. } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
  13242. QualType Inner;
  13243. QualType Ty = E->getType();
  13244. if (const auto *Ptr = Ty->getAs<PointerType>())
  13245. Inner = Ptr->getPointeeType();
  13246. else if (const auto *Arr = S.Context.getAsArrayType(Ty))
  13247. Inner = Arr->getElementType();
  13248. else
  13249. return nullptr;
  13250. if (Inner->hasAttr(attr::NoDeref))
  13251. return E;
  13252. }
  13253. return nullptr;
  13254. }
  13255. } // namespace
  13256. void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
  13257. for (const Expr *E : Rec.PossibleDerefs) {
  13258. const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
  13259. if (DeclRef) {
  13260. const ValueDecl *Decl = DeclRef->getDecl();
  13261. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
  13262. << Decl->getName() << E->getSourceRange();
  13263. Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
  13264. } else {
  13265. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
  13266. << E->getSourceRange();
  13267. }
  13268. }
  13269. Rec.PossibleDerefs.clear();
  13270. }
  13271. void Sema::PopExpressionEvaluationContext() {
  13272. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  13273. unsigned NumTypos = Rec.NumTypos;
  13274. if (!Rec.Lambdas.empty()) {
  13275. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  13276. if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
  13277. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
  13278. unsigned D;
  13279. if (Rec.isUnevaluated()) {
  13280. // C++11 [expr.prim.lambda]p2:
  13281. // A lambda-expression shall not appear in an unevaluated operand
  13282. // (Clause 5).
  13283. D = diag::err_lambda_unevaluated_operand;
  13284. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  13285. // C++1y [expr.const]p2:
  13286. // A conditional-expression e is a core constant expression unless the
  13287. // evaluation of e, following the rules of the abstract machine, would
  13288. // evaluate [...] a lambda-expression.
  13289. D = diag::err_lambda_in_constant_expression;
  13290. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  13291. // C++17 [expr.prim.lamda]p2:
  13292. // A lambda-expression shall not appear [...] in a template-argument.
  13293. D = diag::err_lambda_in_invalid_context;
  13294. } else
  13295. llvm_unreachable("Couldn't infer lambda error message.");
  13296. for (const auto *L : Rec.Lambdas)
  13297. Diag(L->getBeginLoc(), D);
  13298. }
  13299. }
  13300. WarnOnPendingNoDerefs(Rec);
  13301. // When are coming out of an unevaluated context, clear out any
  13302. // temporaries that we may have created as part of the evaluation of
  13303. // the expression in that context: they aren't relevant because they
  13304. // will never be constructed.
  13305. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  13306. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  13307. ExprCleanupObjects.end());
  13308. Cleanup = Rec.ParentCleanup;
  13309. CleanupVarDeclMarking();
  13310. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  13311. // Otherwise, merge the contexts together.
  13312. } else {
  13313. Cleanup.mergeFrom(Rec.ParentCleanup);
  13314. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  13315. Rec.SavedMaybeODRUseExprs.end());
  13316. }
  13317. // Pop the current expression evaluation context off the stack.
  13318. ExprEvalContexts.pop_back();
  13319. // The global expression evaluation context record is never popped.
  13320. ExprEvalContexts.back().NumTypos += NumTypos;
  13321. }
  13322. void Sema::DiscardCleanupsInEvaluationContext() {
  13323. ExprCleanupObjects.erase(
  13324. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  13325. ExprCleanupObjects.end());
  13326. Cleanup.reset();
  13327. MaybeODRUseExprs.clear();
  13328. }
  13329. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  13330. ExprResult Result = CheckPlaceholderExpr(E);
  13331. if (Result.isInvalid())
  13332. return ExprError();
  13333. E = Result.get();
  13334. if (!E->getType()->isVariablyModifiedType())
  13335. return E;
  13336. return TransformToPotentiallyEvaluated(E);
  13337. }
  13338. /// Are we in a context that is potentially constant evaluated per C++20
  13339. /// [expr.const]p12?
  13340. static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
  13341. /// C++2a [expr.const]p12:
  13342. // An expression or conversion is potentially constant evaluated if it is
  13343. switch (SemaRef.ExprEvalContexts.back().Context) {
  13344. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13345. // -- a manifestly constant-evaluated expression,
  13346. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13347. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13348. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13349. // -- a potentially-evaluated expression,
  13350. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13351. // -- an immediate subexpression of a braced-init-list,
  13352. // -- [FIXME] an expression of the form & cast-expression that occurs
  13353. // within a templated entity
  13354. // -- a subexpression of one of the above that is not a subexpression of
  13355. // a nested unevaluated operand.
  13356. return true;
  13357. case Sema::ExpressionEvaluationContext::Unevaluated:
  13358. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13359. // Expressions in this context are never evaluated.
  13360. return false;
  13361. }
  13362. llvm_unreachable("Invalid context");
  13363. }
  13364. /// Return true if this function has a calling convention that requires mangling
  13365. /// in the size of the parameter pack.
  13366. static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
  13367. // These manglings don't do anything on non-Windows or non-x86 platforms, so
  13368. // we don't need parameter type sizes.
  13369. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  13370. if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
  13371. TT.getArch() != llvm::Triple::x86_64))
  13372. return false;
  13373. // If this is C++ and this isn't an extern "C" function, parameters do not
  13374. // need to be complete. In this case, C++ mangling will apply, which doesn't
  13375. // use the size of the parameters.
  13376. if (S.getLangOpts().CPlusPlus && !FD->isExternC())
  13377. return false;
  13378. // Stdcall, fastcall, and vectorcall need this special treatment.
  13379. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13380. switch (CC) {
  13381. case CC_X86StdCall:
  13382. case CC_X86FastCall:
  13383. case CC_X86VectorCall:
  13384. return true;
  13385. default:
  13386. break;
  13387. }
  13388. return false;
  13389. }
  13390. /// Require that all of the parameter types of function be complete. Normally,
  13391. /// parameter types are only required to be complete when a function is called
  13392. /// or defined, but to mangle functions with certain calling conventions, the
  13393. /// mangler needs to know the size of the parameter list. In this situation,
  13394. /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
  13395. /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
  13396. /// result in a linker error. Clang doesn't implement this behavior, and instead
  13397. /// attempts to error at compile time.
  13398. static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
  13399. SourceLocation Loc) {
  13400. class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
  13401. FunctionDecl *FD;
  13402. ParmVarDecl *Param;
  13403. public:
  13404. ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
  13405. : FD(FD), Param(Param) {}
  13406. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  13407. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13408. StringRef CCName;
  13409. switch (CC) {
  13410. case CC_X86StdCall:
  13411. CCName = "stdcall";
  13412. break;
  13413. case CC_X86FastCall:
  13414. CCName = "fastcall";
  13415. break;
  13416. case CC_X86VectorCall:
  13417. CCName = "vectorcall";
  13418. break;
  13419. default:
  13420. llvm_unreachable("CC does not need mangling");
  13421. }
  13422. S.Diag(Loc, diag::err_cconv_incomplete_param_type)
  13423. << Param->getDeclName() << FD->getDeclName() << CCName;
  13424. }
  13425. };
  13426. for (ParmVarDecl *Param : FD->parameters()) {
  13427. ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
  13428. S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
  13429. }
  13430. }
  13431. namespace {
  13432. enum class OdrUseContext {
  13433. /// Declarations in this context are not odr-used.
  13434. None,
  13435. /// Declarations in this context are formally odr-used, but this is a
  13436. /// dependent context.
  13437. Dependent,
  13438. /// Declarations in this context are odr-used but not actually used (yet).
  13439. FormallyOdrUsed,
  13440. /// Declarations in this context are used.
  13441. Used
  13442. };
  13443. }
  13444. /// Are we within a context in which references to resolved functions or to
  13445. /// variables result in odr-use?
  13446. static OdrUseContext isOdrUseContext(Sema &SemaRef) {
  13447. OdrUseContext Result;
  13448. switch (SemaRef.ExprEvalContexts.back().Context) {
  13449. case Sema::ExpressionEvaluationContext::Unevaluated:
  13450. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13451. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13452. return OdrUseContext::None;
  13453. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13454. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13455. Result = OdrUseContext::Used;
  13456. break;
  13457. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13458. Result = OdrUseContext::FormallyOdrUsed;
  13459. break;
  13460. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13461. // A default argument formally results in odr-use, but doesn't actually
  13462. // result in a use in any real sense until it itself is used.
  13463. Result = OdrUseContext::FormallyOdrUsed;
  13464. break;
  13465. }
  13466. if (SemaRef.CurContext->isDependentContext())
  13467. return OdrUseContext::Dependent;
  13468. return Result;
  13469. }
  13470. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  13471. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  13472. return Func->isConstexpr() &&
  13473. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  13474. }
  13475. /// Mark a function referenced, and check whether it is odr-used
  13476. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  13477. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  13478. bool MightBeOdrUse) {
  13479. assert(Func && "No function?");
  13480. Func->setReferenced();
  13481. // Recursive functions aren't really used until they're used from some other
  13482. // context.
  13483. bool IsRecursiveCall = CurContext == Func;
  13484. // C++11 [basic.def.odr]p3:
  13485. // A function whose name appears as a potentially-evaluated expression is
  13486. // odr-used if it is the unique lookup result or the selected member of a
  13487. // set of overloaded functions [...].
  13488. //
  13489. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  13490. // can just check that here.
  13491. OdrUseContext OdrUse =
  13492. MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
  13493. if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
  13494. OdrUse = OdrUseContext::FormallyOdrUsed;
  13495. // Trivial default constructors and destructors are never actually used.
  13496. // FIXME: What about other special members?
  13497. if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
  13498. OdrUse == OdrUseContext::Used) {
  13499. if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
  13500. if (Constructor->isDefaultConstructor())
  13501. OdrUse = OdrUseContext::FormallyOdrUsed;
  13502. if (isa<CXXDestructorDecl>(Func))
  13503. OdrUse = OdrUseContext::FormallyOdrUsed;
  13504. }
  13505. // C++20 [expr.const]p12:
  13506. // A function [...] is needed for constant evaluation if it is [...] a
  13507. // constexpr function that is named by an expression that is potentially
  13508. // constant evaluated
  13509. bool NeededForConstantEvaluation =
  13510. isPotentiallyConstantEvaluatedContext(*this) &&
  13511. isImplicitlyDefinableConstexprFunction(Func);
  13512. // Determine whether we require a function definition to exist, per
  13513. // C++11 [temp.inst]p3:
  13514. // Unless a function template specialization has been explicitly
  13515. // instantiated or explicitly specialized, the function template
  13516. // specialization is implicitly instantiated when the specialization is
  13517. // referenced in a context that requires a function definition to exist.
  13518. // C++20 [temp.inst]p7:
  13519. // The existence of a definition of a [...] function is considered to
  13520. // affect the semantics of the program if the [...] function is needed for
  13521. // constant evaluation by an expression
  13522. // C++20 [basic.def.odr]p10:
  13523. // Every program shall contain exactly one definition of every non-inline
  13524. // function or variable that is odr-used in that program outside of a
  13525. // discarded statement
  13526. // C++20 [special]p1:
  13527. // The implementation will implicitly define [defaulted special members]
  13528. // if they are odr-used or needed for constant evaluation.
  13529. //
  13530. // Note that we skip the implicit instantiation of templates that are only
  13531. // used in unused default arguments or by recursive calls to themselves.
  13532. // This is formally non-conforming, but seems reasonable in practice.
  13533. bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
  13534. NeededForConstantEvaluation);
  13535. // C++14 [temp.expl.spec]p6:
  13536. // If a template [...] is explicitly specialized then that specialization
  13537. // shall be declared before the first use of that specialization that would
  13538. // cause an implicit instantiation to take place, in every translation unit
  13539. // in which such a use occurs
  13540. if (NeedDefinition &&
  13541. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  13542. Func->getMemberSpecializationInfo()))
  13543. checkSpecializationVisibility(Loc, Func);
  13544. // C++14 [except.spec]p17:
  13545. // An exception-specification is considered to be needed when:
  13546. // - the function is odr-used or, if it appears in an unevaluated operand,
  13547. // would be odr-used if the expression were potentially-evaluated;
  13548. //
  13549. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  13550. // function is a pure virtual function we're calling, and in that case the
  13551. // function was selected by overload resolution and we need to resolve its
  13552. // exception specification for a different reason.
  13553. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  13554. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  13555. ResolveExceptionSpec(Loc, FPT);
  13556. if (getLangOpts().CUDA)
  13557. CheckCUDACall(Loc, Func);
  13558. // If we need a definition, try to create one.
  13559. if (NeedDefinition && !Func->getBody()) {
  13560. runWithSufficientStackSpace(Loc, [&] {
  13561. if (CXXConstructorDecl *Constructor =
  13562. dyn_cast<CXXConstructorDecl>(Func)) {
  13563. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  13564. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  13565. if (Constructor->isDefaultConstructor()) {
  13566. if (Constructor->isTrivial() &&
  13567. !Constructor->hasAttr<DLLExportAttr>())
  13568. return;
  13569. DefineImplicitDefaultConstructor(Loc, Constructor);
  13570. } else if (Constructor->isCopyConstructor()) {
  13571. DefineImplicitCopyConstructor(Loc, Constructor);
  13572. } else if (Constructor->isMoveConstructor()) {
  13573. DefineImplicitMoveConstructor(Loc, Constructor);
  13574. }
  13575. } else if (Constructor->getInheritedConstructor()) {
  13576. DefineInheritingConstructor(Loc, Constructor);
  13577. }
  13578. } else if (CXXDestructorDecl *Destructor =
  13579. dyn_cast<CXXDestructorDecl>(Func)) {
  13580. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  13581. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  13582. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  13583. return;
  13584. DefineImplicitDestructor(Loc, Destructor);
  13585. }
  13586. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  13587. MarkVTableUsed(Loc, Destructor->getParent());
  13588. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  13589. if (MethodDecl->isOverloadedOperator() &&
  13590. MethodDecl->getOverloadedOperator() == OO_Equal) {
  13591. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  13592. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  13593. if (MethodDecl->isCopyAssignmentOperator())
  13594. DefineImplicitCopyAssignment(Loc, MethodDecl);
  13595. else if (MethodDecl->isMoveAssignmentOperator())
  13596. DefineImplicitMoveAssignment(Loc, MethodDecl);
  13597. }
  13598. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  13599. MethodDecl->getParent()->isLambda()) {
  13600. CXXConversionDecl *Conversion =
  13601. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  13602. if (Conversion->isLambdaToBlockPointerConversion())
  13603. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  13604. else
  13605. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  13606. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  13607. MarkVTableUsed(Loc, MethodDecl->getParent());
  13608. }
  13609. // Implicit instantiation of function templates and member functions of
  13610. // class templates.
  13611. if (Func->isImplicitlyInstantiable()) {
  13612. TemplateSpecializationKind TSK =
  13613. Func->getTemplateSpecializationKindForInstantiation();
  13614. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  13615. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13616. if (FirstInstantiation) {
  13617. PointOfInstantiation = Loc;
  13618. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13619. } else if (TSK != TSK_ImplicitInstantiation) {
  13620. // Use the point of use as the point of instantiation, instead of the
  13621. // point of explicit instantiation (which we track as the actual point
  13622. // of instantiation). This gives better backtraces in diagnostics.
  13623. PointOfInstantiation = Loc;
  13624. }
  13625. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  13626. Func->isConstexpr()) {
  13627. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  13628. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  13629. CodeSynthesisContexts.size())
  13630. PendingLocalImplicitInstantiations.push_back(
  13631. std::make_pair(Func, PointOfInstantiation));
  13632. else if (Func->isConstexpr())
  13633. // Do not defer instantiations of constexpr functions, to avoid the
  13634. // expression evaluator needing to call back into Sema if it sees a
  13635. // call to such a function.
  13636. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  13637. else {
  13638. Func->setInstantiationIsPending(true);
  13639. PendingInstantiations.push_back(
  13640. std::make_pair(Func, PointOfInstantiation));
  13641. // Notify the consumer that a function was implicitly instantiated.
  13642. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  13643. }
  13644. }
  13645. } else {
  13646. // Walk redefinitions, as some of them may be instantiable.
  13647. for (auto i : Func->redecls()) {
  13648. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  13649. MarkFunctionReferenced(Loc, i, MightBeOdrUse);
  13650. }
  13651. }
  13652. });
  13653. }
  13654. // If this is the first "real" use, act on that.
  13655. if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
  13656. // Keep track of used but undefined functions.
  13657. if (!Func->isDefined()) {
  13658. if (mightHaveNonExternalLinkage(Func))
  13659. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13660. else if (Func->getMostRecentDecl()->isInlined() &&
  13661. !LangOpts.GNUInline &&
  13662. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  13663. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13664. else if (isExternalWithNoLinkageType(Func))
  13665. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13666. }
  13667. // Some x86 Windows calling conventions mangle the size of the parameter
  13668. // pack into the name. Computing the size of the parameters requires the
  13669. // parameter types to be complete. Check that now.
  13670. if (funcHasParameterSizeMangling(*this, Func))
  13671. CheckCompleteParameterTypesForMangler(*this, Func, Loc);
  13672. Func->markUsed(Context);
  13673. }
  13674. if (LangOpts.OpenMP) {
  13675. markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
  13676. if (LangOpts.OpenMPIsDevice)
  13677. checkOpenMPDeviceFunction(Loc, Func);
  13678. else
  13679. checkOpenMPHostFunction(Loc, Func);
  13680. }
  13681. }
  13682. /// Directly mark a variable odr-used. Given a choice, prefer to use
  13683. /// MarkVariableReferenced since it does additional checks and then
  13684. /// calls MarkVarDeclODRUsed.
  13685. /// If the variable must be captured:
  13686. /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
  13687. /// - else capture it in the DeclContext that maps to the
  13688. /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
  13689. static void
  13690. MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
  13691. const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
  13692. // Keep track of used but undefined variables.
  13693. // FIXME: We shouldn't suppress this warning for static data members.
  13694. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  13695. (!Var->isExternallyVisible() || Var->isInline() ||
  13696. SemaRef.isExternalWithNoLinkageType(Var)) &&
  13697. !(Var->isStaticDataMember() && Var->hasInit())) {
  13698. SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
  13699. if (old.isInvalid())
  13700. old = Loc;
  13701. }
  13702. QualType CaptureType, DeclRefType;
  13703. if (SemaRef.LangOpts.OpenMP)
  13704. SemaRef.tryCaptureOpenMPLambdas(Var);
  13705. SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
  13706. /*EllipsisLoc*/ SourceLocation(),
  13707. /*BuildAndDiagnose*/ true,
  13708. CaptureType, DeclRefType,
  13709. FunctionScopeIndexToStopAt);
  13710. Var->markUsed(SemaRef.Context);
  13711. }
  13712. void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
  13713. SourceLocation Loc,
  13714. unsigned CapturingScopeIndex) {
  13715. MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
  13716. }
  13717. static void
  13718. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  13719. ValueDecl *var, DeclContext *DC) {
  13720. DeclContext *VarDC = var->getDeclContext();
  13721. // If the parameter still belongs to the translation unit, then
  13722. // we're actually just using one parameter in the declaration of
  13723. // the next.
  13724. if (isa<ParmVarDecl>(var) &&
  13725. isa<TranslationUnitDecl>(VarDC))
  13726. return;
  13727. // For C code, don't diagnose about capture if we're not actually in code
  13728. // right now; it's impossible to write a non-constant expression outside of
  13729. // function context, so we'll get other (more useful) diagnostics later.
  13730. //
  13731. // For C++, things get a bit more nasty... it would be nice to suppress this
  13732. // diagnostic for certain cases like using a local variable in an array bound
  13733. // for a member of a local class, but the correct predicate is not obvious.
  13734. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  13735. return;
  13736. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  13737. unsigned ContextKind = 3; // unknown
  13738. if (isa<CXXMethodDecl>(VarDC) &&
  13739. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  13740. ContextKind = 2;
  13741. } else if (isa<FunctionDecl>(VarDC)) {
  13742. ContextKind = 0;
  13743. } else if (isa<BlockDecl>(VarDC)) {
  13744. ContextKind = 1;
  13745. }
  13746. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  13747. << var << ValueKind << ContextKind << VarDC;
  13748. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  13749. << var;
  13750. // FIXME: Add additional diagnostic info about class etc. which prevents
  13751. // capture.
  13752. }
  13753. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  13754. bool &SubCapturesAreNested,
  13755. QualType &CaptureType,
  13756. QualType &DeclRefType) {
  13757. // Check whether we've already captured it.
  13758. if (CSI->CaptureMap.count(Var)) {
  13759. // If we found a capture, any subcaptures are nested.
  13760. SubCapturesAreNested = true;
  13761. // Retrieve the capture type for this variable.
  13762. CaptureType = CSI->getCapture(Var).getCaptureType();
  13763. // Compute the type of an expression that refers to this variable.
  13764. DeclRefType = CaptureType.getNonReferenceType();
  13765. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  13766. // are mutable in the sense that user can change their value - they are
  13767. // private instances of the captured declarations.
  13768. const Capture &Cap = CSI->getCapture(Var);
  13769. if (Cap.isCopyCapture() &&
  13770. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  13771. !(isa<CapturedRegionScopeInfo>(CSI) &&
  13772. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  13773. DeclRefType.addConst();
  13774. return true;
  13775. }
  13776. return false;
  13777. }
  13778. // Only block literals, captured statements, and lambda expressions can
  13779. // capture; other scopes don't work.
  13780. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  13781. SourceLocation Loc,
  13782. const bool Diagnose, Sema &S) {
  13783. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  13784. return getLambdaAwareParentOfDeclContext(DC);
  13785. else if (Var->hasLocalStorage()) {
  13786. if (Diagnose)
  13787. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  13788. }
  13789. return nullptr;
  13790. }
  13791. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13792. // certain types of variables (unnamed, variably modified types etc.)
  13793. // so check for eligibility.
  13794. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  13795. SourceLocation Loc,
  13796. const bool Diagnose, Sema &S) {
  13797. bool IsBlock = isa<BlockScopeInfo>(CSI);
  13798. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  13799. // Lambdas are not allowed to capture unnamed variables
  13800. // (e.g. anonymous unions).
  13801. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  13802. // assuming that's the intent.
  13803. if (IsLambda && !Var->getDeclName()) {
  13804. if (Diagnose) {
  13805. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  13806. S.Diag(Var->getLocation(), diag::note_declared_at);
  13807. }
  13808. return false;
  13809. }
  13810. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  13811. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  13812. if (Diagnose) {
  13813. S.Diag(Loc, diag::err_ref_vm_type);
  13814. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13815. << Var->getDeclName();
  13816. }
  13817. return false;
  13818. }
  13819. // Prohibit structs with flexible array members too.
  13820. // We cannot capture what is in the tail end of the struct.
  13821. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  13822. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  13823. if (Diagnose) {
  13824. if (IsBlock)
  13825. S.Diag(Loc, diag::err_ref_flexarray_type);
  13826. else
  13827. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  13828. << Var->getDeclName();
  13829. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13830. << Var->getDeclName();
  13831. }
  13832. return false;
  13833. }
  13834. }
  13835. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13836. // Lambdas and captured statements are not allowed to capture __block
  13837. // variables; they don't support the expected semantics.
  13838. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  13839. if (Diagnose) {
  13840. S.Diag(Loc, diag::err_capture_block_variable)
  13841. << Var->getDeclName() << !IsLambda;
  13842. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13843. << Var->getDeclName();
  13844. }
  13845. return false;
  13846. }
  13847. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  13848. if (S.getLangOpts().OpenCL && IsBlock &&
  13849. Var->getType()->isBlockPointerType()) {
  13850. if (Diagnose)
  13851. S.Diag(Loc, diag::err_opencl_block_ref_block);
  13852. return false;
  13853. }
  13854. return true;
  13855. }
  13856. // Returns true if the capture by block was successful.
  13857. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  13858. SourceLocation Loc,
  13859. const bool BuildAndDiagnose,
  13860. QualType &CaptureType,
  13861. QualType &DeclRefType,
  13862. const bool Nested,
  13863. Sema &S, bool Invalid) {
  13864. bool ByRef = false;
  13865. // Blocks are not allowed to capture arrays, excepting OpenCL.
  13866. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  13867. // (decayed to pointers).
  13868. if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  13869. if (BuildAndDiagnose) {
  13870. S.Diag(Loc, diag::err_ref_array_type);
  13871. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13872. << Var->getDeclName();
  13873. Invalid = true;
  13874. } else {
  13875. return false;
  13876. }
  13877. }
  13878. // Forbid the block-capture of autoreleasing variables.
  13879. if (!Invalid &&
  13880. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13881. if (BuildAndDiagnose) {
  13882. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  13883. << /*block*/ 0;
  13884. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13885. << Var->getDeclName();
  13886. Invalid = true;
  13887. } else {
  13888. return false;
  13889. }
  13890. }
  13891. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  13892. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  13893. QualType PointeeTy = PT->getPointeeType();
  13894. if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
  13895. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  13896. !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
  13897. if (BuildAndDiagnose) {
  13898. SourceLocation VarLoc = Var->getLocation();
  13899. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  13900. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  13901. }
  13902. }
  13903. }
  13904. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13905. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  13906. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  13907. // Block capture by reference does not change the capture or
  13908. // declaration reference types.
  13909. ByRef = true;
  13910. } else {
  13911. // Block capture by copy introduces 'const'.
  13912. CaptureType = CaptureType.getNonReferenceType().withConst();
  13913. DeclRefType = CaptureType;
  13914. }
  13915. // Actually capture the variable.
  13916. if (BuildAndDiagnose)
  13917. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
  13918. CaptureType, Invalid);
  13919. return !Invalid;
  13920. }
  13921. /// Capture the given variable in the captured region.
  13922. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  13923. VarDecl *Var,
  13924. SourceLocation Loc,
  13925. const bool BuildAndDiagnose,
  13926. QualType &CaptureType,
  13927. QualType &DeclRefType,
  13928. const bool RefersToCapturedVariable,
  13929. Sema &S, bool Invalid) {
  13930. // By default, capture variables by reference.
  13931. bool ByRef = true;
  13932. // Using an LValue reference type is consistent with Lambdas (see below).
  13933. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  13934. if (S.isOpenMPCapturedDecl(Var)) {
  13935. bool HasConst = DeclRefType.isConstQualified();
  13936. DeclRefType = DeclRefType.getUnqualifiedType();
  13937. // Don't lose diagnostics about assignments to const.
  13938. if (HasConst)
  13939. DeclRefType.addConst();
  13940. }
  13941. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
  13942. RSI->OpenMPCaptureLevel);
  13943. }
  13944. if (ByRef)
  13945. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13946. else
  13947. CaptureType = DeclRefType;
  13948. // Actually capture the variable.
  13949. if (BuildAndDiagnose)
  13950. RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
  13951. Loc, SourceLocation(), CaptureType, Invalid);
  13952. return !Invalid;
  13953. }
  13954. /// Capture the given variable in the lambda.
  13955. static bool captureInLambda(LambdaScopeInfo *LSI,
  13956. VarDecl *Var,
  13957. SourceLocation Loc,
  13958. const bool BuildAndDiagnose,
  13959. QualType &CaptureType,
  13960. QualType &DeclRefType,
  13961. const bool RefersToCapturedVariable,
  13962. const Sema::TryCaptureKind Kind,
  13963. SourceLocation EllipsisLoc,
  13964. const bool IsTopScope,
  13965. Sema &S, bool Invalid) {
  13966. // Determine whether we are capturing by reference or by value.
  13967. bool ByRef = false;
  13968. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  13969. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  13970. } else {
  13971. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  13972. }
  13973. // Compute the type of the field that will capture this variable.
  13974. if (ByRef) {
  13975. // C++11 [expr.prim.lambda]p15:
  13976. // An entity is captured by reference if it is implicitly or
  13977. // explicitly captured but not captured by copy. It is
  13978. // unspecified whether additional unnamed non-static data
  13979. // members are declared in the closure type for entities
  13980. // captured by reference.
  13981. //
  13982. // FIXME: It is not clear whether we want to build an lvalue reference
  13983. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  13984. // to do the former, while EDG does the latter. Core issue 1249 will
  13985. // clarify, but for now we follow GCC because it's a more permissive and
  13986. // easily defensible position.
  13987. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13988. } else {
  13989. // C++11 [expr.prim.lambda]p14:
  13990. // For each entity captured by copy, an unnamed non-static
  13991. // data member is declared in the closure type. The
  13992. // declaration order of these members is unspecified. The type
  13993. // of such a data member is the type of the corresponding
  13994. // captured entity if the entity is not a reference to an
  13995. // object, or the referenced type otherwise. [Note: If the
  13996. // captured entity is a reference to a function, the
  13997. // corresponding data member is also a reference to a
  13998. // function. - end note ]
  13999. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  14000. if (!RefType->getPointeeType()->isFunctionType())
  14001. CaptureType = RefType->getPointeeType();
  14002. }
  14003. // Forbid the lambda copy-capture of autoreleasing variables.
  14004. if (!Invalid &&
  14005. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  14006. if (BuildAndDiagnose) {
  14007. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  14008. S.Diag(Var->getLocation(), diag::note_previous_decl)
  14009. << Var->getDeclName();
  14010. Invalid = true;
  14011. } else {
  14012. return false;
  14013. }
  14014. }
  14015. // Make sure that by-copy captures are of a complete and non-abstract type.
  14016. if (!Invalid && BuildAndDiagnose) {
  14017. if (!CaptureType->isDependentType() &&
  14018. S.RequireCompleteType(Loc, CaptureType,
  14019. diag::err_capture_of_incomplete_type,
  14020. Var->getDeclName()))
  14021. Invalid = true;
  14022. else if (S.RequireNonAbstractType(Loc, CaptureType,
  14023. diag::err_capture_of_abstract_type))
  14024. Invalid = true;
  14025. }
  14026. }
  14027. // Compute the type of a reference to this captured variable.
  14028. if (ByRef)
  14029. DeclRefType = CaptureType.getNonReferenceType();
  14030. else {
  14031. // C++ [expr.prim.lambda]p5:
  14032. // The closure type for a lambda-expression has a public inline
  14033. // function call operator [...]. This function call operator is
  14034. // declared const (9.3.1) if and only if the lambda-expression's
  14035. // parameter-declaration-clause is not followed by mutable.
  14036. DeclRefType = CaptureType.getNonReferenceType();
  14037. if (!LSI->Mutable && !CaptureType->isReferenceType())
  14038. DeclRefType.addConst();
  14039. }
  14040. // Add the capture.
  14041. if (BuildAndDiagnose)
  14042. LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
  14043. Loc, EllipsisLoc, CaptureType, Invalid);
  14044. return !Invalid;
  14045. }
  14046. bool Sema::tryCaptureVariable(
  14047. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  14048. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  14049. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  14050. // An init-capture is notionally from the context surrounding its
  14051. // declaration, but its parent DC is the lambda class.
  14052. DeclContext *VarDC = Var->getDeclContext();
  14053. if (Var->isInitCapture())
  14054. VarDC = VarDC->getParent();
  14055. DeclContext *DC = CurContext;
  14056. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  14057. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  14058. // We need to sync up the Declaration Context with the
  14059. // FunctionScopeIndexToStopAt
  14060. if (FunctionScopeIndexToStopAt) {
  14061. unsigned FSIndex = FunctionScopes.size() - 1;
  14062. while (FSIndex != MaxFunctionScopesIndex) {
  14063. DC = getLambdaAwareParentOfDeclContext(DC);
  14064. --FSIndex;
  14065. }
  14066. }
  14067. // If the variable is declared in the current context, there is no need to
  14068. // capture it.
  14069. if (VarDC == DC) return true;
  14070. // Capture global variables if it is required to use private copy of this
  14071. // variable.
  14072. bool IsGlobal = !Var->hasLocalStorage();
  14073. if (IsGlobal &&
  14074. !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
  14075. MaxFunctionScopesIndex)))
  14076. return true;
  14077. Var = Var->getCanonicalDecl();
  14078. // Walk up the stack to determine whether we can capture the variable,
  14079. // performing the "simple" checks that don't depend on type. We stop when
  14080. // we've either hit the declared scope of the variable or find an existing
  14081. // capture of that variable. We start from the innermost capturing-entity
  14082. // (the DC) and ensure that all intervening capturing-entities
  14083. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  14084. // declcontext can either capture the variable or have already captured
  14085. // the variable.
  14086. CaptureType = Var->getType();
  14087. DeclRefType = CaptureType.getNonReferenceType();
  14088. bool Nested = false;
  14089. bool Explicit = (Kind != TryCapture_Implicit);
  14090. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  14091. do {
  14092. // Only block literals, captured statements, and lambda expressions can
  14093. // capture; other scopes don't work.
  14094. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  14095. ExprLoc,
  14096. BuildAndDiagnose,
  14097. *this);
  14098. // We need to check for the parent *first* because, if we *have*
  14099. // private-captured a global variable, we need to recursively capture it in
  14100. // intermediate blocks, lambdas, etc.
  14101. if (!ParentDC) {
  14102. if (IsGlobal) {
  14103. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  14104. break;
  14105. }
  14106. return true;
  14107. }
  14108. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  14109. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  14110. // Check whether we've already captured it.
  14111. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  14112. DeclRefType)) {
  14113. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  14114. break;
  14115. }
  14116. // If we are instantiating a generic lambda call operator body,
  14117. // we do not want to capture new variables. What was captured
  14118. // during either a lambdas transformation or initial parsing
  14119. // should be used.
  14120. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  14121. if (BuildAndDiagnose) {
  14122. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  14123. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  14124. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  14125. Diag(Var->getLocation(), diag::note_previous_decl)
  14126. << Var->getDeclName();
  14127. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  14128. } else
  14129. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  14130. }
  14131. return true;
  14132. }
  14133. // Try to capture variable-length arrays types.
  14134. if (Var->getType()->isVariablyModifiedType()) {
  14135. // We're going to walk down into the type and look for VLA
  14136. // expressions.
  14137. QualType QTy = Var->getType();
  14138. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  14139. QTy = PVD->getOriginalType();
  14140. captureVariablyModifiedType(Context, QTy, CSI);
  14141. }
  14142. if (getLangOpts().OpenMP) {
  14143. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  14144. // OpenMP private variables should not be captured in outer scope, so
  14145. // just break here. Similarly, global variables that are captured in a
  14146. // target region should not be captured outside the scope of the region.
  14147. if (RSI->CapRegionKind == CR_OpenMP) {
  14148. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  14149. auto IsTargetCap = !IsOpenMPPrivateDecl &&
  14150. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  14151. // When we detect target captures we are looking from inside the
  14152. // target region, therefore we need to propagate the capture from the
  14153. // enclosing region. Therefore, the capture is not initially nested.
  14154. if (IsTargetCap)
  14155. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  14156. if (IsTargetCap || IsOpenMPPrivateDecl) {
  14157. Nested = !IsTargetCap;
  14158. DeclRefType = DeclRefType.getUnqualifiedType();
  14159. CaptureType = Context.getLValueReferenceType(DeclRefType);
  14160. break;
  14161. }
  14162. }
  14163. }
  14164. }
  14165. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  14166. // No capture-default, and this is not an explicit capture
  14167. // so cannot capture this variable.
  14168. if (BuildAndDiagnose) {
  14169. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  14170. Diag(Var->getLocation(), diag::note_previous_decl)
  14171. << Var->getDeclName();
  14172. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  14173. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
  14174. diag::note_lambda_decl);
  14175. // FIXME: If we error out because an outer lambda can not implicitly
  14176. // capture a variable that an inner lambda explicitly captures, we
  14177. // should have the inner lambda do the explicit capture - because
  14178. // it makes for cleaner diagnostics later. This would purely be done
  14179. // so that the diagnostic does not misleadingly claim that a variable
  14180. // can not be captured by a lambda implicitly even though it is captured
  14181. // explicitly. Suggestion:
  14182. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  14183. // at the function head
  14184. // - cache the StartingDeclContext - this must be a lambda
  14185. // - captureInLambda in the innermost lambda the variable.
  14186. }
  14187. return true;
  14188. }
  14189. FunctionScopesIndex--;
  14190. DC = ParentDC;
  14191. Explicit = false;
  14192. } while (!VarDC->Equals(DC));
  14193. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  14194. // computing the type of the capture at each step, checking type-specific
  14195. // requirements, and adding captures if requested.
  14196. // If the variable had already been captured previously, we start capturing
  14197. // at the lambda nested within that one.
  14198. bool Invalid = false;
  14199. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  14200. ++I) {
  14201. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  14202. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  14203. // certain types of variables (unnamed, variably modified types etc.)
  14204. // so check for eligibility.
  14205. if (!Invalid)
  14206. Invalid =
  14207. !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
  14208. // After encountering an error, if we're actually supposed to capture, keep
  14209. // capturing in nested contexts to suppress any follow-on diagnostics.
  14210. if (Invalid && !BuildAndDiagnose)
  14211. return true;
  14212. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  14213. Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  14214. DeclRefType, Nested, *this, Invalid);
  14215. Nested = true;
  14216. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  14217. Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
  14218. CaptureType, DeclRefType, Nested,
  14219. *this, Invalid);
  14220. Nested = true;
  14221. } else {
  14222. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  14223. Invalid =
  14224. !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  14225. DeclRefType, Nested, Kind, EllipsisLoc,
  14226. /*IsTopScope*/ I == N - 1, *this, Invalid);
  14227. Nested = true;
  14228. }
  14229. if (Invalid && !BuildAndDiagnose)
  14230. return true;
  14231. }
  14232. return Invalid;
  14233. }
  14234. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  14235. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  14236. QualType CaptureType;
  14237. QualType DeclRefType;
  14238. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  14239. /*BuildAndDiagnose=*/true, CaptureType,
  14240. DeclRefType, nullptr);
  14241. }
  14242. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  14243. QualType CaptureType;
  14244. QualType DeclRefType;
  14245. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  14246. /*BuildAndDiagnose=*/false, CaptureType,
  14247. DeclRefType, nullptr);
  14248. }
  14249. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  14250. QualType CaptureType;
  14251. QualType DeclRefType;
  14252. // Determine whether we can capture this variable.
  14253. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  14254. /*BuildAndDiagnose=*/false, CaptureType,
  14255. DeclRefType, nullptr))
  14256. return QualType();
  14257. return DeclRefType;
  14258. }
  14259. namespace {
  14260. // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
  14261. // The produced TemplateArgumentListInfo* points to data stored within this
  14262. // object, so should only be used in contexts where the pointer will not be
  14263. // used after the CopiedTemplateArgs object is destroyed.
  14264. class CopiedTemplateArgs {
  14265. bool HasArgs;
  14266. TemplateArgumentListInfo TemplateArgStorage;
  14267. public:
  14268. template<typename RefExpr>
  14269. CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
  14270. if (HasArgs)
  14271. E->copyTemplateArgumentsInto(TemplateArgStorage);
  14272. }
  14273. operator TemplateArgumentListInfo*()
  14274. #ifdef __has_cpp_attribute
  14275. #if __has_cpp_attribute(clang::lifetimebound)
  14276. [[clang::lifetimebound]]
  14277. #endif
  14278. #endif
  14279. {
  14280. return HasArgs ? &TemplateArgStorage : nullptr;
  14281. }
  14282. };
  14283. }
  14284. /// Walk the set of potential results of an expression and mark them all as
  14285. /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
  14286. ///
  14287. /// \return A new expression if we found any potential results, ExprEmpty() if
  14288. /// not, and ExprError() if we diagnosed an error.
  14289. static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
  14290. NonOdrUseReason NOUR) {
  14291. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  14292. // an object that satisfies the requirements for appearing in a
  14293. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  14294. // is immediately applied." This function handles the lvalue-to-rvalue
  14295. // conversion part.
  14296. //
  14297. // If we encounter a node that claims to be an odr-use but shouldn't be, we
  14298. // transform it into the relevant kind of non-odr-use node and rebuild the
  14299. // tree of nodes leading to it.
  14300. //
  14301. // This is a mini-TreeTransform that only transforms a restricted subset of
  14302. // nodes (and only certain operands of them).
  14303. // Rebuild a subexpression.
  14304. auto Rebuild = [&](Expr *Sub) {
  14305. return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
  14306. };
  14307. // Check whether a potential result satisfies the requirements of NOUR.
  14308. auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
  14309. // Any entity other than a VarDecl is always odr-used whenever it's named
  14310. // in a potentially-evaluated expression.
  14311. auto *VD = dyn_cast<VarDecl>(D);
  14312. if (!VD)
  14313. return true;
  14314. // C++2a [basic.def.odr]p4:
  14315. // A variable x whose name appears as a potentially-evalauted expression
  14316. // e is odr-used by e unless
  14317. // -- x is a reference that is usable in constant expressions, or
  14318. // -- x is a variable of non-reference type that is usable in constant
  14319. // expressions and has no mutable subobjects, and e is an element of
  14320. // the set of potential results of an expression of
  14321. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14322. // conversion is applied, or
  14323. // -- x is a variable of non-reference type, and e is an element of the
  14324. // set of potential results of a discarded-value expression to which
  14325. // the lvalue-to-rvalue conversion is not applied
  14326. //
  14327. // We check the first bullet and the "potentially-evaluated" condition in
  14328. // BuildDeclRefExpr. We check the type requirements in the second bullet
  14329. // in CheckLValueToRValueConversionOperand below.
  14330. switch (NOUR) {
  14331. case NOUR_None:
  14332. case NOUR_Unevaluated:
  14333. llvm_unreachable("unexpected non-odr-use-reason");
  14334. case NOUR_Constant:
  14335. // Constant references were handled when they were built.
  14336. if (VD->getType()->isReferenceType())
  14337. return true;
  14338. if (auto *RD = VD->getType()->getAsCXXRecordDecl())
  14339. if (RD->hasMutableFields())
  14340. return true;
  14341. if (!VD->isUsableInConstantExpressions(S.Context))
  14342. return true;
  14343. break;
  14344. case NOUR_Discarded:
  14345. if (VD->getType()->isReferenceType())
  14346. return true;
  14347. break;
  14348. }
  14349. return false;
  14350. };
  14351. // Mark that this expression does not constitute an odr-use.
  14352. auto MarkNotOdrUsed = [&] {
  14353. S.MaybeODRUseExprs.erase(E);
  14354. if (LambdaScopeInfo *LSI = S.getCurLambda())
  14355. LSI->markVariableExprAsNonODRUsed(E);
  14356. };
  14357. // C++2a [basic.def.odr]p2:
  14358. // The set of potential results of an expression e is defined as follows:
  14359. switch (E->getStmtClass()) {
  14360. // -- If e is an id-expression, ...
  14361. case Expr::DeclRefExprClass: {
  14362. auto *DRE = cast<DeclRefExpr>(E);
  14363. if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
  14364. break;
  14365. // Rebuild as a non-odr-use DeclRefExpr.
  14366. MarkNotOdrUsed();
  14367. return DeclRefExpr::Create(
  14368. S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
  14369. DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
  14370. DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
  14371. DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
  14372. }
  14373. case Expr::FunctionParmPackExprClass: {
  14374. auto *FPPE = cast<FunctionParmPackExpr>(E);
  14375. // If any of the declarations in the pack is odr-used, then the expression
  14376. // as a whole constitutes an odr-use.
  14377. for (VarDecl *D : *FPPE)
  14378. if (IsPotentialResultOdrUsed(D))
  14379. return ExprEmpty();
  14380. // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
  14381. // nothing cares about whether we marked this as an odr-use, but it might
  14382. // be useful for non-compiler tools.
  14383. MarkNotOdrUsed();
  14384. break;
  14385. }
  14386. // -- If e is a subscripting operation with an array operand...
  14387. case Expr::ArraySubscriptExprClass: {
  14388. auto *ASE = cast<ArraySubscriptExpr>(E);
  14389. Expr *OldBase = ASE->getBase()->IgnoreImplicit();
  14390. if (!OldBase->getType()->isArrayType())
  14391. break;
  14392. ExprResult Base = Rebuild(OldBase);
  14393. if (!Base.isUsable())
  14394. return Base;
  14395. Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
  14396. Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
  14397. SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
  14398. return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
  14399. ASE->getRBracketLoc());
  14400. }
  14401. case Expr::MemberExprClass: {
  14402. auto *ME = cast<MemberExpr>(E);
  14403. // -- If e is a class member access expression [...] naming a non-static
  14404. // data member...
  14405. if (isa<FieldDecl>(ME->getMemberDecl())) {
  14406. ExprResult Base = Rebuild(ME->getBase());
  14407. if (!Base.isUsable())
  14408. return Base;
  14409. return MemberExpr::Create(
  14410. S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
  14411. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
  14412. ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
  14413. CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
  14414. ME->getObjectKind(), ME->isNonOdrUse());
  14415. }
  14416. if (ME->getMemberDecl()->isCXXInstanceMember())
  14417. break;
  14418. // -- If e is a class member access expression naming a static data member,
  14419. // ...
  14420. if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
  14421. break;
  14422. // Rebuild as a non-odr-use MemberExpr.
  14423. MarkNotOdrUsed();
  14424. return MemberExpr::Create(
  14425. S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
  14426. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
  14427. ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
  14428. ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
  14429. return ExprEmpty();
  14430. }
  14431. case Expr::BinaryOperatorClass: {
  14432. auto *BO = cast<BinaryOperator>(E);
  14433. Expr *LHS = BO->getLHS();
  14434. Expr *RHS = BO->getRHS();
  14435. // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
  14436. if (BO->getOpcode() == BO_PtrMemD) {
  14437. ExprResult Sub = Rebuild(LHS);
  14438. if (!Sub.isUsable())
  14439. return Sub;
  14440. LHS = Sub.get();
  14441. // -- If e is a comma expression, ...
  14442. } else if (BO->getOpcode() == BO_Comma) {
  14443. ExprResult Sub = Rebuild(RHS);
  14444. if (!Sub.isUsable())
  14445. return Sub;
  14446. RHS = Sub.get();
  14447. } else {
  14448. break;
  14449. }
  14450. return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
  14451. LHS, RHS);
  14452. }
  14453. // -- If e has the form (e1)...
  14454. case Expr::ParenExprClass: {
  14455. auto *PE = cast<ParenExpr>(E);
  14456. ExprResult Sub = Rebuild(PE->getSubExpr());
  14457. if (!Sub.isUsable())
  14458. return Sub;
  14459. return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
  14460. }
  14461. // -- If e is a glvalue conditional expression, ...
  14462. // We don't apply this to a binary conditional operator. FIXME: Should we?
  14463. case Expr::ConditionalOperatorClass: {
  14464. auto *CO = cast<ConditionalOperator>(E);
  14465. ExprResult LHS = Rebuild(CO->getLHS());
  14466. if (LHS.isInvalid())
  14467. return ExprError();
  14468. ExprResult RHS = Rebuild(CO->getRHS());
  14469. if (RHS.isInvalid())
  14470. return ExprError();
  14471. if (!LHS.isUsable() && !RHS.isUsable())
  14472. return ExprEmpty();
  14473. if (!LHS.isUsable())
  14474. LHS = CO->getLHS();
  14475. if (!RHS.isUsable())
  14476. RHS = CO->getRHS();
  14477. return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
  14478. CO->getCond(), LHS.get(), RHS.get());
  14479. }
  14480. // [Clang extension]
  14481. // -- If e has the form __extension__ e1...
  14482. case Expr::UnaryOperatorClass: {
  14483. auto *UO = cast<UnaryOperator>(E);
  14484. if (UO->getOpcode() != UO_Extension)
  14485. break;
  14486. ExprResult Sub = Rebuild(UO->getSubExpr());
  14487. if (!Sub.isUsable())
  14488. return Sub;
  14489. return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
  14490. Sub.get());
  14491. }
  14492. // [Clang extension]
  14493. // -- If e has the form _Generic(...), the set of potential results is the
  14494. // union of the sets of potential results of the associated expressions.
  14495. case Expr::GenericSelectionExprClass: {
  14496. auto *GSE = cast<GenericSelectionExpr>(E);
  14497. SmallVector<Expr *, 4> AssocExprs;
  14498. bool AnyChanged = false;
  14499. for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
  14500. ExprResult AssocExpr = Rebuild(OrigAssocExpr);
  14501. if (AssocExpr.isInvalid())
  14502. return ExprError();
  14503. if (AssocExpr.isUsable()) {
  14504. AssocExprs.push_back(AssocExpr.get());
  14505. AnyChanged = true;
  14506. } else {
  14507. AssocExprs.push_back(OrigAssocExpr);
  14508. }
  14509. }
  14510. return AnyChanged ? S.CreateGenericSelectionExpr(
  14511. GSE->getGenericLoc(), GSE->getDefaultLoc(),
  14512. GSE->getRParenLoc(), GSE->getControllingExpr(),
  14513. GSE->getAssocTypeSourceInfos(), AssocExprs)
  14514. : ExprEmpty();
  14515. }
  14516. // [Clang extension]
  14517. // -- If e has the form __builtin_choose_expr(...), the set of potential
  14518. // results is the union of the sets of potential results of the
  14519. // second and third subexpressions.
  14520. case Expr::ChooseExprClass: {
  14521. auto *CE = cast<ChooseExpr>(E);
  14522. ExprResult LHS = Rebuild(CE->getLHS());
  14523. if (LHS.isInvalid())
  14524. return ExprError();
  14525. ExprResult RHS = Rebuild(CE->getLHS());
  14526. if (RHS.isInvalid())
  14527. return ExprError();
  14528. if (!LHS.get() && !RHS.get())
  14529. return ExprEmpty();
  14530. if (!LHS.isUsable())
  14531. LHS = CE->getLHS();
  14532. if (!RHS.isUsable())
  14533. RHS = CE->getRHS();
  14534. return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
  14535. RHS.get(), CE->getRParenLoc());
  14536. }
  14537. // Step through non-syntactic nodes.
  14538. case Expr::ConstantExprClass: {
  14539. auto *CE = cast<ConstantExpr>(E);
  14540. ExprResult Sub = Rebuild(CE->getSubExpr());
  14541. if (!Sub.isUsable())
  14542. return Sub;
  14543. return ConstantExpr::Create(S.Context, Sub.get());
  14544. }
  14545. // We could mostly rely on the recursive rebuilding to rebuild implicit
  14546. // casts, but not at the top level, so rebuild them here.
  14547. case Expr::ImplicitCastExprClass: {
  14548. auto *ICE = cast<ImplicitCastExpr>(E);
  14549. // Only step through the narrow set of cast kinds we expect to encounter.
  14550. // Anything else suggests we've left the region in which potential results
  14551. // can be found.
  14552. switch (ICE->getCastKind()) {
  14553. case CK_NoOp:
  14554. case CK_DerivedToBase:
  14555. case CK_UncheckedDerivedToBase: {
  14556. ExprResult Sub = Rebuild(ICE->getSubExpr());
  14557. if (!Sub.isUsable())
  14558. return Sub;
  14559. CXXCastPath Path(ICE->path());
  14560. return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
  14561. ICE->getValueKind(), &Path);
  14562. }
  14563. default:
  14564. break;
  14565. }
  14566. break;
  14567. }
  14568. default:
  14569. break;
  14570. }
  14571. // Can't traverse through this node. Nothing to do.
  14572. return ExprEmpty();
  14573. }
  14574. ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
  14575. // Check whether the operand is or contains an object of non-trivial C union
  14576. // type.
  14577. if (E->getType().isVolatileQualified() &&
  14578. (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  14579. E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
  14580. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  14581. Sema::NTCUC_LValueToRValueVolatile,
  14582. NTCUK_Destruct|NTCUK_Copy);
  14583. // C++2a [basic.def.odr]p4:
  14584. // [...] an expression of non-volatile-qualified non-class type to which
  14585. // the lvalue-to-rvalue conversion is applied [...]
  14586. if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
  14587. return E;
  14588. ExprResult Result =
  14589. rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
  14590. if (Result.isInvalid())
  14591. return ExprError();
  14592. return Result.get() ? Result : E;
  14593. }
  14594. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  14595. Res = CorrectDelayedTyposInExpr(Res);
  14596. if (!Res.isUsable())
  14597. return Res;
  14598. // If a constant-expression is a reference to a variable where we delay
  14599. // deciding whether it is an odr-use, just assume we will apply the
  14600. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  14601. // (a non-type template argument), we have special handling anyway.
  14602. return CheckLValueToRValueConversionOperand(Res.get());
  14603. }
  14604. void Sema::CleanupVarDeclMarking() {
  14605. // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
  14606. // call.
  14607. MaybeODRUseExprSet LocalMaybeODRUseExprs;
  14608. std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
  14609. for (Expr *E : LocalMaybeODRUseExprs) {
  14610. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  14611. MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
  14612. DRE->getLocation(), *this);
  14613. } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
  14614. MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
  14615. *this);
  14616. } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
  14617. for (VarDecl *VD : *FP)
  14618. MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
  14619. } else {
  14620. llvm_unreachable("Unexpected expression");
  14621. }
  14622. }
  14623. assert(MaybeODRUseExprs.empty() &&
  14624. "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
  14625. }
  14626. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  14627. VarDecl *Var, Expr *E) {
  14628. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
  14629. isa<FunctionParmPackExpr>(E)) &&
  14630. "Invalid Expr argument to DoMarkVarDeclReferenced");
  14631. Var->setReferenced();
  14632. if (Var->isInvalidDecl())
  14633. return;
  14634. auto *MSI = Var->getMemberSpecializationInfo();
  14635. TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
  14636. : Var->getTemplateSpecializationKind();
  14637. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  14638. bool UsableInConstantExpr =
  14639. Var->mightBeUsableInConstantExpressions(SemaRef.Context);
  14640. // C++20 [expr.const]p12:
  14641. // A variable [...] is needed for constant evaluation if it is [...] a
  14642. // variable whose name appears as a potentially constant evaluated
  14643. // expression that is either a contexpr variable or is of non-volatile
  14644. // const-qualified integral type or of reference type
  14645. bool NeededForConstantEvaluation =
  14646. isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
  14647. bool NeedDefinition =
  14648. OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
  14649. VarTemplateSpecializationDecl *VarSpec =
  14650. dyn_cast<VarTemplateSpecializationDecl>(Var);
  14651. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  14652. "Can't instantiate a partial template specialization.");
  14653. // If this might be a member specialization of a static data member, check
  14654. // the specialization is visible. We already did the checks for variable
  14655. // template specializations when we created them.
  14656. if (NeedDefinition && TSK != TSK_Undeclared &&
  14657. !isa<VarTemplateSpecializationDecl>(Var))
  14658. SemaRef.checkSpecializationVisibility(Loc, Var);
  14659. // Perform implicit instantiation of static data members, static data member
  14660. // templates of class templates, and variable template specializations. Delay
  14661. // instantiations of variable templates, except for those that could be used
  14662. // in a constant expression.
  14663. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  14664. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  14665. // instantiation declaration if a variable is usable in a constant
  14666. // expression (among other cases).
  14667. bool TryInstantiating =
  14668. TSK == TSK_ImplicitInstantiation ||
  14669. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  14670. if (TryInstantiating) {
  14671. SourceLocation PointOfInstantiation =
  14672. MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
  14673. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  14674. if (FirstInstantiation) {
  14675. PointOfInstantiation = Loc;
  14676. if (MSI)
  14677. MSI->setPointOfInstantiation(PointOfInstantiation);
  14678. else
  14679. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  14680. }
  14681. bool InstantiationDependent = false;
  14682. bool IsNonDependent =
  14683. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  14684. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  14685. : true;
  14686. // Do not instantiate specializations that are still type-dependent.
  14687. if (IsNonDependent) {
  14688. if (UsableInConstantExpr) {
  14689. // Do not defer instantiations of variables that could be used in a
  14690. // constant expression.
  14691. SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
  14692. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  14693. });
  14694. } else if (FirstInstantiation ||
  14695. isa<VarTemplateSpecializationDecl>(Var)) {
  14696. // FIXME: For a specialization of a variable template, we don't
  14697. // distinguish between "declaration and type implicitly instantiated"
  14698. // and "implicit instantiation of definition requested", so we have
  14699. // no direct way to avoid enqueueing the pending instantiation
  14700. // multiple times.
  14701. SemaRef.PendingInstantiations
  14702. .push_back(std::make_pair(Var, PointOfInstantiation));
  14703. }
  14704. }
  14705. }
  14706. }
  14707. // C++2a [basic.def.odr]p4:
  14708. // A variable x whose name appears as a potentially-evaluated expression e
  14709. // is odr-used by e unless
  14710. // -- x is a reference that is usable in constant expressions
  14711. // -- x is a variable of non-reference type that is usable in constant
  14712. // expressions and has no mutable subobjects [FIXME], and e is an
  14713. // element of the set of potential results of an expression of
  14714. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14715. // conversion is applied
  14716. // -- x is a variable of non-reference type, and e is an element of the set
  14717. // of potential results of a discarded-value expression to which the
  14718. // lvalue-to-rvalue conversion is not applied [FIXME]
  14719. //
  14720. // We check the first part of the second bullet here, and
  14721. // Sema::CheckLValueToRValueConversionOperand deals with the second part.
  14722. // FIXME: To get the third bullet right, we need to delay this even for
  14723. // variables that are not usable in constant expressions.
  14724. // If we already know this isn't an odr-use, there's nothing more to do.
  14725. if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  14726. if (DRE->isNonOdrUse())
  14727. return;
  14728. if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
  14729. if (ME->isNonOdrUse())
  14730. return;
  14731. switch (OdrUse) {
  14732. case OdrUseContext::None:
  14733. assert((!E || isa<FunctionParmPackExpr>(E)) &&
  14734. "missing non-odr-use marking for unevaluated decl ref");
  14735. break;
  14736. case OdrUseContext::FormallyOdrUsed:
  14737. // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
  14738. // behavior.
  14739. break;
  14740. case OdrUseContext::Used:
  14741. // If we might later find that this expression isn't actually an odr-use,
  14742. // delay the marking.
  14743. if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
  14744. SemaRef.MaybeODRUseExprs.insert(E);
  14745. else
  14746. MarkVarDeclODRUsed(Var, Loc, SemaRef);
  14747. break;
  14748. case OdrUseContext::Dependent:
  14749. // If this is a dependent context, we don't need to mark variables as
  14750. // odr-used, but we may still need to track them for lambda capture.
  14751. // FIXME: Do we also need to do this inside dependent typeid expressions
  14752. // (which are modeled as unevaluated at this point)?
  14753. const bool RefersToEnclosingScope =
  14754. (SemaRef.CurContext != Var->getDeclContext() &&
  14755. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  14756. if (RefersToEnclosingScope) {
  14757. LambdaScopeInfo *const LSI =
  14758. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  14759. if (LSI && (!LSI->CallOperator ||
  14760. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  14761. // If a variable could potentially be odr-used, defer marking it so
  14762. // until we finish analyzing the full expression for any
  14763. // lvalue-to-rvalue
  14764. // or discarded value conversions that would obviate odr-use.
  14765. // Add it to the list of potential captures that will be analyzed
  14766. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  14767. // unless the variable is a reference that was initialized by a constant
  14768. // expression (this will never need to be captured or odr-used).
  14769. //
  14770. // FIXME: We can simplify this a lot after implementing P0588R1.
  14771. assert(E && "Capture variable should be used in an expression.");
  14772. if (!Var->getType()->isReferenceType() ||
  14773. !Var->isUsableInConstantExpressions(SemaRef.Context))
  14774. LSI->addPotentialCapture(E->IgnoreParens());
  14775. }
  14776. }
  14777. break;
  14778. }
  14779. }
  14780. /// Mark a variable referenced, and check whether it is odr-used
  14781. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  14782. /// used directly for normal expressions referring to VarDecl.
  14783. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  14784. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  14785. }
  14786. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  14787. Decl *D, Expr *E, bool MightBeOdrUse) {
  14788. if (SemaRef.isInOpenMPDeclareTargetContext())
  14789. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  14790. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  14791. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  14792. return;
  14793. }
  14794. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  14795. // If this is a call to a method via a cast, also mark the method in the
  14796. // derived class used in case codegen can devirtualize the call.
  14797. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  14798. if (!ME)
  14799. return;
  14800. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  14801. if (!MD)
  14802. return;
  14803. // Only attempt to devirtualize if this is truly a virtual call.
  14804. bool IsVirtualCall = MD->isVirtual() &&
  14805. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  14806. if (!IsVirtualCall)
  14807. return;
  14808. // If it's possible to devirtualize the call, mark the called function
  14809. // referenced.
  14810. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  14811. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  14812. if (DM)
  14813. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  14814. }
  14815. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  14816. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  14817. // TODO: update this with DR# once a defect report is filed.
  14818. // C++11 defect. The address of a pure member should not be an ODR use, even
  14819. // if it's a qualified reference.
  14820. bool OdrUse = true;
  14821. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  14822. if (Method->isVirtual() &&
  14823. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  14824. OdrUse = false;
  14825. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  14826. }
  14827. /// Perform reference-marking and odr-use handling for a MemberExpr.
  14828. void Sema::MarkMemberReferenced(MemberExpr *E) {
  14829. // C++11 [basic.def.odr]p2:
  14830. // A non-overloaded function whose name appears as a potentially-evaluated
  14831. // expression or a member of a set of candidate functions, if selected by
  14832. // overload resolution when referred to from a potentially-evaluated
  14833. // expression, is odr-used, unless it is a pure virtual function and its
  14834. // name is not explicitly qualified.
  14835. bool MightBeOdrUse = true;
  14836. if (E->performsVirtualDispatch(getLangOpts())) {
  14837. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  14838. if (Method->isPure())
  14839. MightBeOdrUse = false;
  14840. }
  14841. SourceLocation Loc =
  14842. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  14843. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  14844. }
  14845. /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
  14846. void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
  14847. for (VarDecl *VD : *E)
  14848. MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
  14849. }
  14850. /// Perform marking for a reference to an arbitrary declaration. It
  14851. /// marks the declaration referenced, and performs odr-use checking for
  14852. /// functions and variables. This method should not be used when building a
  14853. /// normal expression which refers to a variable.
  14854. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  14855. bool MightBeOdrUse) {
  14856. if (MightBeOdrUse) {
  14857. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14858. MarkVariableReferenced(Loc, VD);
  14859. return;
  14860. }
  14861. }
  14862. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14863. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  14864. return;
  14865. }
  14866. D->setReferenced();
  14867. }
  14868. namespace {
  14869. // Mark all of the declarations used by a type as referenced.
  14870. // FIXME: Not fully implemented yet! We need to have a better understanding
  14871. // of when we're entering a context we should not recurse into.
  14872. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  14873. // TreeTransforms rebuilding the type in a new context. Rather than
  14874. // duplicating the TreeTransform logic, we should consider reusing it here.
  14875. // Currently that causes problems when rebuilding LambdaExprs.
  14876. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  14877. Sema &S;
  14878. SourceLocation Loc;
  14879. public:
  14880. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  14881. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  14882. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  14883. };
  14884. }
  14885. bool MarkReferencedDecls::TraverseTemplateArgument(
  14886. const TemplateArgument &Arg) {
  14887. {
  14888. // A non-type template argument is a constant-evaluated context.
  14889. EnterExpressionEvaluationContext Evaluated(
  14890. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  14891. if (Arg.getKind() == TemplateArgument::Declaration) {
  14892. if (Decl *D = Arg.getAsDecl())
  14893. S.MarkAnyDeclReferenced(Loc, D, true);
  14894. } else if (Arg.getKind() == TemplateArgument::Expression) {
  14895. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  14896. }
  14897. }
  14898. return Inherited::TraverseTemplateArgument(Arg);
  14899. }
  14900. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  14901. MarkReferencedDecls Marker(*this, Loc);
  14902. Marker.TraverseType(T);
  14903. }
  14904. namespace {
  14905. /// Helper class that marks all of the declarations referenced by
  14906. /// potentially-evaluated subexpressions as "referenced".
  14907. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  14908. Sema &S;
  14909. bool SkipLocalVariables;
  14910. public:
  14911. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  14912. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  14913. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  14914. void VisitDeclRefExpr(DeclRefExpr *E) {
  14915. // If we were asked not to visit local variables, don't.
  14916. if (SkipLocalVariables) {
  14917. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  14918. if (VD->hasLocalStorage())
  14919. return;
  14920. }
  14921. S.MarkDeclRefReferenced(E);
  14922. }
  14923. void VisitMemberExpr(MemberExpr *E) {
  14924. S.MarkMemberReferenced(E);
  14925. Inherited::VisitMemberExpr(E);
  14926. }
  14927. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  14928. S.MarkFunctionReferenced(
  14929. E->getBeginLoc(),
  14930. const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
  14931. Visit(E->getSubExpr());
  14932. }
  14933. void VisitCXXNewExpr(CXXNewExpr *E) {
  14934. if (E->getOperatorNew())
  14935. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
  14936. if (E->getOperatorDelete())
  14937. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  14938. Inherited::VisitCXXNewExpr(E);
  14939. }
  14940. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  14941. if (E->getOperatorDelete())
  14942. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  14943. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  14944. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  14945. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  14946. S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
  14947. }
  14948. Inherited::VisitCXXDeleteExpr(E);
  14949. }
  14950. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  14951. S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
  14952. Inherited::VisitCXXConstructExpr(E);
  14953. }
  14954. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  14955. Visit(E->getExpr());
  14956. }
  14957. };
  14958. }
  14959. /// Mark any declarations that appear within this expression or any
  14960. /// potentially-evaluated subexpressions as "referenced".
  14961. ///
  14962. /// \param SkipLocalVariables If true, don't mark local variables as
  14963. /// 'referenced'.
  14964. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  14965. bool SkipLocalVariables) {
  14966. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  14967. }
  14968. /// Emit a diagnostic that describes an effect on the run-time behavior
  14969. /// of the program being compiled.
  14970. ///
  14971. /// This routine emits the given diagnostic when the code currently being
  14972. /// type-checked is "potentially evaluated", meaning that there is a
  14973. /// possibility that the code will actually be executable. Code in sizeof()
  14974. /// expressions, code used only during overload resolution, etc., are not
  14975. /// potentially evaluated. This routine will suppress such diagnostics or,
  14976. /// in the absolutely nutty case of potentially potentially evaluated
  14977. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  14978. /// later.
  14979. ///
  14980. /// This routine should be used for all diagnostics that describe the run-time
  14981. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  14982. /// Failure to do so will likely result in spurious diagnostics or failures
  14983. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  14984. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
  14985. const PartialDiagnostic &PD) {
  14986. switch (ExprEvalContexts.back().Context) {
  14987. case ExpressionEvaluationContext::Unevaluated:
  14988. case ExpressionEvaluationContext::UnevaluatedList:
  14989. case ExpressionEvaluationContext::UnevaluatedAbstract:
  14990. case ExpressionEvaluationContext::DiscardedStatement:
  14991. // The argument will never be evaluated, so don't complain.
  14992. break;
  14993. case ExpressionEvaluationContext::ConstantEvaluated:
  14994. // Relevant diagnostics should be produced by constant evaluation.
  14995. break;
  14996. case ExpressionEvaluationContext::PotentiallyEvaluated:
  14997. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  14998. if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
  14999. FunctionScopes.back()->PossiblyUnreachableDiags.
  15000. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
  15001. return true;
  15002. }
  15003. // The initializer of a constexpr variable or of the first declaration of a
  15004. // static data member is not syntactically a constant evaluated constant,
  15005. // but nonetheless is always required to be a constant expression, so we
  15006. // can skip diagnosing.
  15007. // FIXME: Using the mangling context here is a hack.
  15008. if (auto *VD = dyn_cast_or_null<VarDecl>(
  15009. ExprEvalContexts.back().ManglingContextDecl)) {
  15010. if (VD->isConstexpr() ||
  15011. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  15012. break;
  15013. // FIXME: For any other kind of variable, we should build a CFG for its
  15014. // initializer and check whether the context in question is reachable.
  15015. }
  15016. Diag(Loc, PD);
  15017. return true;
  15018. }
  15019. return false;
  15020. }
  15021. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  15022. const PartialDiagnostic &PD) {
  15023. return DiagRuntimeBehavior(
  15024. Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
  15025. }
  15026. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  15027. CallExpr *CE, FunctionDecl *FD) {
  15028. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  15029. return false;
  15030. // If we're inside a decltype's expression, don't check for a valid return
  15031. // type or construct temporaries until we know whether this is the last call.
  15032. if (ExprEvalContexts.back().ExprContext ==
  15033. ExpressionEvaluationContextRecord::EK_Decltype) {
  15034. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  15035. return false;
  15036. }
  15037. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  15038. FunctionDecl *FD;
  15039. CallExpr *CE;
  15040. public:
  15041. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  15042. : FD(FD), CE(CE) { }
  15043. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  15044. if (!FD) {
  15045. S.Diag(Loc, diag::err_call_incomplete_return)
  15046. << T << CE->getSourceRange();
  15047. return;
  15048. }
  15049. S.Diag(Loc, diag::err_call_function_incomplete_return)
  15050. << CE->getSourceRange() << FD->getDeclName() << T;
  15051. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  15052. << FD->getDeclName();
  15053. }
  15054. } Diagnoser(FD, CE);
  15055. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  15056. return true;
  15057. return false;
  15058. }
  15059. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  15060. // will prevent this condition from triggering, which is what we want.
  15061. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  15062. SourceLocation Loc;
  15063. unsigned diagnostic = diag::warn_condition_is_assignment;
  15064. bool IsOrAssign = false;
  15065. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  15066. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  15067. return;
  15068. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  15069. // Greylist some idioms by putting them into a warning subcategory.
  15070. if (ObjCMessageExpr *ME
  15071. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  15072. Selector Sel = ME->getSelector();
  15073. // self = [<foo> init...]
  15074. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  15075. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  15076. // <foo> = [<bar> nextObject]
  15077. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  15078. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  15079. }
  15080. Loc = Op->getOperatorLoc();
  15081. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  15082. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  15083. return;
  15084. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  15085. Loc = Op->getOperatorLoc();
  15086. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  15087. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  15088. else {
  15089. // Not an assignment.
  15090. return;
  15091. }
  15092. Diag(Loc, diagnostic) << E->getSourceRange();
  15093. SourceLocation Open = E->getBeginLoc();
  15094. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  15095. Diag(Loc, diag::note_condition_assign_silence)
  15096. << FixItHint::CreateInsertion(Open, "(")
  15097. << FixItHint::CreateInsertion(Close, ")");
  15098. if (IsOrAssign)
  15099. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  15100. << FixItHint::CreateReplacement(Loc, "!=");
  15101. else
  15102. Diag(Loc, diag::note_condition_assign_to_comparison)
  15103. << FixItHint::CreateReplacement(Loc, "==");
  15104. }
  15105. /// Redundant parentheses over an equality comparison can indicate
  15106. /// that the user intended an assignment used as condition.
  15107. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  15108. // Don't warn if the parens came from a macro.
  15109. SourceLocation parenLoc = ParenE->getBeginLoc();
  15110. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  15111. return;
  15112. // Don't warn for dependent expressions.
  15113. if (ParenE->isTypeDependent())
  15114. return;
  15115. Expr *E = ParenE->IgnoreParens();
  15116. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  15117. if (opE->getOpcode() == BO_EQ &&
  15118. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  15119. == Expr::MLV_Valid) {
  15120. SourceLocation Loc = opE->getOperatorLoc();
  15121. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  15122. SourceRange ParenERange = ParenE->getSourceRange();
  15123. Diag(Loc, diag::note_equality_comparison_silence)
  15124. << FixItHint::CreateRemoval(ParenERange.getBegin())
  15125. << FixItHint::CreateRemoval(ParenERange.getEnd());
  15126. Diag(Loc, diag::note_equality_comparison_to_assign)
  15127. << FixItHint::CreateReplacement(Loc, "=");
  15128. }
  15129. }
  15130. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  15131. bool IsConstexpr) {
  15132. DiagnoseAssignmentAsCondition(E);
  15133. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  15134. DiagnoseEqualityWithExtraParens(parenE);
  15135. ExprResult result = CheckPlaceholderExpr(E);
  15136. if (result.isInvalid()) return ExprError();
  15137. E = result.get();
  15138. if (!E->isTypeDependent()) {
  15139. if (getLangOpts().CPlusPlus)
  15140. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  15141. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  15142. if (ERes.isInvalid())
  15143. return ExprError();
  15144. E = ERes.get();
  15145. QualType T = E->getType();
  15146. if (!T->isScalarType()) { // C99 6.8.4.1p1
  15147. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  15148. << T << E->getSourceRange();
  15149. return ExprError();
  15150. }
  15151. CheckBoolLikeConversion(E, Loc);
  15152. }
  15153. return E;
  15154. }
  15155. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  15156. Expr *SubExpr, ConditionKind CK) {
  15157. // Empty conditions are valid in for-statements.
  15158. if (!SubExpr)
  15159. return ConditionResult();
  15160. ExprResult Cond;
  15161. switch (CK) {
  15162. case ConditionKind::Boolean:
  15163. Cond = CheckBooleanCondition(Loc, SubExpr);
  15164. break;
  15165. case ConditionKind::ConstexprIf:
  15166. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  15167. break;
  15168. case ConditionKind::Switch:
  15169. Cond = CheckSwitchCondition(Loc, SubExpr);
  15170. break;
  15171. }
  15172. if (Cond.isInvalid())
  15173. return ConditionError();
  15174. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  15175. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  15176. if (!FullExpr.get())
  15177. return ConditionError();
  15178. return ConditionResult(*this, nullptr, FullExpr,
  15179. CK == ConditionKind::ConstexprIf);
  15180. }
  15181. namespace {
  15182. /// A visitor for rebuilding a call to an __unknown_any expression
  15183. /// to have an appropriate type.
  15184. struct RebuildUnknownAnyFunction
  15185. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  15186. Sema &S;
  15187. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  15188. ExprResult VisitStmt(Stmt *S) {
  15189. llvm_unreachable("unexpected statement!");
  15190. }
  15191. ExprResult VisitExpr(Expr *E) {
  15192. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  15193. << E->getSourceRange();
  15194. return ExprError();
  15195. }
  15196. /// Rebuild an expression which simply semantically wraps another
  15197. /// expression which it shares the type and value kind of.
  15198. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15199. ExprResult SubResult = Visit(E->getSubExpr());
  15200. if (SubResult.isInvalid()) return ExprError();
  15201. Expr *SubExpr = SubResult.get();
  15202. E->setSubExpr(SubExpr);
  15203. E->setType(SubExpr->getType());
  15204. E->setValueKind(SubExpr->getValueKind());
  15205. assert(E->getObjectKind() == OK_Ordinary);
  15206. return E;
  15207. }
  15208. ExprResult VisitParenExpr(ParenExpr *E) {
  15209. return rebuildSugarExpr(E);
  15210. }
  15211. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15212. return rebuildSugarExpr(E);
  15213. }
  15214. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15215. ExprResult SubResult = Visit(E->getSubExpr());
  15216. if (SubResult.isInvalid()) return ExprError();
  15217. Expr *SubExpr = SubResult.get();
  15218. E->setSubExpr(SubExpr);
  15219. E->setType(S.Context.getPointerType(SubExpr->getType()));
  15220. assert(E->getValueKind() == VK_RValue);
  15221. assert(E->getObjectKind() == OK_Ordinary);
  15222. return E;
  15223. }
  15224. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  15225. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  15226. E->setType(VD->getType());
  15227. assert(E->getValueKind() == VK_RValue);
  15228. if (S.getLangOpts().CPlusPlus &&
  15229. !(isa<CXXMethodDecl>(VD) &&
  15230. cast<CXXMethodDecl>(VD)->isInstance()))
  15231. E->setValueKind(VK_LValue);
  15232. return E;
  15233. }
  15234. ExprResult VisitMemberExpr(MemberExpr *E) {
  15235. return resolveDecl(E, E->getMemberDecl());
  15236. }
  15237. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15238. return resolveDecl(E, E->getDecl());
  15239. }
  15240. };
  15241. }
  15242. /// Given a function expression of unknown-any type, try to rebuild it
  15243. /// to have a function type.
  15244. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  15245. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  15246. if (Result.isInvalid()) return ExprError();
  15247. return S.DefaultFunctionArrayConversion(Result.get());
  15248. }
  15249. namespace {
  15250. /// A visitor for rebuilding an expression of type __unknown_anytype
  15251. /// into one which resolves the type directly on the referring
  15252. /// expression. Strict preservation of the original source
  15253. /// structure is not a goal.
  15254. struct RebuildUnknownAnyExpr
  15255. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  15256. Sema &S;
  15257. /// The current destination type.
  15258. QualType DestType;
  15259. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  15260. : S(S), DestType(CastType) {}
  15261. ExprResult VisitStmt(Stmt *S) {
  15262. llvm_unreachable("unexpected statement!");
  15263. }
  15264. ExprResult VisitExpr(Expr *E) {
  15265. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15266. << E->getSourceRange();
  15267. return ExprError();
  15268. }
  15269. ExprResult VisitCallExpr(CallExpr *E);
  15270. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  15271. /// Rebuild an expression which simply semantically wraps another
  15272. /// expression which it shares the type and value kind of.
  15273. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15274. ExprResult SubResult = Visit(E->getSubExpr());
  15275. if (SubResult.isInvalid()) return ExprError();
  15276. Expr *SubExpr = SubResult.get();
  15277. E->setSubExpr(SubExpr);
  15278. E->setType(SubExpr->getType());
  15279. E->setValueKind(SubExpr->getValueKind());
  15280. assert(E->getObjectKind() == OK_Ordinary);
  15281. return E;
  15282. }
  15283. ExprResult VisitParenExpr(ParenExpr *E) {
  15284. return rebuildSugarExpr(E);
  15285. }
  15286. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15287. return rebuildSugarExpr(E);
  15288. }
  15289. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15290. const PointerType *Ptr = DestType->getAs<PointerType>();
  15291. if (!Ptr) {
  15292. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  15293. << E->getSourceRange();
  15294. return ExprError();
  15295. }
  15296. if (isa<CallExpr>(E->getSubExpr())) {
  15297. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  15298. << E->getSourceRange();
  15299. return ExprError();
  15300. }
  15301. assert(E->getValueKind() == VK_RValue);
  15302. assert(E->getObjectKind() == OK_Ordinary);
  15303. E->setType(DestType);
  15304. // Build the sub-expression as if it were an object of the pointee type.
  15305. DestType = Ptr->getPointeeType();
  15306. ExprResult SubResult = Visit(E->getSubExpr());
  15307. if (SubResult.isInvalid()) return ExprError();
  15308. E->setSubExpr(SubResult.get());
  15309. return E;
  15310. }
  15311. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  15312. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  15313. ExprResult VisitMemberExpr(MemberExpr *E) {
  15314. return resolveDecl(E, E->getMemberDecl());
  15315. }
  15316. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15317. return resolveDecl(E, E->getDecl());
  15318. }
  15319. };
  15320. }
  15321. /// Rebuilds a call expression which yielded __unknown_anytype.
  15322. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  15323. Expr *CalleeExpr = E->getCallee();
  15324. enum FnKind {
  15325. FK_MemberFunction,
  15326. FK_FunctionPointer,
  15327. FK_BlockPointer
  15328. };
  15329. FnKind Kind;
  15330. QualType CalleeType = CalleeExpr->getType();
  15331. if (CalleeType == S.Context.BoundMemberTy) {
  15332. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  15333. Kind = FK_MemberFunction;
  15334. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  15335. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  15336. CalleeType = Ptr->getPointeeType();
  15337. Kind = FK_FunctionPointer;
  15338. } else {
  15339. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  15340. Kind = FK_BlockPointer;
  15341. }
  15342. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  15343. // Verify that this is a legal result type of a function.
  15344. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15345. unsigned diagID = diag::err_func_returning_array_function;
  15346. if (Kind == FK_BlockPointer)
  15347. diagID = diag::err_block_returning_array_function;
  15348. S.Diag(E->getExprLoc(), diagID)
  15349. << DestType->isFunctionType() << DestType;
  15350. return ExprError();
  15351. }
  15352. // Otherwise, go ahead and set DestType as the call's result.
  15353. E->setType(DestType.getNonLValueExprType(S.Context));
  15354. E->setValueKind(Expr::getValueKindForType(DestType));
  15355. assert(E->getObjectKind() == OK_Ordinary);
  15356. // Rebuild the function type, replacing the result type with DestType.
  15357. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  15358. if (Proto) {
  15359. // __unknown_anytype(...) is a special case used by the debugger when
  15360. // it has no idea what a function's signature is.
  15361. //
  15362. // We want to build this call essentially under the K&R
  15363. // unprototyped rules, but making a FunctionNoProtoType in C++
  15364. // would foul up all sorts of assumptions. However, we cannot
  15365. // simply pass all arguments as variadic arguments, nor can we
  15366. // portably just call the function under a non-variadic type; see
  15367. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  15368. // However, it turns out that in practice it is generally safe to
  15369. // call a function declared as "A foo(B,C,D);" under the prototype
  15370. // "A foo(B,C,D,...);". The only known exception is with the
  15371. // Windows ABI, where any variadic function is implicitly cdecl
  15372. // regardless of its normal CC. Therefore we change the parameter
  15373. // types to match the types of the arguments.
  15374. //
  15375. // This is a hack, but it is far superior to moving the
  15376. // corresponding target-specific code from IR-gen to Sema/AST.
  15377. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  15378. SmallVector<QualType, 8> ArgTypes;
  15379. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  15380. ArgTypes.reserve(E->getNumArgs());
  15381. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  15382. Expr *Arg = E->getArg(i);
  15383. QualType ArgType = Arg->getType();
  15384. if (E->isLValue()) {
  15385. ArgType = S.Context.getLValueReferenceType(ArgType);
  15386. } else if (E->isXValue()) {
  15387. ArgType = S.Context.getRValueReferenceType(ArgType);
  15388. }
  15389. ArgTypes.push_back(ArgType);
  15390. }
  15391. ParamTypes = ArgTypes;
  15392. }
  15393. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  15394. Proto->getExtProtoInfo());
  15395. } else {
  15396. DestType = S.Context.getFunctionNoProtoType(DestType,
  15397. FnType->getExtInfo());
  15398. }
  15399. // Rebuild the appropriate pointer-to-function type.
  15400. switch (Kind) {
  15401. case FK_MemberFunction:
  15402. // Nothing to do.
  15403. break;
  15404. case FK_FunctionPointer:
  15405. DestType = S.Context.getPointerType(DestType);
  15406. break;
  15407. case FK_BlockPointer:
  15408. DestType = S.Context.getBlockPointerType(DestType);
  15409. break;
  15410. }
  15411. // Finally, we can recurse.
  15412. ExprResult CalleeResult = Visit(CalleeExpr);
  15413. if (!CalleeResult.isUsable()) return ExprError();
  15414. E->setCallee(CalleeResult.get());
  15415. // Bind a temporary if necessary.
  15416. return S.MaybeBindToTemporary(E);
  15417. }
  15418. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  15419. // Verify that this is a legal result type of a call.
  15420. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15421. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  15422. << DestType->isFunctionType() << DestType;
  15423. return ExprError();
  15424. }
  15425. // Rewrite the method result type if available.
  15426. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  15427. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  15428. Method->setReturnType(DestType);
  15429. }
  15430. // Change the type of the message.
  15431. E->setType(DestType.getNonReferenceType());
  15432. E->setValueKind(Expr::getValueKindForType(DestType));
  15433. return S.MaybeBindToTemporary(E);
  15434. }
  15435. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  15436. // The only case we should ever see here is a function-to-pointer decay.
  15437. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  15438. assert(E->getValueKind() == VK_RValue);
  15439. assert(E->getObjectKind() == OK_Ordinary);
  15440. E->setType(DestType);
  15441. // Rebuild the sub-expression as the pointee (function) type.
  15442. DestType = DestType->castAs<PointerType>()->getPointeeType();
  15443. ExprResult Result = Visit(E->getSubExpr());
  15444. if (!Result.isUsable()) return ExprError();
  15445. E->setSubExpr(Result.get());
  15446. return E;
  15447. } else if (E->getCastKind() == CK_LValueToRValue) {
  15448. assert(E->getValueKind() == VK_RValue);
  15449. assert(E->getObjectKind() == OK_Ordinary);
  15450. assert(isa<BlockPointerType>(E->getType()));
  15451. E->setType(DestType);
  15452. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  15453. DestType = S.Context.getLValueReferenceType(DestType);
  15454. ExprResult Result = Visit(E->getSubExpr());
  15455. if (!Result.isUsable()) return ExprError();
  15456. E->setSubExpr(Result.get());
  15457. return E;
  15458. } else {
  15459. llvm_unreachable("Unhandled cast type!");
  15460. }
  15461. }
  15462. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  15463. ExprValueKind ValueKind = VK_LValue;
  15464. QualType Type = DestType;
  15465. // We know how to make this work for certain kinds of decls:
  15466. // - functions
  15467. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  15468. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  15469. DestType = Ptr->getPointeeType();
  15470. ExprResult Result = resolveDecl(E, VD);
  15471. if (Result.isInvalid()) return ExprError();
  15472. return S.ImpCastExprToType(Result.get(), Type,
  15473. CK_FunctionToPointerDecay, VK_RValue);
  15474. }
  15475. if (!Type->isFunctionType()) {
  15476. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  15477. << VD << E->getSourceRange();
  15478. return ExprError();
  15479. }
  15480. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  15481. // We must match the FunctionDecl's type to the hack introduced in
  15482. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  15483. // type. See the lengthy commentary in that routine.
  15484. QualType FDT = FD->getType();
  15485. const FunctionType *FnType = FDT->castAs<FunctionType>();
  15486. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  15487. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  15488. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  15489. SourceLocation Loc = FD->getLocation();
  15490. FunctionDecl *NewFD = FunctionDecl::Create(
  15491. S.Context, FD->getDeclContext(), Loc, Loc,
  15492. FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
  15493. SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
  15494. /*ConstexprKind*/ CSK_unspecified);
  15495. if (FD->getQualifier())
  15496. NewFD->setQualifierInfo(FD->getQualifierLoc());
  15497. SmallVector<ParmVarDecl*, 16> Params;
  15498. for (const auto &AI : FT->param_types()) {
  15499. ParmVarDecl *Param =
  15500. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  15501. Param->setScopeInfo(0, Params.size());
  15502. Params.push_back(Param);
  15503. }
  15504. NewFD->setParams(Params);
  15505. DRE->setDecl(NewFD);
  15506. VD = DRE->getDecl();
  15507. }
  15508. }
  15509. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  15510. if (MD->isInstance()) {
  15511. ValueKind = VK_RValue;
  15512. Type = S.Context.BoundMemberTy;
  15513. }
  15514. // Function references aren't l-values in C.
  15515. if (!S.getLangOpts().CPlusPlus)
  15516. ValueKind = VK_RValue;
  15517. // - variables
  15518. } else if (isa<VarDecl>(VD)) {
  15519. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  15520. Type = RefTy->getPointeeType();
  15521. } else if (Type->isFunctionType()) {
  15522. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  15523. << VD << E->getSourceRange();
  15524. return ExprError();
  15525. }
  15526. // - nothing else
  15527. } else {
  15528. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  15529. << VD << E->getSourceRange();
  15530. return ExprError();
  15531. }
  15532. // Modifying the declaration like this is friendly to IR-gen but
  15533. // also really dangerous.
  15534. VD->setType(DestType);
  15535. E->setType(Type);
  15536. E->setValueKind(ValueKind);
  15537. return E;
  15538. }
  15539. /// Check a cast of an unknown-any type. We intentionally only
  15540. /// trigger this for C-style casts.
  15541. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  15542. Expr *CastExpr, CastKind &CastKind,
  15543. ExprValueKind &VK, CXXCastPath &Path) {
  15544. // The type we're casting to must be either void or complete.
  15545. if (!CastType->isVoidType() &&
  15546. RequireCompleteType(TypeRange.getBegin(), CastType,
  15547. diag::err_typecheck_cast_to_incomplete))
  15548. return ExprError();
  15549. // Rewrite the casted expression from scratch.
  15550. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  15551. if (!result.isUsable()) return ExprError();
  15552. CastExpr = result.get();
  15553. VK = CastExpr->getValueKind();
  15554. CastKind = CK_NoOp;
  15555. return CastExpr;
  15556. }
  15557. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  15558. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  15559. }
  15560. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  15561. Expr *arg, QualType &paramType) {
  15562. // If the syntactic form of the argument is not an explicit cast of
  15563. // any sort, just do default argument promotion.
  15564. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  15565. if (!castArg) {
  15566. ExprResult result = DefaultArgumentPromotion(arg);
  15567. if (result.isInvalid()) return ExprError();
  15568. paramType = result.get()->getType();
  15569. return result;
  15570. }
  15571. // Otherwise, use the type that was written in the explicit cast.
  15572. assert(!arg->hasPlaceholderType());
  15573. paramType = castArg->getTypeAsWritten();
  15574. // Copy-initialize a parameter of that type.
  15575. InitializedEntity entity =
  15576. InitializedEntity::InitializeParameter(Context, paramType,
  15577. /*consumed*/ false);
  15578. return PerformCopyInitialization(entity, callLoc, arg);
  15579. }
  15580. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  15581. Expr *orig = E;
  15582. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  15583. while (true) {
  15584. E = E->IgnoreParenImpCasts();
  15585. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  15586. E = call->getCallee();
  15587. diagID = diag::err_uncasted_call_of_unknown_any;
  15588. } else {
  15589. break;
  15590. }
  15591. }
  15592. SourceLocation loc;
  15593. NamedDecl *d;
  15594. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  15595. loc = ref->getLocation();
  15596. d = ref->getDecl();
  15597. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  15598. loc = mem->getMemberLoc();
  15599. d = mem->getMemberDecl();
  15600. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  15601. diagID = diag::err_uncasted_call_of_unknown_any;
  15602. loc = msg->getSelectorStartLoc();
  15603. d = msg->getMethodDecl();
  15604. if (!d) {
  15605. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  15606. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  15607. << orig->getSourceRange();
  15608. return ExprError();
  15609. }
  15610. } else {
  15611. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15612. << E->getSourceRange();
  15613. return ExprError();
  15614. }
  15615. S.Diag(loc, diagID) << d << orig->getSourceRange();
  15616. // Never recoverable.
  15617. return ExprError();
  15618. }
  15619. /// Check for operands with placeholder types and complain if found.
  15620. /// Returns ExprError() if there was an error and no recovery was possible.
  15621. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  15622. if (!getLangOpts().CPlusPlus) {
  15623. // C cannot handle TypoExpr nodes on either side of a binop because it
  15624. // doesn't handle dependent types properly, so make sure any TypoExprs have
  15625. // been dealt with before checking the operands.
  15626. ExprResult Result = CorrectDelayedTyposInExpr(E);
  15627. if (!Result.isUsable()) return ExprError();
  15628. E = Result.get();
  15629. }
  15630. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  15631. if (!placeholderType) return E;
  15632. switch (placeholderType->getKind()) {
  15633. // Overloaded expressions.
  15634. case BuiltinType::Overload: {
  15635. // Try to resolve a single function template specialization.
  15636. // This is obligatory.
  15637. ExprResult Result = E;
  15638. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  15639. return Result;
  15640. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  15641. // leaves Result unchanged on failure.
  15642. Result = E;
  15643. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  15644. return Result;
  15645. // If that failed, try to recover with a call.
  15646. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  15647. /*complain*/ true);
  15648. return Result;
  15649. }
  15650. // Bound member functions.
  15651. case BuiltinType::BoundMember: {
  15652. ExprResult result = E;
  15653. const Expr *BME = E->IgnoreParens();
  15654. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  15655. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  15656. if (isa<CXXPseudoDestructorExpr>(BME)) {
  15657. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  15658. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  15659. if (ME->getMemberNameInfo().getName().getNameKind() ==
  15660. DeclarationName::CXXDestructorName)
  15661. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  15662. }
  15663. tryToRecoverWithCall(result, PD,
  15664. /*complain*/ true);
  15665. return result;
  15666. }
  15667. // ARC unbridged casts.
  15668. case BuiltinType::ARCUnbridgedCast: {
  15669. Expr *realCast = stripARCUnbridgedCast(E);
  15670. diagnoseARCUnbridgedCast(realCast);
  15671. return realCast;
  15672. }
  15673. // Expressions of unknown type.
  15674. case BuiltinType::UnknownAny:
  15675. return diagnoseUnknownAnyExpr(*this, E);
  15676. // Pseudo-objects.
  15677. case BuiltinType::PseudoObject:
  15678. return checkPseudoObjectRValue(E);
  15679. case BuiltinType::BuiltinFn: {
  15680. // Accept __noop without parens by implicitly converting it to a call expr.
  15681. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  15682. if (DRE) {
  15683. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  15684. if (FD->getBuiltinID() == Builtin::BI__noop) {
  15685. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  15686. CK_BuiltinFnToFnPtr)
  15687. .get();
  15688. return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
  15689. VK_RValue, SourceLocation());
  15690. }
  15691. }
  15692. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  15693. return ExprError();
  15694. }
  15695. // Expressions of unknown type.
  15696. case BuiltinType::OMPArraySection:
  15697. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  15698. return ExprError();
  15699. // Everything else should be impossible.
  15700. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  15701. case BuiltinType::Id:
  15702. #include "clang/Basic/OpenCLImageTypes.def"
  15703. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  15704. case BuiltinType::Id:
  15705. #include "clang/Basic/OpenCLExtensionTypes.def"
  15706. #define SVE_TYPE(Name, Id, SingletonId) \
  15707. case BuiltinType::Id:
  15708. #include "clang/Basic/AArch64SVEACLETypes.def"
  15709. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  15710. #define PLACEHOLDER_TYPE(Id, SingletonId)
  15711. #include "clang/AST/BuiltinTypes.def"
  15712. break;
  15713. }
  15714. llvm_unreachable("invalid placeholder type!");
  15715. }
  15716. bool Sema::CheckCaseExpression(Expr *E) {
  15717. if (E->isTypeDependent())
  15718. return true;
  15719. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  15720. return E->getType()->isIntegralOrEnumerationType();
  15721. return false;
  15722. }
  15723. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  15724. ExprResult
  15725. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  15726. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  15727. "Unknown Objective-C Boolean value!");
  15728. QualType BoolT = Context.ObjCBuiltinBoolTy;
  15729. if (!Context.getBOOLDecl()) {
  15730. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  15731. Sema::LookupOrdinaryName);
  15732. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  15733. NamedDecl *ND = Result.getFoundDecl();
  15734. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  15735. Context.setBOOLDecl(TD);
  15736. }
  15737. }
  15738. if (Context.getBOOLDecl())
  15739. BoolT = Context.getBOOLType();
  15740. return new (Context)
  15741. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  15742. }
  15743. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  15744. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  15745. SourceLocation RParen) {
  15746. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  15747. auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  15748. return Spec.getPlatform() == Platform;
  15749. });
  15750. VersionTuple Version;
  15751. if (Spec != AvailSpecs.end())
  15752. Version = Spec->getVersion();
  15753. // The use of `@available` in the enclosing function should be analyzed to
  15754. // warn when it's used inappropriately (i.e. not if(@available)).
  15755. if (getCurFunctionOrMethodDecl())
  15756. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  15757. else if (getCurBlock() || getCurLambda())
  15758. getCurFunction()->HasPotentialAvailabilityViolations = true;
  15759. return new (Context)
  15760. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  15761. }