SemaChecking.cpp 570 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606
  1. //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
  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 extra semantic analysis beyond what is enforced
  10. // by the C type system.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/APValue.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/AttrIterator.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclarationName.h"
  23. #include "clang/AST/EvaluatedExprVisitor.h"
  24. #include "clang/AST/Expr.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/ExprObjC.h"
  27. #include "clang/AST/ExprOpenMP.h"
  28. #include "clang/AST/FormatString.h"
  29. #include "clang/AST/NSAPI.h"
  30. #include "clang/AST/NonTrivialTypeVisitor.h"
  31. #include "clang/AST/OperationKinds.h"
  32. #include "clang/AST/Stmt.h"
  33. #include "clang/AST/TemplateBase.h"
  34. #include "clang/AST/Type.h"
  35. #include "clang/AST/TypeLoc.h"
  36. #include "clang/AST/UnresolvedSet.h"
  37. #include "clang/Basic/AddressSpaces.h"
  38. #include "clang/Basic/CharInfo.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/IdentifierTable.h"
  41. #include "clang/Basic/LLVM.h"
  42. #include "clang/Basic/LangOptions.h"
  43. #include "clang/Basic/OpenCLOptions.h"
  44. #include "clang/Basic/OperatorKinds.h"
  45. #include "clang/Basic/PartialDiagnostic.h"
  46. #include "clang/Basic/SourceLocation.h"
  47. #include "clang/Basic/SourceManager.h"
  48. #include "clang/Basic/Specifiers.h"
  49. #include "clang/Basic/SyncScope.h"
  50. #include "clang/Basic/TargetBuiltins.h"
  51. #include "clang/Basic/TargetCXXABI.h"
  52. #include "clang/Basic/TargetInfo.h"
  53. #include "clang/Basic/TypeTraits.h"
  54. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  55. #include "clang/Sema/Initialization.h"
  56. #include "clang/Sema/Lookup.h"
  57. #include "clang/Sema/Ownership.h"
  58. #include "clang/Sema/Scope.h"
  59. #include "clang/Sema/ScopeInfo.h"
  60. #include "clang/Sema/Sema.h"
  61. #include "clang/Sema/SemaInternal.h"
  62. #include "llvm/ADT/APFloat.h"
  63. #include "llvm/ADT/APInt.h"
  64. #include "llvm/ADT/APSInt.h"
  65. #include "llvm/ADT/ArrayRef.h"
  66. #include "llvm/ADT/DenseMap.h"
  67. #include "llvm/ADT/FoldingSet.h"
  68. #include "llvm/ADT/None.h"
  69. #include "llvm/ADT/Optional.h"
  70. #include "llvm/ADT/STLExtras.h"
  71. #include "llvm/ADT/SmallBitVector.h"
  72. #include "llvm/ADT/SmallPtrSet.h"
  73. #include "llvm/ADT/SmallString.h"
  74. #include "llvm/ADT/SmallVector.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/StringSwitch.h"
  77. #include "llvm/ADT/Triple.h"
  78. #include "llvm/Support/AtomicOrdering.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/ConvertUTF.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/Format.h"
  84. #include "llvm/Support/Locale.h"
  85. #include "llvm/Support/MathExtras.h"
  86. #include "llvm/Support/SaveAndRestore.h"
  87. #include "llvm/Support/raw_ostream.h"
  88. #include <algorithm>
  89. #include <cassert>
  90. #include <cstddef>
  91. #include <cstdint>
  92. #include <functional>
  93. #include <limits>
  94. #include <string>
  95. #include <tuple>
  96. #include <utility>
  97. using namespace clang;
  98. using namespace sema;
  99. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  100. unsigned ByteNo) const {
  101. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  102. Context.getTargetInfo());
  103. }
  104. /// Checks that a call expression's argument count is the desired number.
  105. /// This is useful when doing custom type-checking. Returns true on error.
  106. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  107. unsigned argCount = call->getNumArgs();
  108. if (argCount == desiredArgCount) return false;
  109. if (argCount < desiredArgCount)
  110. return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
  111. << 0 /*function call*/ << desiredArgCount << argCount
  112. << call->getSourceRange();
  113. // Highlight all the excess arguments.
  114. SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
  115. call->getArg(argCount - 1)->getEndLoc());
  116. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  117. << 0 /*function call*/ << desiredArgCount << argCount
  118. << call->getArg(1)->getSourceRange();
  119. }
  120. /// Check that the first argument to __builtin_annotation is an integer
  121. /// and the second argument is a non-wide string literal.
  122. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  123. if (checkArgCount(S, TheCall, 2))
  124. return true;
  125. // First argument should be an integer.
  126. Expr *ValArg = TheCall->getArg(0);
  127. QualType Ty = ValArg->getType();
  128. if (!Ty->isIntegerType()) {
  129. S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
  130. << ValArg->getSourceRange();
  131. return true;
  132. }
  133. // Second argument should be a constant string.
  134. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  135. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  136. if (!Literal || !Literal->isAscii()) {
  137. S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
  138. << StrArg->getSourceRange();
  139. return true;
  140. }
  141. TheCall->setType(Ty);
  142. return false;
  143. }
  144. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  145. // We need at least one argument.
  146. if (TheCall->getNumArgs() < 1) {
  147. S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  148. << 0 << 1 << TheCall->getNumArgs()
  149. << TheCall->getCallee()->getSourceRange();
  150. return true;
  151. }
  152. // All arguments should be wide string literals.
  153. for (Expr *Arg : TheCall->arguments()) {
  154. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  155. if (!Literal || !Literal->isWide()) {
  156. S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
  157. << Arg->getSourceRange();
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  164. /// result type to the corresponding pointer type.
  165. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  166. if (checkArgCount(S, TheCall, 1))
  167. return true;
  168. ExprResult Arg(TheCall->getArg(0));
  169. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
  170. if (ResultType.isNull())
  171. return true;
  172. TheCall->setArg(0, Arg.get());
  173. TheCall->setType(ResultType);
  174. return false;
  175. }
  176. /// Check the number of arguments and set the result type to
  177. /// the argument type.
  178. static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
  179. if (checkArgCount(S, TheCall, 1))
  180. return true;
  181. TheCall->setType(TheCall->getArg(0)->getType());
  182. return false;
  183. }
  184. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  185. if (checkArgCount(S, TheCall, 3))
  186. return true;
  187. // First two arguments should be integers.
  188. for (unsigned I = 0; I < 2; ++I) {
  189. ExprResult Arg = TheCall->getArg(I);
  190. QualType Ty = Arg.get()->getType();
  191. if (!Ty->isIntegerType()) {
  192. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  193. << Ty << Arg.get()->getSourceRange();
  194. return true;
  195. }
  196. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  197. S.getASTContext(), Ty, /*consume*/ false);
  198. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  199. if (Arg.isInvalid())
  200. return true;
  201. TheCall->setArg(I, Arg.get());
  202. }
  203. // Third argument should be a pointer to a non-const integer.
  204. // IRGen correctly handles volatile, restrict, and address spaces, and
  205. // the other qualifiers aren't possible.
  206. {
  207. ExprResult Arg = TheCall->getArg(2);
  208. QualType Ty = Arg.get()->getType();
  209. const auto *PtrTy = Ty->getAs<PointerType>();
  210. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  211. !PtrTy->getPointeeType().isConstQualified())) {
  212. S.Diag(Arg.get()->getBeginLoc(),
  213. diag::err_overflow_builtin_must_be_ptr_int)
  214. << Ty << Arg.get()->getSourceRange();
  215. return true;
  216. }
  217. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  218. S.getASTContext(), Ty, /*consume*/ false);
  219. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  220. if (Arg.isInvalid())
  221. return true;
  222. TheCall->setArg(2, Arg.get());
  223. }
  224. return false;
  225. }
  226. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  227. if (checkArgCount(S, BuiltinCall, 2))
  228. return true;
  229. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  230. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  231. Expr *Call = BuiltinCall->getArg(0);
  232. Expr *Chain = BuiltinCall->getArg(1);
  233. if (Call->getStmtClass() != Stmt::CallExprClass) {
  234. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  235. << Call->getSourceRange();
  236. return true;
  237. }
  238. auto CE = cast<CallExpr>(Call);
  239. if (CE->getCallee()->getType()->isBlockPointerType()) {
  240. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  241. << Call->getSourceRange();
  242. return true;
  243. }
  244. const Decl *TargetDecl = CE->getCalleeDecl();
  245. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  246. if (FD->getBuiltinID()) {
  247. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  248. << Call->getSourceRange();
  249. return true;
  250. }
  251. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  252. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  253. << Call->getSourceRange();
  254. return true;
  255. }
  256. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  257. if (ChainResult.isInvalid())
  258. return true;
  259. if (!ChainResult.get()->getType()->isPointerType()) {
  260. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  261. << Chain->getSourceRange();
  262. return true;
  263. }
  264. QualType ReturnTy = CE->getCallReturnType(S.Context);
  265. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  266. QualType BuiltinTy = S.Context.getFunctionType(
  267. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  268. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  269. Builtin =
  270. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  271. BuiltinCall->setType(CE->getType());
  272. BuiltinCall->setValueKind(CE->getValueKind());
  273. BuiltinCall->setObjectKind(CE->getObjectKind());
  274. BuiltinCall->setCallee(Builtin);
  275. BuiltinCall->setArg(1, ChainResult.get());
  276. return false;
  277. }
  278. /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
  279. /// __builtin_*_chk function, then use the object size argument specified in the
  280. /// source. Otherwise, infer the object size using __builtin_object_size.
  281. void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
  282. CallExpr *TheCall) {
  283. // FIXME: There are some more useful checks we could be doing here:
  284. // - Analyze the format string of sprintf to see how much of buffer is used.
  285. // - Evaluate strlen of strcpy arguments, use as object size.
  286. if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
  287. isConstantEvaluated())
  288. return;
  289. unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
  290. if (!BuiltinID)
  291. return;
  292. unsigned DiagID = 0;
  293. bool IsChkVariant = false;
  294. unsigned SizeIndex, ObjectIndex;
  295. switch (BuiltinID) {
  296. default:
  297. return;
  298. case Builtin::BI__builtin___memcpy_chk:
  299. case Builtin::BI__builtin___memmove_chk:
  300. case Builtin::BI__builtin___memset_chk:
  301. case Builtin::BI__builtin___strlcat_chk:
  302. case Builtin::BI__builtin___strlcpy_chk:
  303. case Builtin::BI__builtin___strncat_chk:
  304. case Builtin::BI__builtin___strncpy_chk:
  305. case Builtin::BI__builtin___stpncpy_chk:
  306. case Builtin::BI__builtin___memccpy_chk: {
  307. DiagID = diag::warn_builtin_chk_overflow;
  308. IsChkVariant = true;
  309. SizeIndex = TheCall->getNumArgs() - 2;
  310. ObjectIndex = TheCall->getNumArgs() - 1;
  311. break;
  312. }
  313. case Builtin::BI__builtin___snprintf_chk:
  314. case Builtin::BI__builtin___vsnprintf_chk: {
  315. DiagID = diag::warn_builtin_chk_overflow;
  316. IsChkVariant = true;
  317. SizeIndex = 1;
  318. ObjectIndex = 3;
  319. break;
  320. }
  321. case Builtin::BIstrncat:
  322. case Builtin::BI__builtin_strncat:
  323. case Builtin::BIstrncpy:
  324. case Builtin::BI__builtin_strncpy:
  325. case Builtin::BIstpncpy:
  326. case Builtin::BI__builtin_stpncpy: {
  327. // Whether these functions overflow depends on the runtime strlen of the
  328. // string, not just the buffer size, so emitting the "always overflow"
  329. // diagnostic isn't quite right. We should still diagnose passing a buffer
  330. // size larger than the destination buffer though; this is a runtime abort
  331. // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
  332. DiagID = diag::warn_fortify_source_size_mismatch;
  333. SizeIndex = TheCall->getNumArgs() - 1;
  334. ObjectIndex = 0;
  335. break;
  336. }
  337. case Builtin::BImemcpy:
  338. case Builtin::BI__builtin_memcpy:
  339. case Builtin::BImemmove:
  340. case Builtin::BI__builtin_memmove:
  341. case Builtin::BImemset:
  342. case Builtin::BI__builtin_memset: {
  343. DiagID = diag::warn_fortify_source_overflow;
  344. SizeIndex = TheCall->getNumArgs() - 1;
  345. ObjectIndex = 0;
  346. break;
  347. }
  348. case Builtin::BIsnprintf:
  349. case Builtin::BI__builtin_snprintf:
  350. case Builtin::BIvsnprintf:
  351. case Builtin::BI__builtin_vsnprintf: {
  352. DiagID = diag::warn_fortify_source_size_mismatch;
  353. SizeIndex = 1;
  354. ObjectIndex = 0;
  355. break;
  356. }
  357. }
  358. llvm::APSInt ObjectSize;
  359. // For __builtin___*_chk, the object size is explicitly provided by the caller
  360. // (usually using __builtin_object_size). Use that value to check this call.
  361. if (IsChkVariant) {
  362. Expr::EvalResult Result;
  363. Expr *SizeArg = TheCall->getArg(ObjectIndex);
  364. if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
  365. return;
  366. ObjectSize = Result.Val.getInt();
  367. // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
  368. } else {
  369. // If the parameter has a pass_object_size attribute, then we should use its
  370. // (potentially) more strict checking mode. Otherwise, conservatively assume
  371. // type 0.
  372. int BOSType = 0;
  373. if (const auto *POS =
  374. FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
  375. BOSType = POS->getType();
  376. Expr *ObjArg = TheCall->getArg(ObjectIndex);
  377. uint64_t Result;
  378. if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
  379. return;
  380. // Get the object size in the target's size_t width.
  381. const TargetInfo &TI = getASTContext().getTargetInfo();
  382. unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
  383. ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
  384. }
  385. // Evaluate the number of bytes of the object that this call will use.
  386. Expr::EvalResult Result;
  387. Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
  388. if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
  389. return;
  390. llvm::APSInt UsedSize = Result.Val.getInt();
  391. if (UsedSize.ule(ObjectSize))
  392. return;
  393. StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
  394. // Skim off the details of whichever builtin was called to produce a better
  395. // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
  396. if (IsChkVariant) {
  397. FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
  398. FunctionName = FunctionName.drop_back(std::strlen("_chk"));
  399. } else if (FunctionName.startswith("__builtin_")) {
  400. FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
  401. }
  402. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  403. PDiag(DiagID)
  404. << FunctionName << ObjectSize.toString(/*Radix=*/10)
  405. << UsedSize.toString(/*Radix=*/10));
  406. }
  407. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  408. Scope::ScopeFlags NeededScopeFlags,
  409. unsigned DiagID) {
  410. // Scopes aren't available during instantiation. Fortunately, builtin
  411. // functions cannot be template args so they cannot be formed through template
  412. // instantiation. Therefore checking once during the parse is sufficient.
  413. if (SemaRef.inTemplateInstantiation())
  414. return false;
  415. Scope *S = SemaRef.getCurScope();
  416. while (S && !S->isSEHExceptScope())
  417. S = S->getParent();
  418. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  419. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  420. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  421. << DRE->getDecl()->getIdentifier();
  422. return true;
  423. }
  424. return false;
  425. }
  426. static inline bool isBlockPointer(Expr *Arg) {
  427. return Arg->getType()->isBlockPointerType();
  428. }
  429. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  430. /// void*, which is a requirement of device side enqueue.
  431. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  432. const BlockPointerType *BPT =
  433. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  434. ArrayRef<QualType> Params =
  435. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  436. unsigned ArgCounter = 0;
  437. bool IllegalParams = false;
  438. // Iterate through the block parameters until either one is found that is not
  439. // a local void*, or the block is valid.
  440. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  441. I != E; ++I, ++ArgCounter) {
  442. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  443. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  444. LangAS::opencl_local) {
  445. // Get the location of the error. If a block literal has been passed
  446. // (BlockExpr) then we can point straight to the offending argument,
  447. // else we just point to the variable reference.
  448. SourceLocation ErrorLoc;
  449. if (isa<BlockExpr>(BlockArg)) {
  450. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  451. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  452. } else if (isa<DeclRefExpr>(BlockArg)) {
  453. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  454. }
  455. S.Diag(ErrorLoc,
  456. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  457. IllegalParams = true;
  458. }
  459. }
  460. return IllegalParams;
  461. }
  462. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  463. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  464. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  465. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  466. return true;
  467. }
  468. return false;
  469. }
  470. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  471. if (checkArgCount(S, TheCall, 2))
  472. return true;
  473. if (checkOpenCLSubgroupExt(S, TheCall))
  474. return true;
  475. // First argument is an ndrange_t type.
  476. Expr *NDRangeArg = TheCall->getArg(0);
  477. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  478. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  479. << TheCall->getDirectCallee() << "'ndrange_t'";
  480. return true;
  481. }
  482. Expr *BlockArg = TheCall->getArg(1);
  483. if (!isBlockPointer(BlockArg)) {
  484. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  485. << TheCall->getDirectCallee() << "block";
  486. return true;
  487. }
  488. return checkOpenCLBlockArgs(S, BlockArg);
  489. }
  490. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  491. /// get_kernel_work_group_size
  492. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  493. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  494. if (checkArgCount(S, TheCall, 1))
  495. return true;
  496. Expr *BlockArg = TheCall->getArg(0);
  497. if (!isBlockPointer(BlockArg)) {
  498. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  499. << TheCall->getDirectCallee() << "block";
  500. return true;
  501. }
  502. return checkOpenCLBlockArgs(S, BlockArg);
  503. }
  504. /// Diagnose integer type and any valid implicit conversion to it.
  505. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  506. const QualType &IntType);
  507. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  508. unsigned Start, unsigned End) {
  509. bool IllegalParams = false;
  510. for (unsigned I = Start; I <= End; ++I)
  511. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  512. S.Context.getSizeType());
  513. return IllegalParams;
  514. }
  515. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  516. /// 'local void*' parameter of passed block.
  517. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  518. Expr *BlockArg,
  519. unsigned NumNonVarArgs) {
  520. const BlockPointerType *BPT =
  521. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  522. unsigned NumBlockParams =
  523. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  524. unsigned TotalNumArgs = TheCall->getNumArgs();
  525. // For each argument passed to the block, a corresponding uint needs to
  526. // be passed to describe the size of the local memory.
  527. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  528. S.Diag(TheCall->getBeginLoc(),
  529. diag::err_opencl_enqueue_kernel_local_size_args);
  530. return true;
  531. }
  532. // Check that the sizes of the local memory are specified by integers.
  533. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  534. TotalNumArgs - 1);
  535. }
  536. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  537. /// overload formats specified in Table 6.13.17.1.
  538. /// int enqueue_kernel(queue_t queue,
  539. /// kernel_enqueue_flags_t flags,
  540. /// const ndrange_t ndrange,
  541. /// void (^block)(void))
  542. /// int enqueue_kernel(queue_t queue,
  543. /// kernel_enqueue_flags_t flags,
  544. /// const ndrange_t ndrange,
  545. /// uint num_events_in_wait_list,
  546. /// clk_event_t *event_wait_list,
  547. /// clk_event_t *event_ret,
  548. /// void (^block)(void))
  549. /// int enqueue_kernel(queue_t queue,
  550. /// kernel_enqueue_flags_t flags,
  551. /// const ndrange_t ndrange,
  552. /// void (^block)(local void*, ...),
  553. /// uint size0, ...)
  554. /// int enqueue_kernel(queue_t queue,
  555. /// kernel_enqueue_flags_t flags,
  556. /// const ndrange_t ndrange,
  557. /// uint num_events_in_wait_list,
  558. /// clk_event_t *event_wait_list,
  559. /// clk_event_t *event_ret,
  560. /// void (^block)(local void*, ...),
  561. /// uint size0, ...)
  562. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  563. unsigned NumArgs = TheCall->getNumArgs();
  564. if (NumArgs < 4) {
  565. S.Diag(TheCall->getBeginLoc(),
  566. diag::err_typecheck_call_too_few_args_at_least)
  567. << 0 << 4 << NumArgs;
  568. return true;
  569. }
  570. Expr *Arg0 = TheCall->getArg(0);
  571. Expr *Arg1 = TheCall->getArg(1);
  572. Expr *Arg2 = TheCall->getArg(2);
  573. Expr *Arg3 = TheCall->getArg(3);
  574. // First argument always needs to be a queue_t type.
  575. if (!Arg0->getType()->isQueueT()) {
  576. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  577. diag::err_opencl_builtin_expected_type)
  578. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  579. return true;
  580. }
  581. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  582. if (!Arg1->getType()->isIntegerType()) {
  583. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  584. diag::err_opencl_builtin_expected_type)
  585. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  586. return true;
  587. }
  588. // Third argument is always an ndrange_t type.
  589. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  590. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  591. diag::err_opencl_builtin_expected_type)
  592. << TheCall->getDirectCallee() << "'ndrange_t'";
  593. return true;
  594. }
  595. // With four arguments, there is only one form that the function could be
  596. // called in: no events and no variable arguments.
  597. if (NumArgs == 4) {
  598. // check that the last argument is the right block type.
  599. if (!isBlockPointer(Arg3)) {
  600. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  601. << TheCall->getDirectCallee() << "block";
  602. return true;
  603. }
  604. // we have a block type, check the prototype
  605. const BlockPointerType *BPT =
  606. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  607. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  608. S.Diag(Arg3->getBeginLoc(),
  609. diag::err_opencl_enqueue_kernel_blocks_no_args);
  610. return true;
  611. }
  612. return false;
  613. }
  614. // we can have block + varargs.
  615. if (isBlockPointer(Arg3))
  616. return (checkOpenCLBlockArgs(S, Arg3) ||
  617. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  618. // last two cases with either exactly 7 args or 7 args and varargs.
  619. if (NumArgs >= 7) {
  620. // check common block argument.
  621. Expr *Arg6 = TheCall->getArg(6);
  622. if (!isBlockPointer(Arg6)) {
  623. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  624. << TheCall->getDirectCallee() << "block";
  625. return true;
  626. }
  627. if (checkOpenCLBlockArgs(S, Arg6))
  628. return true;
  629. // Forth argument has to be any integer type.
  630. if (!Arg3->getType()->isIntegerType()) {
  631. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  632. diag::err_opencl_builtin_expected_type)
  633. << TheCall->getDirectCallee() << "integer";
  634. return true;
  635. }
  636. // check remaining common arguments.
  637. Expr *Arg4 = TheCall->getArg(4);
  638. Expr *Arg5 = TheCall->getArg(5);
  639. // Fifth argument is always passed as a pointer to clk_event_t.
  640. if (!Arg4->isNullPointerConstant(S.Context,
  641. Expr::NPC_ValueDependentIsNotNull) &&
  642. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  643. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  644. diag::err_opencl_builtin_expected_type)
  645. << TheCall->getDirectCallee()
  646. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  647. return true;
  648. }
  649. // Sixth argument is always passed as a pointer to clk_event_t.
  650. if (!Arg5->isNullPointerConstant(S.Context,
  651. Expr::NPC_ValueDependentIsNotNull) &&
  652. !(Arg5->getType()->isPointerType() &&
  653. Arg5->getType()->getPointeeType()->isClkEventT())) {
  654. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  655. diag::err_opencl_builtin_expected_type)
  656. << TheCall->getDirectCallee()
  657. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  658. return true;
  659. }
  660. if (NumArgs == 7)
  661. return false;
  662. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  663. }
  664. // None of the specific case has been detected, give generic error
  665. S.Diag(TheCall->getBeginLoc(),
  666. diag::err_opencl_enqueue_kernel_incorrect_args);
  667. return true;
  668. }
  669. /// Returns OpenCL access qual.
  670. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  671. return D->getAttr<OpenCLAccessAttr>();
  672. }
  673. /// Returns true if pipe element type is different from the pointer.
  674. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  675. const Expr *Arg0 = Call->getArg(0);
  676. // First argument type should always be pipe.
  677. if (!Arg0->getType()->isPipeType()) {
  678. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  679. << Call->getDirectCallee() << Arg0->getSourceRange();
  680. return true;
  681. }
  682. OpenCLAccessAttr *AccessQual =
  683. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  684. // Validates the access qualifier is compatible with the call.
  685. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  686. // read_only and write_only, and assumed to be read_only if no qualifier is
  687. // specified.
  688. switch (Call->getDirectCallee()->getBuiltinID()) {
  689. case Builtin::BIread_pipe:
  690. case Builtin::BIreserve_read_pipe:
  691. case Builtin::BIcommit_read_pipe:
  692. case Builtin::BIwork_group_reserve_read_pipe:
  693. case Builtin::BIsub_group_reserve_read_pipe:
  694. case Builtin::BIwork_group_commit_read_pipe:
  695. case Builtin::BIsub_group_commit_read_pipe:
  696. if (!(!AccessQual || AccessQual->isReadOnly())) {
  697. S.Diag(Arg0->getBeginLoc(),
  698. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  699. << "read_only" << Arg0->getSourceRange();
  700. return true;
  701. }
  702. break;
  703. case Builtin::BIwrite_pipe:
  704. case Builtin::BIreserve_write_pipe:
  705. case Builtin::BIcommit_write_pipe:
  706. case Builtin::BIwork_group_reserve_write_pipe:
  707. case Builtin::BIsub_group_reserve_write_pipe:
  708. case Builtin::BIwork_group_commit_write_pipe:
  709. case Builtin::BIsub_group_commit_write_pipe:
  710. if (!(AccessQual && AccessQual->isWriteOnly())) {
  711. S.Diag(Arg0->getBeginLoc(),
  712. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  713. << "write_only" << Arg0->getSourceRange();
  714. return true;
  715. }
  716. break;
  717. default:
  718. break;
  719. }
  720. return false;
  721. }
  722. /// Returns true if pipe element type is different from the pointer.
  723. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  724. const Expr *Arg0 = Call->getArg(0);
  725. const Expr *ArgIdx = Call->getArg(Idx);
  726. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  727. const QualType EltTy = PipeTy->getElementType();
  728. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  729. // The Idx argument should be a pointer and the type of the pointer and
  730. // the type of pipe element should also be the same.
  731. if (!ArgTy ||
  732. !S.Context.hasSameType(
  733. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  734. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  735. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  736. << ArgIdx->getType() << ArgIdx->getSourceRange();
  737. return true;
  738. }
  739. return false;
  740. }
  741. // Performs semantic analysis for the read/write_pipe call.
  742. // \param S Reference to the semantic analyzer.
  743. // \param Call A pointer to the builtin call.
  744. // \return True if a semantic error has been found, false otherwise.
  745. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  746. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  747. // functions have two forms.
  748. switch (Call->getNumArgs()) {
  749. case 2:
  750. if (checkOpenCLPipeArg(S, Call))
  751. return true;
  752. // The call with 2 arguments should be
  753. // read/write_pipe(pipe T, T*).
  754. // Check packet type T.
  755. if (checkOpenCLPipePacketType(S, Call, 1))
  756. return true;
  757. break;
  758. case 4: {
  759. if (checkOpenCLPipeArg(S, Call))
  760. return true;
  761. // The call with 4 arguments should be
  762. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  763. // Check reserve_id_t.
  764. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  765. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  766. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  767. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  768. return true;
  769. }
  770. // Check the index.
  771. const Expr *Arg2 = Call->getArg(2);
  772. if (!Arg2->getType()->isIntegerType() &&
  773. !Arg2->getType()->isUnsignedIntegerType()) {
  774. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  775. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  776. << Arg2->getType() << Arg2->getSourceRange();
  777. return true;
  778. }
  779. // Check packet type T.
  780. if (checkOpenCLPipePacketType(S, Call, 3))
  781. return true;
  782. } break;
  783. default:
  784. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  785. << Call->getDirectCallee() << Call->getSourceRange();
  786. return true;
  787. }
  788. return false;
  789. }
  790. // Performs a semantic analysis on the {work_group_/sub_group_
  791. // /_}reserve_{read/write}_pipe
  792. // \param S Reference to the semantic analyzer.
  793. // \param Call The call to the builtin function to be analyzed.
  794. // \return True if a semantic error was found, false otherwise.
  795. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  796. if (checkArgCount(S, Call, 2))
  797. return true;
  798. if (checkOpenCLPipeArg(S, Call))
  799. return true;
  800. // Check the reserve size.
  801. if (!Call->getArg(1)->getType()->isIntegerType() &&
  802. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  803. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  804. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  805. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  806. return true;
  807. }
  808. // Since return type of reserve_read/write_pipe built-in function is
  809. // reserve_id_t, which is not defined in the builtin def file , we used int
  810. // as return type and need to override the return type of these functions.
  811. Call->setType(S.Context.OCLReserveIDTy);
  812. return false;
  813. }
  814. // Performs a semantic analysis on {work_group_/sub_group_
  815. // /_}commit_{read/write}_pipe
  816. // \param S Reference to the semantic analyzer.
  817. // \param Call The call to the builtin function to be analyzed.
  818. // \return True if a semantic error was found, false otherwise.
  819. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  820. if (checkArgCount(S, Call, 2))
  821. return true;
  822. if (checkOpenCLPipeArg(S, Call))
  823. return true;
  824. // Check reserve_id_t.
  825. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  826. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  827. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  828. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  829. return true;
  830. }
  831. return false;
  832. }
  833. // Performs a semantic analysis on the call to built-in Pipe
  834. // Query Functions.
  835. // \param S Reference to the semantic analyzer.
  836. // \param Call The call to the builtin function to be analyzed.
  837. // \return True if a semantic error was found, false otherwise.
  838. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  839. if (checkArgCount(S, Call, 1))
  840. return true;
  841. if (!Call->getArg(0)->getType()->isPipeType()) {
  842. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  843. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  844. return true;
  845. }
  846. return false;
  847. }
  848. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  849. // Performs semantic analysis for the to_global/local/private call.
  850. // \param S Reference to the semantic analyzer.
  851. // \param BuiltinID ID of the builtin function.
  852. // \param Call A pointer to the builtin call.
  853. // \return True if a semantic error has been found, false otherwise.
  854. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  855. CallExpr *Call) {
  856. if (Call->getNumArgs() != 1) {
  857. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
  858. << Call->getDirectCallee() << Call->getSourceRange();
  859. return true;
  860. }
  861. auto RT = Call->getArg(0)->getType();
  862. if (!RT->isPointerType() || RT->getPointeeType()
  863. .getAddressSpace() == LangAS::opencl_constant) {
  864. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  865. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  866. return true;
  867. }
  868. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  869. S.Diag(Call->getArg(0)->getBeginLoc(),
  870. diag::warn_opencl_generic_address_space_arg)
  871. << Call->getDirectCallee()->getNameInfo().getAsString()
  872. << Call->getArg(0)->getSourceRange();
  873. }
  874. RT = RT->getPointeeType();
  875. auto Qual = RT.getQualifiers();
  876. switch (BuiltinID) {
  877. case Builtin::BIto_global:
  878. Qual.setAddressSpace(LangAS::opencl_global);
  879. break;
  880. case Builtin::BIto_local:
  881. Qual.setAddressSpace(LangAS::opencl_local);
  882. break;
  883. case Builtin::BIto_private:
  884. Qual.setAddressSpace(LangAS::opencl_private);
  885. break;
  886. default:
  887. llvm_unreachable("Invalid builtin function");
  888. }
  889. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  890. RT.getUnqualifiedType(), Qual)));
  891. return false;
  892. }
  893. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  894. if (checkArgCount(S, TheCall, 1))
  895. return ExprError();
  896. // Compute __builtin_launder's parameter type from the argument.
  897. // The parameter type is:
  898. // * The type of the argument if it's not an array or function type,
  899. // Otherwise,
  900. // * The decayed argument type.
  901. QualType ParamTy = [&]() {
  902. QualType ArgTy = TheCall->getArg(0)->getType();
  903. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  904. return S.Context.getPointerType(Ty->getElementType());
  905. if (ArgTy->isFunctionType()) {
  906. return S.Context.getPointerType(ArgTy);
  907. }
  908. return ArgTy;
  909. }();
  910. TheCall->setType(ParamTy);
  911. auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
  912. if (!ParamTy->isPointerType())
  913. return 0;
  914. if (ParamTy->isFunctionPointerType())
  915. return 1;
  916. if (ParamTy->isVoidPointerType())
  917. return 2;
  918. return llvm::Optional<unsigned>{};
  919. }();
  920. if (DiagSelect.hasValue()) {
  921. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  922. << DiagSelect.getValue() << TheCall->getSourceRange();
  923. return ExprError();
  924. }
  925. // We either have an incomplete class type, or we have a class template
  926. // whose instantiation has not been forced. Example:
  927. //
  928. // template <class T> struct Foo { T value; };
  929. // Foo<int> *p = nullptr;
  930. // auto *d = __builtin_launder(p);
  931. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  932. diag::err_incomplete_type))
  933. return ExprError();
  934. assert(ParamTy->getPointeeType()->isObjectType() &&
  935. "Unhandled non-object pointer case");
  936. InitializedEntity Entity =
  937. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  938. ExprResult Arg =
  939. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  940. if (Arg.isInvalid())
  941. return ExprError();
  942. TheCall->setArg(0, Arg.get());
  943. return TheCall;
  944. }
  945. // Emit an error and return true if the current architecture is not in the list
  946. // of supported architectures.
  947. static bool
  948. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  949. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  950. llvm::Triple::ArchType CurArch =
  951. S.getASTContext().getTargetInfo().getTriple().getArch();
  952. if (llvm::is_contained(SupportedArchs, CurArch))
  953. return false;
  954. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  955. << TheCall->getSourceRange();
  956. return true;
  957. }
  958. ExprResult
  959. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  960. CallExpr *TheCall) {
  961. ExprResult TheCallResult(TheCall);
  962. // Find out if any arguments are required to be integer constant expressions.
  963. unsigned ICEArguments = 0;
  964. ASTContext::GetBuiltinTypeError Error;
  965. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  966. if (Error != ASTContext::GE_None)
  967. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  968. // If any arguments are required to be ICE's, check and diagnose.
  969. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  970. // Skip arguments not required to be ICE's.
  971. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  972. llvm::APSInt Result;
  973. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  974. return true;
  975. ICEArguments &= ~(1 << ArgNo);
  976. }
  977. switch (BuiltinID) {
  978. case Builtin::BI__builtin___CFStringMakeConstantString:
  979. assert(TheCall->getNumArgs() == 1 &&
  980. "Wrong # arguments to builtin CFStringMakeConstantString");
  981. if (CheckObjCString(TheCall->getArg(0)))
  982. return ExprError();
  983. break;
  984. case Builtin::BI__builtin_ms_va_start:
  985. case Builtin::BI__builtin_stdarg_start:
  986. case Builtin::BI__builtin_va_start:
  987. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  988. return ExprError();
  989. break;
  990. case Builtin::BI__va_start: {
  991. switch (Context.getTargetInfo().getTriple().getArch()) {
  992. case llvm::Triple::aarch64:
  993. case llvm::Triple::arm:
  994. case llvm::Triple::thumb:
  995. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  996. return ExprError();
  997. break;
  998. default:
  999. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  1000. return ExprError();
  1001. break;
  1002. }
  1003. break;
  1004. }
  1005. // The acquire, release, and no fence variants are ARM and AArch64 only.
  1006. case Builtin::BI_interlockedbittestandset_acq:
  1007. case Builtin::BI_interlockedbittestandset_rel:
  1008. case Builtin::BI_interlockedbittestandset_nf:
  1009. case Builtin::BI_interlockedbittestandreset_acq:
  1010. case Builtin::BI_interlockedbittestandreset_rel:
  1011. case Builtin::BI_interlockedbittestandreset_nf:
  1012. if (CheckBuiltinTargetSupport(
  1013. *this, BuiltinID, TheCall,
  1014. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  1015. return ExprError();
  1016. break;
  1017. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  1018. case Builtin::BI_bittest64:
  1019. case Builtin::BI_bittestandcomplement64:
  1020. case Builtin::BI_bittestandreset64:
  1021. case Builtin::BI_bittestandset64:
  1022. case Builtin::BI_interlockedbittestandreset64:
  1023. case Builtin::BI_interlockedbittestandset64:
  1024. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  1025. {llvm::Triple::x86_64, llvm::Triple::arm,
  1026. llvm::Triple::thumb, llvm::Triple::aarch64}))
  1027. return ExprError();
  1028. break;
  1029. case Builtin::BI__builtin_isgreater:
  1030. case Builtin::BI__builtin_isgreaterequal:
  1031. case Builtin::BI__builtin_isless:
  1032. case Builtin::BI__builtin_islessequal:
  1033. case Builtin::BI__builtin_islessgreater:
  1034. case Builtin::BI__builtin_isunordered:
  1035. if (SemaBuiltinUnorderedCompare(TheCall))
  1036. return ExprError();
  1037. break;
  1038. case Builtin::BI__builtin_fpclassify:
  1039. if (SemaBuiltinFPClassification(TheCall, 6))
  1040. return ExprError();
  1041. break;
  1042. case Builtin::BI__builtin_isfinite:
  1043. case Builtin::BI__builtin_isinf:
  1044. case Builtin::BI__builtin_isinf_sign:
  1045. case Builtin::BI__builtin_isnan:
  1046. case Builtin::BI__builtin_isnormal:
  1047. case Builtin::BI__builtin_signbit:
  1048. case Builtin::BI__builtin_signbitf:
  1049. case Builtin::BI__builtin_signbitl:
  1050. if (SemaBuiltinFPClassification(TheCall, 1))
  1051. return ExprError();
  1052. break;
  1053. case Builtin::BI__builtin_shufflevector:
  1054. return SemaBuiltinShuffleVector(TheCall);
  1055. // TheCall will be freed by the smart pointer here, but that's fine, since
  1056. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  1057. case Builtin::BI__builtin_prefetch:
  1058. if (SemaBuiltinPrefetch(TheCall))
  1059. return ExprError();
  1060. break;
  1061. case Builtin::BI__builtin_alloca_with_align:
  1062. if (SemaBuiltinAllocaWithAlign(TheCall))
  1063. return ExprError();
  1064. LLVM_FALLTHROUGH;
  1065. case Builtin::BI__builtin_alloca:
  1066. Diag(TheCall->getBeginLoc(), diag::warn_alloca)
  1067. << TheCall->getDirectCallee();
  1068. break;
  1069. case Builtin::BI__assume:
  1070. case Builtin::BI__builtin_assume:
  1071. if (SemaBuiltinAssume(TheCall))
  1072. return ExprError();
  1073. break;
  1074. case Builtin::BI__builtin_assume_aligned:
  1075. if (SemaBuiltinAssumeAligned(TheCall))
  1076. return ExprError();
  1077. break;
  1078. case Builtin::BI__builtin_dynamic_object_size:
  1079. case Builtin::BI__builtin_object_size:
  1080. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  1081. return ExprError();
  1082. break;
  1083. case Builtin::BI__builtin_longjmp:
  1084. if (SemaBuiltinLongjmp(TheCall))
  1085. return ExprError();
  1086. break;
  1087. case Builtin::BI__builtin_setjmp:
  1088. if (SemaBuiltinSetjmp(TheCall))
  1089. return ExprError();
  1090. break;
  1091. case Builtin::BI_setjmp:
  1092. case Builtin::BI_setjmpex:
  1093. if (checkArgCount(*this, TheCall, 1))
  1094. return true;
  1095. break;
  1096. case Builtin::BI__builtin_classify_type:
  1097. if (checkArgCount(*this, TheCall, 1)) return true;
  1098. TheCall->setType(Context.IntTy);
  1099. break;
  1100. case Builtin::BI__builtin_constant_p: {
  1101. if (checkArgCount(*this, TheCall, 1)) return true;
  1102. ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  1103. if (Arg.isInvalid()) return true;
  1104. TheCall->setArg(0, Arg.get());
  1105. TheCall->setType(Context.IntTy);
  1106. break;
  1107. }
  1108. case Builtin::BI__builtin_launder:
  1109. return SemaBuiltinLaunder(*this, TheCall);
  1110. case Builtin::BI__sync_fetch_and_add:
  1111. case Builtin::BI__sync_fetch_and_add_1:
  1112. case Builtin::BI__sync_fetch_and_add_2:
  1113. case Builtin::BI__sync_fetch_and_add_4:
  1114. case Builtin::BI__sync_fetch_and_add_8:
  1115. case Builtin::BI__sync_fetch_and_add_16:
  1116. case Builtin::BI__sync_fetch_and_sub:
  1117. case Builtin::BI__sync_fetch_and_sub_1:
  1118. case Builtin::BI__sync_fetch_and_sub_2:
  1119. case Builtin::BI__sync_fetch_and_sub_4:
  1120. case Builtin::BI__sync_fetch_and_sub_8:
  1121. case Builtin::BI__sync_fetch_and_sub_16:
  1122. case Builtin::BI__sync_fetch_and_or:
  1123. case Builtin::BI__sync_fetch_and_or_1:
  1124. case Builtin::BI__sync_fetch_and_or_2:
  1125. case Builtin::BI__sync_fetch_and_or_4:
  1126. case Builtin::BI__sync_fetch_and_or_8:
  1127. case Builtin::BI__sync_fetch_and_or_16:
  1128. case Builtin::BI__sync_fetch_and_and:
  1129. case Builtin::BI__sync_fetch_and_and_1:
  1130. case Builtin::BI__sync_fetch_and_and_2:
  1131. case Builtin::BI__sync_fetch_and_and_4:
  1132. case Builtin::BI__sync_fetch_and_and_8:
  1133. case Builtin::BI__sync_fetch_and_and_16:
  1134. case Builtin::BI__sync_fetch_and_xor:
  1135. case Builtin::BI__sync_fetch_and_xor_1:
  1136. case Builtin::BI__sync_fetch_and_xor_2:
  1137. case Builtin::BI__sync_fetch_and_xor_4:
  1138. case Builtin::BI__sync_fetch_and_xor_8:
  1139. case Builtin::BI__sync_fetch_and_xor_16:
  1140. case Builtin::BI__sync_fetch_and_nand:
  1141. case Builtin::BI__sync_fetch_and_nand_1:
  1142. case Builtin::BI__sync_fetch_and_nand_2:
  1143. case Builtin::BI__sync_fetch_and_nand_4:
  1144. case Builtin::BI__sync_fetch_and_nand_8:
  1145. case Builtin::BI__sync_fetch_and_nand_16:
  1146. case Builtin::BI__sync_add_and_fetch:
  1147. case Builtin::BI__sync_add_and_fetch_1:
  1148. case Builtin::BI__sync_add_and_fetch_2:
  1149. case Builtin::BI__sync_add_and_fetch_4:
  1150. case Builtin::BI__sync_add_and_fetch_8:
  1151. case Builtin::BI__sync_add_and_fetch_16:
  1152. case Builtin::BI__sync_sub_and_fetch:
  1153. case Builtin::BI__sync_sub_and_fetch_1:
  1154. case Builtin::BI__sync_sub_and_fetch_2:
  1155. case Builtin::BI__sync_sub_and_fetch_4:
  1156. case Builtin::BI__sync_sub_and_fetch_8:
  1157. case Builtin::BI__sync_sub_and_fetch_16:
  1158. case Builtin::BI__sync_and_and_fetch:
  1159. case Builtin::BI__sync_and_and_fetch_1:
  1160. case Builtin::BI__sync_and_and_fetch_2:
  1161. case Builtin::BI__sync_and_and_fetch_4:
  1162. case Builtin::BI__sync_and_and_fetch_8:
  1163. case Builtin::BI__sync_and_and_fetch_16:
  1164. case Builtin::BI__sync_or_and_fetch:
  1165. case Builtin::BI__sync_or_and_fetch_1:
  1166. case Builtin::BI__sync_or_and_fetch_2:
  1167. case Builtin::BI__sync_or_and_fetch_4:
  1168. case Builtin::BI__sync_or_and_fetch_8:
  1169. case Builtin::BI__sync_or_and_fetch_16:
  1170. case Builtin::BI__sync_xor_and_fetch:
  1171. case Builtin::BI__sync_xor_and_fetch_1:
  1172. case Builtin::BI__sync_xor_and_fetch_2:
  1173. case Builtin::BI__sync_xor_and_fetch_4:
  1174. case Builtin::BI__sync_xor_and_fetch_8:
  1175. case Builtin::BI__sync_xor_and_fetch_16:
  1176. case Builtin::BI__sync_nand_and_fetch:
  1177. case Builtin::BI__sync_nand_and_fetch_1:
  1178. case Builtin::BI__sync_nand_and_fetch_2:
  1179. case Builtin::BI__sync_nand_and_fetch_4:
  1180. case Builtin::BI__sync_nand_and_fetch_8:
  1181. case Builtin::BI__sync_nand_and_fetch_16:
  1182. case Builtin::BI__sync_val_compare_and_swap:
  1183. case Builtin::BI__sync_val_compare_and_swap_1:
  1184. case Builtin::BI__sync_val_compare_and_swap_2:
  1185. case Builtin::BI__sync_val_compare_and_swap_4:
  1186. case Builtin::BI__sync_val_compare_and_swap_8:
  1187. case Builtin::BI__sync_val_compare_and_swap_16:
  1188. case Builtin::BI__sync_bool_compare_and_swap:
  1189. case Builtin::BI__sync_bool_compare_and_swap_1:
  1190. case Builtin::BI__sync_bool_compare_and_swap_2:
  1191. case Builtin::BI__sync_bool_compare_and_swap_4:
  1192. case Builtin::BI__sync_bool_compare_and_swap_8:
  1193. case Builtin::BI__sync_bool_compare_and_swap_16:
  1194. case Builtin::BI__sync_lock_test_and_set:
  1195. case Builtin::BI__sync_lock_test_and_set_1:
  1196. case Builtin::BI__sync_lock_test_and_set_2:
  1197. case Builtin::BI__sync_lock_test_and_set_4:
  1198. case Builtin::BI__sync_lock_test_and_set_8:
  1199. case Builtin::BI__sync_lock_test_and_set_16:
  1200. case Builtin::BI__sync_lock_release:
  1201. case Builtin::BI__sync_lock_release_1:
  1202. case Builtin::BI__sync_lock_release_2:
  1203. case Builtin::BI__sync_lock_release_4:
  1204. case Builtin::BI__sync_lock_release_8:
  1205. case Builtin::BI__sync_lock_release_16:
  1206. case Builtin::BI__sync_swap:
  1207. case Builtin::BI__sync_swap_1:
  1208. case Builtin::BI__sync_swap_2:
  1209. case Builtin::BI__sync_swap_4:
  1210. case Builtin::BI__sync_swap_8:
  1211. case Builtin::BI__sync_swap_16:
  1212. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1213. case Builtin::BI__sync_synchronize:
  1214. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1215. << TheCall->getCallee()->getSourceRange();
  1216. break;
  1217. case Builtin::BI__builtin_nontemporal_load:
  1218. case Builtin::BI__builtin_nontemporal_store:
  1219. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1220. #define BUILTIN(ID, TYPE, ATTRS)
  1221. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1222. case Builtin::BI##ID: \
  1223. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1224. #include "clang/Basic/Builtins.def"
  1225. case Builtin::BI__annotation:
  1226. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1227. return ExprError();
  1228. break;
  1229. case Builtin::BI__builtin_annotation:
  1230. if (SemaBuiltinAnnotation(*this, TheCall))
  1231. return ExprError();
  1232. break;
  1233. case Builtin::BI__builtin_addressof:
  1234. if (SemaBuiltinAddressof(*this, TheCall))
  1235. return ExprError();
  1236. break;
  1237. case Builtin::BI__builtin_add_overflow:
  1238. case Builtin::BI__builtin_sub_overflow:
  1239. case Builtin::BI__builtin_mul_overflow:
  1240. if (SemaBuiltinOverflow(*this, TheCall))
  1241. return ExprError();
  1242. break;
  1243. case Builtin::BI__builtin_operator_new:
  1244. case Builtin::BI__builtin_operator_delete: {
  1245. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1246. ExprResult Res =
  1247. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1248. if (Res.isInvalid())
  1249. CorrectDelayedTyposInExpr(TheCallResult.get());
  1250. return Res;
  1251. }
  1252. case Builtin::BI__builtin_dump_struct: {
  1253. // We first want to ensure we are called with 2 arguments
  1254. if (checkArgCount(*this, TheCall, 2))
  1255. return ExprError();
  1256. // Ensure that the first argument is of type 'struct XX *'
  1257. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1258. const QualType PtrArgType = PtrArg->getType();
  1259. if (!PtrArgType->isPointerType() ||
  1260. !PtrArgType->getPointeeType()->isRecordType()) {
  1261. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1262. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1263. << "structure pointer";
  1264. return ExprError();
  1265. }
  1266. // Ensure that the second argument is of type 'FunctionType'
  1267. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1268. const QualType FnPtrArgType = FnPtrArg->getType();
  1269. if (!FnPtrArgType->isPointerType()) {
  1270. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1271. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1272. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1273. return ExprError();
  1274. }
  1275. const auto *FuncType =
  1276. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1277. if (!FuncType) {
  1278. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1279. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1280. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1281. return ExprError();
  1282. }
  1283. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1284. if (!FT->getNumParams()) {
  1285. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1286. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1287. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1288. return ExprError();
  1289. }
  1290. QualType PT = FT->getParamType(0);
  1291. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1292. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1293. !PT->getPointeeType().isConstQualified()) {
  1294. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1295. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1296. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1297. return ExprError();
  1298. }
  1299. }
  1300. TheCall->setType(Context.IntTy);
  1301. break;
  1302. }
  1303. case Builtin::BI__builtin_preserve_access_index:
  1304. if (SemaBuiltinPreserveAI(*this, TheCall))
  1305. return ExprError();
  1306. break;
  1307. case Builtin::BI__builtin_call_with_static_chain:
  1308. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1309. return ExprError();
  1310. break;
  1311. case Builtin::BI__exception_code:
  1312. case Builtin::BI_exception_code:
  1313. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1314. diag::err_seh___except_block))
  1315. return ExprError();
  1316. break;
  1317. case Builtin::BI__exception_info:
  1318. case Builtin::BI_exception_info:
  1319. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1320. diag::err_seh___except_filter))
  1321. return ExprError();
  1322. break;
  1323. case Builtin::BI__GetExceptionInfo:
  1324. if (checkArgCount(*this, TheCall, 1))
  1325. return ExprError();
  1326. if (CheckCXXThrowOperand(
  1327. TheCall->getBeginLoc(),
  1328. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1329. TheCall))
  1330. return ExprError();
  1331. TheCall->setType(Context.VoidPtrTy);
  1332. break;
  1333. // OpenCL v2.0, s6.13.16 - Pipe functions
  1334. case Builtin::BIread_pipe:
  1335. case Builtin::BIwrite_pipe:
  1336. // Since those two functions are declared with var args, we need a semantic
  1337. // check for the argument.
  1338. if (SemaBuiltinRWPipe(*this, TheCall))
  1339. return ExprError();
  1340. break;
  1341. case Builtin::BIreserve_read_pipe:
  1342. case Builtin::BIreserve_write_pipe:
  1343. case Builtin::BIwork_group_reserve_read_pipe:
  1344. case Builtin::BIwork_group_reserve_write_pipe:
  1345. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1346. return ExprError();
  1347. break;
  1348. case Builtin::BIsub_group_reserve_read_pipe:
  1349. case Builtin::BIsub_group_reserve_write_pipe:
  1350. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1351. SemaBuiltinReserveRWPipe(*this, TheCall))
  1352. return ExprError();
  1353. break;
  1354. case Builtin::BIcommit_read_pipe:
  1355. case Builtin::BIcommit_write_pipe:
  1356. case Builtin::BIwork_group_commit_read_pipe:
  1357. case Builtin::BIwork_group_commit_write_pipe:
  1358. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1359. return ExprError();
  1360. break;
  1361. case Builtin::BIsub_group_commit_read_pipe:
  1362. case Builtin::BIsub_group_commit_write_pipe:
  1363. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1364. SemaBuiltinCommitRWPipe(*this, TheCall))
  1365. return ExprError();
  1366. break;
  1367. case Builtin::BIget_pipe_num_packets:
  1368. case Builtin::BIget_pipe_max_packets:
  1369. if (SemaBuiltinPipePackets(*this, TheCall))
  1370. return ExprError();
  1371. break;
  1372. case Builtin::BIto_global:
  1373. case Builtin::BIto_local:
  1374. case Builtin::BIto_private:
  1375. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1376. return ExprError();
  1377. break;
  1378. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1379. case Builtin::BIenqueue_kernel:
  1380. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1381. return ExprError();
  1382. break;
  1383. case Builtin::BIget_kernel_work_group_size:
  1384. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1385. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1386. return ExprError();
  1387. break;
  1388. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1389. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1390. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1391. return ExprError();
  1392. break;
  1393. case Builtin::BI__builtin_os_log_format:
  1394. case Builtin::BI__builtin_os_log_format_buffer_size:
  1395. if (SemaBuiltinOSLogFormat(TheCall))
  1396. return ExprError();
  1397. break;
  1398. }
  1399. // Since the target specific builtins for each arch overlap, only check those
  1400. // of the arch we are compiling for.
  1401. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1402. switch (Context.getTargetInfo().getTriple().getArch()) {
  1403. case llvm::Triple::arm:
  1404. case llvm::Triple::armeb:
  1405. case llvm::Triple::thumb:
  1406. case llvm::Triple::thumbeb:
  1407. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1408. return ExprError();
  1409. break;
  1410. case llvm::Triple::aarch64:
  1411. case llvm::Triple::aarch64_be:
  1412. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1413. return ExprError();
  1414. break;
  1415. case llvm::Triple::hexagon:
  1416. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1417. return ExprError();
  1418. break;
  1419. case llvm::Triple::mips:
  1420. case llvm::Triple::mipsel:
  1421. case llvm::Triple::mips64:
  1422. case llvm::Triple::mips64el:
  1423. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1424. return ExprError();
  1425. break;
  1426. case llvm::Triple::systemz:
  1427. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1428. return ExprError();
  1429. break;
  1430. case llvm::Triple::x86:
  1431. case llvm::Triple::x86_64:
  1432. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1433. return ExprError();
  1434. break;
  1435. case llvm::Triple::ppc:
  1436. case llvm::Triple::ppc64:
  1437. case llvm::Triple::ppc64le:
  1438. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1439. return ExprError();
  1440. break;
  1441. default:
  1442. break;
  1443. }
  1444. }
  1445. return TheCallResult;
  1446. }
  1447. // Get the valid immediate range for the specified NEON type code.
  1448. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1449. NeonTypeFlags Type(t);
  1450. int IsQuad = ForceQuad ? true : Type.isQuad();
  1451. switch (Type.getEltType()) {
  1452. case NeonTypeFlags::Int8:
  1453. case NeonTypeFlags::Poly8:
  1454. return shift ? 7 : (8 << IsQuad) - 1;
  1455. case NeonTypeFlags::Int16:
  1456. case NeonTypeFlags::Poly16:
  1457. return shift ? 15 : (4 << IsQuad) - 1;
  1458. case NeonTypeFlags::Int32:
  1459. return shift ? 31 : (2 << IsQuad) - 1;
  1460. case NeonTypeFlags::Int64:
  1461. case NeonTypeFlags::Poly64:
  1462. return shift ? 63 : (1 << IsQuad) - 1;
  1463. case NeonTypeFlags::Poly128:
  1464. return shift ? 127 : (1 << IsQuad) - 1;
  1465. case NeonTypeFlags::Float16:
  1466. assert(!shift && "cannot shift float types!");
  1467. return (4 << IsQuad) - 1;
  1468. case NeonTypeFlags::Float32:
  1469. assert(!shift && "cannot shift float types!");
  1470. return (2 << IsQuad) - 1;
  1471. case NeonTypeFlags::Float64:
  1472. assert(!shift && "cannot shift float types!");
  1473. return (1 << IsQuad) - 1;
  1474. }
  1475. llvm_unreachable("Invalid NeonTypeFlag!");
  1476. }
  1477. /// getNeonEltType - Return the QualType corresponding to the elements of
  1478. /// the vector type specified by the NeonTypeFlags. This is used to check
  1479. /// the pointer arguments for Neon load/store intrinsics.
  1480. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1481. bool IsPolyUnsigned, bool IsInt64Long) {
  1482. switch (Flags.getEltType()) {
  1483. case NeonTypeFlags::Int8:
  1484. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1485. case NeonTypeFlags::Int16:
  1486. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1487. case NeonTypeFlags::Int32:
  1488. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1489. case NeonTypeFlags::Int64:
  1490. if (IsInt64Long)
  1491. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1492. else
  1493. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1494. : Context.LongLongTy;
  1495. case NeonTypeFlags::Poly8:
  1496. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1497. case NeonTypeFlags::Poly16:
  1498. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1499. case NeonTypeFlags::Poly64:
  1500. if (IsInt64Long)
  1501. return Context.UnsignedLongTy;
  1502. else
  1503. return Context.UnsignedLongLongTy;
  1504. case NeonTypeFlags::Poly128:
  1505. break;
  1506. case NeonTypeFlags::Float16:
  1507. return Context.HalfTy;
  1508. case NeonTypeFlags::Float32:
  1509. return Context.FloatTy;
  1510. case NeonTypeFlags::Float64:
  1511. return Context.DoubleTy;
  1512. }
  1513. llvm_unreachable("Invalid NeonTypeFlag!");
  1514. }
  1515. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1516. llvm::APSInt Result;
  1517. uint64_t mask = 0;
  1518. unsigned TV = 0;
  1519. int PtrArgNum = -1;
  1520. bool HasConstPtr = false;
  1521. switch (BuiltinID) {
  1522. #define GET_NEON_OVERLOAD_CHECK
  1523. #include "clang/Basic/arm_neon.inc"
  1524. #include "clang/Basic/arm_fp16.inc"
  1525. #undef GET_NEON_OVERLOAD_CHECK
  1526. }
  1527. // For NEON intrinsics which are overloaded on vector element type, validate
  1528. // the immediate which specifies which variant to emit.
  1529. unsigned ImmArg = TheCall->getNumArgs()-1;
  1530. if (mask) {
  1531. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1532. return true;
  1533. TV = Result.getLimitedValue(64);
  1534. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1535. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  1536. << TheCall->getArg(ImmArg)->getSourceRange();
  1537. }
  1538. if (PtrArgNum >= 0) {
  1539. // Check that pointer arguments have the specified type.
  1540. Expr *Arg = TheCall->getArg(PtrArgNum);
  1541. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1542. Arg = ICE->getSubExpr();
  1543. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1544. QualType RHSTy = RHS.get()->getType();
  1545. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1546. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1547. Arch == llvm::Triple::aarch64_be;
  1548. bool IsInt64Long =
  1549. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1550. QualType EltTy =
  1551. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1552. if (HasConstPtr)
  1553. EltTy = EltTy.withConst();
  1554. QualType LHSTy = Context.getPointerType(EltTy);
  1555. AssignConvertType ConvTy;
  1556. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1557. if (RHS.isInvalid())
  1558. return true;
  1559. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  1560. RHS.get(), AA_Assigning))
  1561. return true;
  1562. }
  1563. // For NEON intrinsics which take an immediate value as part of the
  1564. // instruction, range check them here.
  1565. unsigned i = 0, l = 0, u = 0;
  1566. switch (BuiltinID) {
  1567. default:
  1568. return false;
  1569. #define GET_NEON_IMMEDIATE_CHECK
  1570. #include "clang/Basic/arm_neon.inc"
  1571. #include "clang/Basic/arm_fp16.inc"
  1572. #undef GET_NEON_IMMEDIATE_CHECK
  1573. }
  1574. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1575. }
  1576. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1577. unsigned MaxWidth) {
  1578. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1579. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1580. BuiltinID == ARM::BI__builtin_arm_strex ||
  1581. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1582. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1583. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1584. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1585. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1586. "unexpected ARM builtin");
  1587. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1588. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1589. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1590. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1591. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1592. // Ensure that we have the proper number of arguments.
  1593. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1594. return true;
  1595. // Inspect the pointer argument of the atomic builtin. This should always be
  1596. // a pointer type, whose element is an integral scalar or pointer type.
  1597. // Because it is a pointer type, we don't have to worry about any implicit
  1598. // casts here.
  1599. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1600. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1601. if (PointerArgRes.isInvalid())
  1602. return true;
  1603. PointerArg = PointerArgRes.get();
  1604. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1605. if (!pointerType) {
  1606. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  1607. << PointerArg->getType() << PointerArg->getSourceRange();
  1608. return true;
  1609. }
  1610. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1611. // task is to insert the appropriate casts into the AST. First work out just
  1612. // what the appropriate type is.
  1613. QualType ValType = pointerType->getPointeeType();
  1614. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1615. if (IsLdrex)
  1616. AddrType.addConst();
  1617. // Issue a warning if the cast is dodgy.
  1618. CastKind CastNeeded = CK_NoOp;
  1619. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1620. CastNeeded = CK_BitCast;
  1621. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  1622. << PointerArg->getType() << Context.getPointerType(AddrType)
  1623. << AA_Passing << PointerArg->getSourceRange();
  1624. }
  1625. // Finally, do the cast and replace the argument with the corrected version.
  1626. AddrType = Context.getPointerType(AddrType);
  1627. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1628. if (PointerArgRes.isInvalid())
  1629. return true;
  1630. PointerArg = PointerArgRes.get();
  1631. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1632. // In general, we allow ints, floats and pointers to be loaded and stored.
  1633. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1634. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1635. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1636. << PointerArg->getType() << PointerArg->getSourceRange();
  1637. return true;
  1638. }
  1639. // But ARM doesn't have instructions to deal with 128-bit versions.
  1640. if (Context.getTypeSize(ValType) > MaxWidth) {
  1641. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1642. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  1643. << PointerArg->getType() << PointerArg->getSourceRange();
  1644. return true;
  1645. }
  1646. switch (ValType.getObjCLifetime()) {
  1647. case Qualifiers::OCL_None:
  1648. case Qualifiers::OCL_ExplicitNone:
  1649. // okay
  1650. break;
  1651. case Qualifiers::OCL_Weak:
  1652. case Qualifiers::OCL_Strong:
  1653. case Qualifiers::OCL_Autoreleasing:
  1654. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  1655. << ValType << PointerArg->getSourceRange();
  1656. return true;
  1657. }
  1658. if (IsLdrex) {
  1659. TheCall->setType(ValType);
  1660. return false;
  1661. }
  1662. // Initialize the argument to be stored.
  1663. ExprResult ValArg = TheCall->getArg(0);
  1664. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1665. Context, ValType, /*consume*/ false);
  1666. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1667. if (ValArg.isInvalid())
  1668. return true;
  1669. TheCall->setArg(0, ValArg.get());
  1670. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1671. // but the custom checker bypasses all default analysis.
  1672. TheCall->setType(Context.IntTy);
  1673. return false;
  1674. }
  1675. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1676. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1677. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1678. BuiltinID == ARM::BI__builtin_arm_strex ||
  1679. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1680. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1681. }
  1682. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1683. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1684. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1685. }
  1686. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1687. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1688. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1689. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1690. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1691. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1692. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1693. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1694. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1695. return true;
  1696. // For intrinsics which take an immediate value as part of the instruction,
  1697. // range check them here.
  1698. // FIXME: VFP Intrinsics should error if VFP not present.
  1699. switch (BuiltinID) {
  1700. default: return false;
  1701. case ARM::BI__builtin_arm_ssat:
  1702. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1703. case ARM::BI__builtin_arm_usat:
  1704. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1705. case ARM::BI__builtin_arm_ssat16:
  1706. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1707. case ARM::BI__builtin_arm_usat16:
  1708. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1709. case ARM::BI__builtin_arm_vcvtr_f:
  1710. case ARM::BI__builtin_arm_vcvtr_d:
  1711. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1712. case ARM::BI__builtin_arm_dmb:
  1713. case ARM::BI__builtin_arm_dsb:
  1714. case ARM::BI__builtin_arm_isb:
  1715. case ARM::BI__builtin_arm_dbg:
  1716. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1717. }
  1718. }
  1719. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1720. CallExpr *TheCall) {
  1721. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1722. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1723. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1724. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1725. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1726. }
  1727. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1728. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1729. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1730. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1731. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1732. }
  1733. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1734. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1735. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1736. // Memory Tagging Extensions (MTE) Intrinsics
  1737. if (BuiltinID == AArch64::BI__builtin_arm_irg ||
  1738. BuiltinID == AArch64::BI__builtin_arm_addg ||
  1739. BuiltinID == AArch64::BI__builtin_arm_gmi ||
  1740. BuiltinID == AArch64::BI__builtin_arm_ldg ||
  1741. BuiltinID == AArch64::BI__builtin_arm_stg ||
  1742. BuiltinID == AArch64::BI__builtin_arm_subp) {
  1743. return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
  1744. }
  1745. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1746. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1747. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1748. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1749. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1750. // Only check the valid encoding range. Any constant in this range would be
  1751. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  1752. // an exception for incorrect registers. This matches MSVC behavior.
  1753. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  1754. BuiltinID == AArch64::BI_WriteStatusReg)
  1755. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  1756. if (BuiltinID == AArch64::BI__getReg)
  1757. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  1758. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1759. return true;
  1760. // For intrinsics which take an immediate value as part of the instruction,
  1761. // range check them here.
  1762. unsigned i = 0, l = 0, u = 0;
  1763. switch (BuiltinID) {
  1764. default: return false;
  1765. case AArch64::BI__builtin_arm_dmb:
  1766. case AArch64::BI__builtin_arm_dsb:
  1767. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1768. case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
  1769. }
  1770. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1771. }
  1772. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1773. struct BuiltinAndString {
  1774. unsigned BuiltinID;
  1775. const char *Str;
  1776. };
  1777. static BuiltinAndString ValidCPU[] = {
  1778. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
  1779. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
  1780. { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
  1781. { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
  1782. { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
  1783. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
  1784. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
  1785. { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
  1786. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
  1787. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
  1788. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
  1789. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
  1790. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
  1791. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
  1792. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
  1793. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
  1794. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
  1795. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
  1796. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
  1797. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
  1798. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
  1799. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
  1800. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
  1801. };
  1802. static BuiltinAndString ValidHVX[] = {
  1803. { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
  1804. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
  1805. { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
  1806. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
  1807. { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
  1808. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
  1809. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
  1810. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
  1811. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
  1812. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
  1813. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
  1814. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
  1815. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
  1816. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
  1817. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
  1818. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
  1819. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
  1820. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
  1821. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
  1822. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
  1823. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
  1824. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
  1825. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
  1826. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
  1827. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
  1828. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
  1829. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
  1830. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
  1831. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
  1832. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
  1833. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
  1834. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
  1835. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
  1836. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
  1837. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
  2330. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
  2331. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
  2332. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
  2333. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
  2334. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
  2335. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
  2336. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
  2337. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
  2338. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
  2339. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
  2340. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
  2341. { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
  2342. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
  2343. { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
  2344. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
  2345. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
  2346. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
  2347. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
  2348. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
  2349. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
  2350. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
  2351. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
  2352. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
  2353. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
  2354. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
  2355. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
  2356. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
  2357. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
  2358. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
  2359. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
  2360. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
  2361. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
  2362. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
  2363. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
  2364. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
  2365. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
  2366. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
  2367. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
  2368. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
  2369. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
  2370. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
  2371. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
  2372. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
  2373. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
  2374. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
  2375. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
  2376. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
  2377. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
  2378. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
  2379. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
  2380. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
  2381. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
  2382. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
  2383. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
  2384. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
  2385. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
  2386. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
  2387. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
  2388. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
  2389. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
  2390. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
  2391. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
  2392. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
  2393. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
  2394. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
  2395. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
  2396. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
  2397. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
  2398. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
  2399. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
  2400. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
  2401. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
  2402. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
  2403. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
  2404. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
  2405. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
  2406. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
  2407. { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
  2408. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
  2409. { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
  2410. { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
  2411. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
  2412. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
  2413. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
  2414. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
  2415. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
  2416. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
  2417. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
  2418. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
  2419. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
  2420. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
  2421. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
  2422. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
  2423. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
  2424. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
  2425. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
  2426. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
  2427. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
  2428. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
  2429. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
  2430. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
  2431. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
  2432. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
  2433. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
  2434. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
  2435. { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
  2436. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
  2437. { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
  2438. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
  2439. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
  2440. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
  2441. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
  2442. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
  2443. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
  2444. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
  2445. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
  2446. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
  2447. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
  2448. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
  2449. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
  2450. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
  2451. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
  2452. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
  2453. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
  2454. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
  2455. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
  2456. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
  2457. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
  2458. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
  2459. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
  2460. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
  2461. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
  2462. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
  2463. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
  2464. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
  2465. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
  2466. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
  2467. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
  2468. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
  2469. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
  2470. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
  2471. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
  2472. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
  2473. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
  2474. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
  2475. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
  2476. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
  2477. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
  2478. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
  2479. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
  2480. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
  2481. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
  2482. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
  2483. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
  2484. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
  2485. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
  2486. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
  2487. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
  2488. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
  2489. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
  2490. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
  2491. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
  2492. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
  2493. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
  2494. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
  2495. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
  2496. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
  2497. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
  2498. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
  2499. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
  2500. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
  2501. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
  2502. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
  2503. { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
  2504. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
  2505. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
  2506. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
  2507. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
  2508. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
  2509. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
  2510. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
  2511. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
  2512. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
  2513. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
  2514. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
  2515. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
  2516. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
  2517. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
  2518. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
  2519. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
  2520. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
  2521. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
  2522. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
  2523. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
  2524. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
  2525. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
  2526. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
  2527. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
  2528. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
  2529. { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
  2530. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
  2531. { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
  2532. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
  2533. { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
  2534. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
  2535. };
  2536. // Sort the tables on first execution so we can binary search them.
  2537. auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
  2538. return LHS.BuiltinID < RHS.BuiltinID;
  2539. };
  2540. static const bool SortOnce =
  2541. (llvm::sort(ValidCPU, SortCmp),
  2542. llvm::sort(ValidHVX, SortCmp), true);
  2543. (void)SortOnce;
  2544. auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
  2545. return BI.BuiltinID < BuiltinID;
  2546. };
  2547. const TargetInfo &TI = Context.getTargetInfo();
  2548. const BuiltinAndString *FC =
  2549. llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
  2550. if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
  2551. const TargetOptions &Opts = TI.getTargetOpts();
  2552. StringRef CPU = Opts.CPU;
  2553. if (!CPU.empty()) {
  2554. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2555. CPU.consume_front("hexagon");
  2556. SmallVector<StringRef, 3> CPUs;
  2557. StringRef(FC->Str).split(CPUs, ',');
  2558. if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
  2559. return Diag(TheCall->getBeginLoc(),
  2560. diag::err_hexagon_builtin_unsupported_cpu);
  2561. }
  2562. }
  2563. const BuiltinAndString *FH =
  2564. llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
  2565. if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
  2566. if (!TI.hasFeature("hvx"))
  2567. return Diag(TheCall->getBeginLoc(),
  2568. diag::err_hexagon_builtin_requires_hvx);
  2569. SmallVector<StringRef, 3> HVXs;
  2570. StringRef(FH->Str).split(HVXs, ',');
  2571. bool IsValid = llvm::any_of(HVXs,
  2572. [&TI] (StringRef V) {
  2573. std::string F = "hvx" + V.str();
  2574. return TI.hasFeature(F);
  2575. });
  2576. if (!IsValid)
  2577. return Diag(TheCall->getBeginLoc(),
  2578. diag::err_hexagon_builtin_unsupported_hvx);
  2579. }
  2580. return false;
  2581. }
  2582. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2583. struct ArgInfo {
  2584. uint8_t OpNum;
  2585. bool IsSigned;
  2586. uint8_t BitWidth;
  2587. uint8_t Align;
  2588. };
  2589. struct BuiltinInfo {
  2590. unsigned BuiltinID;
  2591. ArgInfo Infos[2];
  2592. };
  2593. static BuiltinInfo Infos[] = {
  2594. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2595. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2596. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2597. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
  2598. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2599. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2600. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2601. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2602. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2603. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2604. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2605. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2606. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2607. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2608. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2609. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2610. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2611. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2612. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2613. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2614. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2615. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2616. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2617. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2618. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2619. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2620. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2621. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2622. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2623. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2624. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2625. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2626. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2627. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2628. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2629. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2630. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2631. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2632. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2633. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2634. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2635. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2636. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2637. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2638. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2639. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2640. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2641. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2642. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2643. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2644. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2645. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2646. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2647. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2648. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2649. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2650. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2651. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2652. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2653. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2654. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2655. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2656. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2657. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2658. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2659. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2660. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2661. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2662. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2663. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2664. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2665. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2666. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2667. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2668. {{ 1, false, 6, 0 }} },
  2669. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2670. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2671. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2672. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2673. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2674. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2675. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2676. {{ 1, false, 5, 0 }} },
  2677. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2678. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2679. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2680. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2681. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2682. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2683. { 2, false, 5, 0 }} },
  2684. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2685. { 2, false, 6, 0 }} },
  2686. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2687. { 3, false, 5, 0 }} },
  2688. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2689. { 3, false, 6, 0 }} },
  2690. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2691. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2692. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2693. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2694. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2695. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2696. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2697. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2698. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2699. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2700. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2701. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2702. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2703. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2704. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2705. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2706. {{ 2, false, 4, 0 },
  2707. { 3, false, 5, 0 }} },
  2708. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2709. {{ 2, false, 4, 0 },
  2710. { 3, false, 5, 0 }} },
  2711. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2712. {{ 2, false, 4, 0 },
  2713. { 3, false, 5, 0 }} },
  2714. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2715. {{ 2, false, 4, 0 },
  2716. { 3, false, 5, 0 }} },
  2717. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2718. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2719. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2720. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2721. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2722. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2723. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2724. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2725. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2726. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2727. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2728. { 2, false, 5, 0 }} },
  2729. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2730. { 2, false, 6, 0 }} },
  2731. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2732. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2733. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2734. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2735. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2736. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2737. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2738. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2739. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2740. {{ 1, false, 4, 0 }} },
  2741. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2742. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2743. {{ 1, false, 4, 0 }} },
  2744. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2745. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2746. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2747. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2748. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2749. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2750. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2751. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2752. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2753. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2754. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2755. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2756. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2757. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2758. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2759. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2760. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2761. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2762. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2763. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2764. {{ 3, false, 1, 0 }} },
  2765. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2766. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2767. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2768. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2769. {{ 3, false, 1, 0 }} },
  2770. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2771. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2772. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2773. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2774. {{ 3, false, 1, 0 }} },
  2775. };
  2776. // Use a dynamically initialized static to sort the table exactly once on
  2777. // first run.
  2778. static const bool SortOnce =
  2779. (llvm::sort(Infos,
  2780. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  2781. return LHS.BuiltinID < RHS.BuiltinID;
  2782. }),
  2783. true);
  2784. (void)SortOnce;
  2785. const BuiltinInfo *F = llvm::partition_point(
  2786. Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
  2787. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2788. return false;
  2789. bool Error = false;
  2790. for (const ArgInfo &A : F->Infos) {
  2791. // Ignore empty ArgInfo elements.
  2792. if (A.BitWidth == 0)
  2793. continue;
  2794. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2795. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2796. if (!A.Align) {
  2797. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2798. } else {
  2799. unsigned M = 1 << A.Align;
  2800. Min *= M;
  2801. Max *= M;
  2802. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2803. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2804. }
  2805. }
  2806. return Error;
  2807. }
  2808. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2809. CallExpr *TheCall) {
  2810. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2811. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2812. }
  2813. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2814. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2815. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2816. // by the underlying instruction i.e., df/m, df/n and then by size.
  2817. //
  2818. // FIXME: The size tests here should instead be tablegen'd along with the
  2819. // definitions from include/clang/Basic/BuiltinsMips.def.
  2820. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2821. // be too.
  2822. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2823. unsigned i = 0, l = 0, u = 0, m = 0;
  2824. switch (BuiltinID) {
  2825. default: return false;
  2826. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2827. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2828. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2829. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2830. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2831. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2832. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2833. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  2834. // df/m field.
  2835. // These intrinsics take an unsigned 3 bit immediate.
  2836. case Mips::BI__builtin_msa_bclri_b:
  2837. case Mips::BI__builtin_msa_bnegi_b:
  2838. case Mips::BI__builtin_msa_bseti_b:
  2839. case Mips::BI__builtin_msa_sat_s_b:
  2840. case Mips::BI__builtin_msa_sat_u_b:
  2841. case Mips::BI__builtin_msa_slli_b:
  2842. case Mips::BI__builtin_msa_srai_b:
  2843. case Mips::BI__builtin_msa_srari_b:
  2844. case Mips::BI__builtin_msa_srli_b:
  2845. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2846. case Mips::BI__builtin_msa_binsli_b:
  2847. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2848. // These intrinsics take an unsigned 4 bit immediate.
  2849. case Mips::BI__builtin_msa_bclri_h:
  2850. case Mips::BI__builtin_msa_bnegi_h:
  2851. case Mips::BI__builtin_msa_bseti_h:
  2852. case Mips::BI__builtin_msa_sat_s_h:
  2853. case Mips::BI__builtin_msa_sat_u_h:
  2854. case Mips::BI__builtin_msa_slli_h:
  2855. case Mips::BI__builtin_msa_srai_h:
  2856. case Mips::BI__builtin_msa_srari_h:
  2857. case Mips::BI__builtin_msa_srli_h:
  2858. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2859. case Mips::BI__builtin_msa_binsli_h:
  2860. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2861. // These intrinsics take an unsigned 5 bit immediate.
  2862. // The first block of intrinsics actually have an unsigned 5 bit field,
  2863. // not a df/n field.
  2864. case Mips::BI__builtin_msa_cfcmsa:
  2865. case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
  2866. case Mips::BI__builtin_msa_clei_u_b:
  2867. case Mips::BI__builtin_msa_clei_u_h:
  2868. case Mips::BI__builtin_msa_clei_u_w:
  2869. case Mips::BI__builtin_msa_clei_u_d:
  2870. case Mips::BI__builtin_msa_clti_u_b:
  2871. case Mips::BI__builtin_msa_clti_u_h:
  2872. case Mips::BI__builtin_msa_clti_u_w:
  2873. case Mips::BI__builtin_msa_clti_u_d:
  2874. case Mips::BI__builtin_msa_maxi_u_b:
  2875. case Mips::BI__builtin_msa_maxi_u_h:
  2876. case Mips::BI__builtin_msa_maxi_u_w:
  2877. case Mips::BI__builtin_msa_maxi_u_d:
  2878. case Mips::BI__builtin_msa_mini_u_b:
  2879. case Mips::BI__builtin_msa_mini_u_h:
  2880. case Mips::BI__builtin_msa_mini_u_w:
  2881. case Mips::BI__builtin_msa_mini_u_d:
  2882. case Mips::BI__builtin_msa_addvi_b:
  2883. case Mips::BI__builtin_msa_addvi_h:
  2884. case Mips::BI__builtin_msa_addvi_w:
  2885. case Mips::BI__builtin_msa_addvi_d:
  2886. case Mips::BI__builtin_msa_bclri_w:
  2887. case Mips::BI__builtin_msa_bnegi_w:
  2888. case Mips::BI__builtin_msa_bseti_w:
  2889. case Mips::BI__builtin_msa_sat_s_w:
  2890. case Mips::BI__builtin_msa_sat_u_w:
  2891. case Mips::BI__builtin_msa_slli_w:
  2892. case Mips::BI__builtin_msa_srai_w:
  2893. case Mips::BI__builtin_msa_srari_w:
  2894. case Mips::BI__builtin_msa_srli_w:
  2895. case Mips::BI__builtin_msa_srlri_w:
  2896. case Mips::BI__builtin_msa_subvi_b:
  2897. case Mips::BI__builtin_msa_subvi_h:
  2898. case Mips::BI__builtin_msa_subvi_w:
  2899. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2900. case Mips::BI__builtin_msa_binsli_w:
  2901. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2902. // These intrinsics take an unsigned 6 bit immediate.
  2903. case Mips::BI__builtin_msa_bclri_d:
  2904. case Mips::BI__builtin_msa_bnegi_d:
  2905. case Mips::BI__builtin_msa_bseti_d:
  2906. case Mips::BI__builtin_msa_sat_s_d:
  2907. case Mips::BI__builtin_msa_sat_u_d:
  2908. case Mips::BI__builtin_msa_slli_d:
  2909. case Mips::BI__builtin_msa_srai_d:
  2910. case Mips::BI__builtin_msa_srari_d:
  2911. case Mips::BI__builtin_msa_srli_d:
  2912. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2913. case Mips::BI__builtin_msa_binsli_d:
  2914. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2915. // These intrinsics take a signed 5 bit immediate.
  2916. case Mips::BI__builtin_msa_ceqi_b:
  2917. case Mips::BI__builtin_msa_ceqi_h:
  2918. case Mips::BI__builtin_msa_ceqi_w:
  2919. case Mips::BI__builtin_msa_ceqi_d:
  2920. case Mips::BI__builtin_msa_clti_s_b:
  2921. case Mips::BI__builtin_msa_clti_s_h:
  2922. case Mips::BI__builtin_msa_clti_s_w:
  2923. case Mips::BI__builtin_msa_clti_s_d:
  2924. case Mips::BI__builtin_msa_clei_s_b:
  2925. case Mips::BI__builtin_msa_clei_s_h:
  2926. case Mips::BI__builtin_msa_clei_s_w:
  2927. case Mips::BI__builtin_msa_clei_s_d:
  2928. case Mips::BI__builtin_msa_maxi_s_b:
  2929. case Mips::BI__builtin_msa_maxi_s_h:
  2930. case Mips::BI__builtin_msa_maxi_s_w:
  2931. case Mips::BI__builtin_msa_maxi_s_d:
  2932. case Mips::BI__builtin_msa_mini_s_b:
  2933. case Mips::BI__builtin_msa_mini_s_h:
  2934. case Mips::BI__builtin_msa_mini_s_w:
  2935. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2936. // These intrinsics take an unsigned 8 bit immediate.
  2937. case Mips::BI__builtin_msa_andi_b:
  2938. case Mips::BI__builtin_msa_nori_b:
  2939. case Mips::BI__builtin_msa_ori_b:
  2940. case Mips::BI__builtin_msa_shf_b:
  2941. case Mips::BI__builtin_msa_shf_h:
  2942. case Mips::BI__builtin_msa_shf_w:
  2943. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2944. case Mips::BI__builtin_msa_bseli_b:
  2945. case Mips::BI__builtin_msa_bmnzi_b:
  2946. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2947. // df/n format
  2948. // These intrinsics take an unsigned 4 bit immediate.
  2949. case Mips::BI__builtin_msa_copy_s_b:
  2950. case Mips::BI__builtin_msa_copy_u_b:
  2951. case Mips::BI__builtin_msa_insve_b:
  2952. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2953. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2954. // These intrinsics take an unsigned 3 bit immediate.
  2955. case Mips::BI__builtin_msa_copy_s_h:
  2956. case Mips::BI__builtin_msa_copy_u_h:
  2957. case Mips::BI__builtin_msa_insve_h:
  2958. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2959. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2960. // These intrinsics take an unsigned 2 bit immediate.
  2961. case Mips::BI__builtin_msa_copy_s_w:
  2962. case Mips::BI__builtin_msa_copy_u_w:
  2963. case Mips::BI__builtin_msa_insve_w:
  2964. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2965. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2966. // These intrinsics take an unsigned 1 bit immediate.
  2967. case Mips::BI__builtin_msa_copy_s_d:
  2968. case Mips::BI__builtin_msa_copy_u_d:
  2969. case Mips::BI__builtin_msa_insve_d:
  2970. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2971. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2972. // Memory offsets and immediate loads.
  2973. // These intrinsics take a signed 10 bit immediate.
  2974. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2975. case Mips::BI__builtin_msa_ldi_h:
  2976. case Mips::BI__builtin_msa_ldi_w:
  2977. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2978. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  2979. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  2980. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  2981. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  2982. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  2983. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  2984. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  2985. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  2986. }
  2987. if (!m)
  2988. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2989. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2990. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2991. }
  2992. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2993. unsigned i = 0, l = 0, u = 0;
  2994. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2995. BuiltinID == PPC::BI__builtin_divdeu ||
  2996. BuiltinID == PPC::BI__builtin_bpermd;
  2997. bool IsTarget64Bit = Context.getTargetInfo()
  2998. .getTypeWidth(Context
  2999. .getTargetInfo()
  3000. .getIntPtrType()) == 64;
  3001. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  3002. BuiltinID == PPC::BI__builtin_divweu ||
  3003. BuiltinID == PPC::BI__builtin_divde ||
  3004. BuiltinID == PPC::BI__builtin_divdeu;
  3005. if (Is64BitBltin && !IsTarget64Bit)
  3006. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  3007. << TheCall->getSourceRange();
  3008. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  3009. (BuiltinID == PPC::BI__builtin_bpermd &&
  3010. !Context.getTargetInfo().hasFeature("bpermd")))
  3011. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3012. << TheCall->getSourceRange();
  3013. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  3014. if (!Context.getTargetInfo().hasFeature("vsx"))
  3015. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3016. << TheCall->getSourceRange();
  3017. return false;
  3018. };
  3019. switch (BuiltinID) {
  3020. default: return false;
  3021. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3022. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3023. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3024. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3025. case PPC::BI__builtin_altivec_dss:
  3026. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
  3027. case PPC::BI__builtin_tbegin:
  3028. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  3029. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  3030. case PPC::BI__builtin_tabortwc:
  3031. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  3032. case PPC::BI__builtin_tabortwci:
  3033. case PPC::BI__builtin_tabortdci:
  3034. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3035. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  3036. case PPC::BI__builtin_altivec_dst:
  3037. case PPC::BI__builtin_altivec_dstt:
  3038. case PPC::BI__builtin_altivec_dstst:
  3039. case PPC::BI__builtin_altivec_dststt:
  3040. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
  3041. case PPC::BI__builtin_vsx_xxpermdi:
  3042. case PPC::BI__builtin_vsx_xxsldwi:
  3043. return SemaBuiltinVSX(TheCall);
  3044. case PPC::BI__builtin_unpack_vector_int128:
  3045. return SemaVSXCheck(TheCall) ||
  3046. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3047. case PPC::BI__builtin_pack_vector_int128:
  3048. return SemaVSXCheck(TheCall);
  3049. }
  3050. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3051. }
  3052. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  3053. CallExpr *TheCall) {
  3054. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  3055. Expr *Arg = TheCall->getArg(0);
  3056. llvm::APSInt AbortCode(32);
  3057. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  3058. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  3059. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  3060. << Arg->getSourceRange();
  3061. }
  3062. // For intrinsics which take an immediate value as part of the instruction,
  3063. // range check them here.
  3064. unsigned i = 0, l = 0, u = 0;
  3065. switch (BuiltinID) {
  3066. default: return false;
  3067. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  3068. case SystemZ::BI__builtin_s390_verimb:
  3069. case SystemZ::BI__builtin_s390_verimh:
  3070. case SystemZ::BI__builtin_s390_verimf:
  3071. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  3072. case SystemZ::BI__builtin_s390_vfaeb:
  3073. case SystemZ::BI__builtin_s390_vfaeh:
  3074. case SystemZ::BI__builtin_s390_vfaef:
  3075. case SystemZ::BI__builtin_s390_vfaebs:
  3076. case SystemZ::BI__builtin_s390_vfaehs:
  3077. case SystemZ::BI__builtin_s390_vfaefs:
  3078. case SystemZ::BI__builtin_s390_vfaezb:
  3079. case SystemZ::BI__builtin_s390_vfaezh:
  3080. case SystemZ::BI__builtin_s390_vfaezf:
  3081. case SystemZ::BI__builtin_s390_vfaezbs:
  3082. case SystemZ::BI__builtin_s390_vfaezhs:
  3083. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  3084. case SystemZ::BI__builtin_s390_vfisb:
  3085. case SystemZ::BI__builtin_s390_vfidb:
  3086. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  3087. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3088. case SystemZ::BI__builtin_s390_vftcisb:
  3089. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  3090. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  3091. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  3092. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  3093. case SystemZ::BI__builtin_s390_vstrcb:
  3094. case SystemZ::BI__builtin_s390_vstrch:
  3095. case SystemZ::BI__builtin_s390_vstrcf:
  3096. case SystemZ::BI__builtin_s390_vstrczb:
  3097. case SystemZ::BI__builtin_s390_vstrczh:
  3098. case SystemZ::BI__builtin_s390_vstrczf:
  3099. case SystemZ::BI__builtin_s390_vstrcbs:
  3100. case SystemZ::BI__builtin_s390_vstrchs:
  3101. case SystemZ::BI__builtin_s390_vstrcfs:
  3102. case SystemZ::BI__builtin_s390_vstrczbs:
  3103. case SystemZ::BI__builtin_s390_vstrczhs:
  3104. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3105. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3106. case SystemZ::BI__builtin_s390_vfminsb:
  3107. case SystemZ::BI__builtin_s390_vfmaxsb:
  3108. case SystemZ::BI__builtin_s390_vfmindb:
  3109. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3110. case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
  3111. case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
  3112. }
  3113. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3114. }
  3115. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3116. /// This checks that the target supports __builtin_cpu_supports and
  3117. /// that the string argument is constant and valid.
  3118. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  3119. Expr *Arg = TheCall->getArg(0);
  3120. // Check if the argument is a string literal.
  3121. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3122. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3123. << Arg->getSourceRange();
  3124. // Check the contents of the string.
  3125. StringRef Feature =
  3126. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3127. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  3128. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3129. << Arg->getSourceRange();
  3130. return false;
  3131. }
  3132. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3133. /// This checks that the target supports __builtin_cpu_is and
  3134. /// that the string argument is constant and valid.
  3135. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  3136. Expr *Arg = TheCall->getArg(0);
  3137. // Check if the argument is a string literal.
  3138. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3139. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3140. << Arg->getSourceRange();
  3141. // Check the contents of the string.
  3142. StringRef Feature =
  3143. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3144. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  3145. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3146. << Arg->getSourceRange();
  3147. return false;
  3148. }
  3149. // Check if the rounding mode is legal.
  3150. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3151. // Indicates if this instruction has rounding control or just SAE.
  3152. bool HasRC = false;
  3153. unsigned ArgNum = 0;
  3154. switch (BuiltinID) {
  3155. default:
  3156. return false;
  3157. case X86::BI__builtin_ia32_vcvttsd2si32:
  3158. case X86::BI__builtin_ia32_vcvttsd2si64:
  3159. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3160. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3161. case X86::BI__builtin_ia32_vcvttss2si32:
  3162. case X86::BI__builtin_ia32_vcvttss2si64:
  3163. case X86::BI__builtin_ia32_vcvttss2usi32:
  3164. case X86::BI__builtin_ia32_vcvttss2usi64:
  3165. ArgNum = 1;
  3166. break;
  3167. case X86::BI__builtin_ia32_maxpd512:
  3168. case X86::BI__builtin_ia32_maxps512:
  3169. case X86::BI__builtin_ia32_minpd512:
  3170. case X86::BI__builtin_ia32_minps512:
  3171. ArgNum = 2;
  3172. break;
  3173. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3174. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3175. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3176. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3177. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3178. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3179. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3180. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3181. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3182. case X86::BI__builtin_ia32_exp2pd_mask:
  3183. case X86::BI__builtin_ia32_exp2ps_mask:
  3184. case X86::BI__builtin_ia32_getexppd512_mask:
  3185. case X86::BI__builtin_ia32_getexpps512_mask:
  3186. case X86::BI__builtin_ia32_rcp28pd_mask:
  3187. case X86::BI__builtin_ia32_rcp28ps_mask:
  3188. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3189. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3190. case X86::BI__builtin_ia32_vcomisd:
  3191. case X86::BI__builtin_ia32_vcomiss:
  3192. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3193. ArgNum = 3;
  3194. break;
  3195. case X86::BI__builtin_ia32_cmppd512_mask:
  3196. case X86::BI__builtin_ia32_cmpps512_mask:
  3197. case X86::BI__builtin_ia32_cmpsd_mask:
  3198. case X86::BI__builtin_ia32_cmpss_mask:
  3199. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3200. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3201. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3202. case X86::BI__builtin_ia32_getmantpd512_mask:
  3203. case X86::BI__builtin_ia32_getmantps512_mask:
  3204. case X86::BI__builtin_ia32_maxsd_round_mask:
  3205. case X86::BI__builtin_ia32_maxss_round_mask:
  3206. case X86::BI__builtin_ia32_minsd_round_mask:
  3207. case X86::BI__builtin_ia32_minss_round_mask:
  3208. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3209. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3210. case X86::BI__builtin_ia32_reducepd512_mask:
  3211. case X86::BI__builtin_ia32_reduceps512_mask:
  3212. case X86::BI__builtin_ia32_rndscalepd_mask:
  3213. case X86::BI__builtin_ia32_rndscaleps_mask:
  3214. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3215. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3216. ArgNum = 4;
  3217. break;
  3218. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3219. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3220. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3221. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3222. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3223. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3224. case X86::BI__builtin_ia32_fixupimmss_mask:
  3225. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3226. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3227. case X86::BI__builtin_ia32_getmantss_round_mask:
  3228. case X86::BI__builtin_ia32_rangepd512_mask:
  3229. case X86::BI__builtin_ia32_rangeps512_mask:
  3230. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3231. case X86::BI__builtin_ia32_rangess128_round_mask:
  3232. case X86::BI__builtin_ia32_reducesd_mask:
  3233. case X86::BI__builtin_ia32_reducess_mask:
  3234. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3235. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3236. ArgNum = 5;
  3237. break;
  3238. case X86::BI__builtin_ia32_vcvtsd2si64:
  3239. case X86::BI__builtin_ia32_vcvtsd2si32:
  3240. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3241. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3242. case X86::BI__builtin_ia32_vcvtss2si32:
  3243. case X86::BI__builtin_ia32_vcvtss2si64:
  3244. case X86::BI__builtin_ia32_vcvtss2usi32:
  3245. case X86::BI__builtin_ia32_vcvtss2usi64:
  3246. case X86::BI__builtin_ia32_sqrtpd512:
  3247. case X86::BI__builtin_ia32_sqrtps512:
  3248. ArgNum = 1;
  3249. HasRC = true;
  3250. break;
  3251. case X86::BI__builtin_ia32_addpd512:
  3252. case X86::BI__builtin_ia32_addps512:
  3253. case X86::BI__builtin_ia32_divpd512:
  3254. case X86::BI__builtin_ia32_divps512:
  3255. case X86::BI__builtin_ia32_mulpd512:
  3256. case X86::BI__builtin_ia32_mulps512:
  3257. case X86::BI__builtin_ia32_subpd512:
  3258. case X86::BI__builtin_ia32_subps512:
  3259. case X86::BI__builtin_ia32_cvtsi2sd64:
  3260. case X86::BI__builtin_ia32_cvtsi2ss32:
  3261. case X86::BI__builtin_ia32_cvtsi2ss64:
  3262. case X86::BI__builtin_ia32_cvtusi2sd64:
  3263. case X86::BI__builtin_ia32_cvtusi2ss32:
  3264. case X86::BI__builtin_ia32_cvtusi2ss64:
  3265. ArgNum = 2;
  3266. HasRC = true;
  3267. break;
  3268. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3269. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3270. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3271. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  3272. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3273. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  3274. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3275. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  3276. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3277. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  3278. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3279. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3280. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3281. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3282. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3283. ArgNum = 3;
  3284. HasRC = true;
  3285. break;
  3286. case X86::BI__builtin_ia32_addss_round_mask:
  3287. case X86::BI__builtin_ia32_addsd_round_mask:
  3288. case X86::BI__builtin_ia32_divss_round_mask:
  3289. case X86::BI__builtin_ia32_divsd_round_mask:
  3290. case X86::BI__builtin_ia32_mulss_round_mask:
  3291. case X86::BI__builtin_ia32_mulsd_round_mask:
  3292. case X86::BI__builtin_ia32_subss_round_mask:
  3293. case X86::BI__builtin_ia32_subsd_round_mask:
  3294. case X86::BI__builtin_ia32_scalefpd512_mask:
  3295. case X86::BI__builtin_ia32_scalefps512_mask:
  3296. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3297. case X86::BI__builtin_ia32_scalefss_round_mask:
  3298. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3299. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3300. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3301. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3302. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3303. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3304. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3305. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3306. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3307. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3308. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3309. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3310. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3311. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3312. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3313. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3314. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3315. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3316. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3317. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3318. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3319. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3320. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3321. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3322. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3323. ArgNum = 4;
  3324. HasRC = true;
  3325. break;
  3326. }
  3327. llvm::APSInt Result;
  3328. // We can't check the value of a dependent argument.
  3329. Expr *Arg = TheCall->getArg(ArgNum);
  3330. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3331. return false;
  3332. // Check constant-ness first.
  3333. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3334. return true;
  3335. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3336. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3337. // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
  3338. // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
  3339. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3340. Result == 8/*ROUND_NO_EXC*/ ||
  3341. (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
  3342. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3343. return false;
  3344. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3345. << Arg->getSourceRange();
  3346. }
  3347. // Check if the gather/scatter scale is legal.
  3348. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3349. CallExpr *TheCall) {
  3350. unsigned ArgNum = 0;
  3351. switch (BuiltinID) {
  3352. default:
  3353. return false;
  3354. case X86::BI__builtin_ia32_gatherpfdpd:
  3355. case X86::BI__builtin_ia32_gatherpfdps:
  3356. case X86::BI__builtin_ia32_gatherpfqpd:
  3357. case X86::BI__builtin_ia32_gatherpfqps:
  3358. case X86::BI__builtin_ia32_scatterpfdpd:
  3359. case X86::BI__builtin_ia32_scatterpfdps:
  3360. case X86::BI__builtin_ia32_scatterpfqpd:
  3361. case X86::BI__builtin_ia32_scatterpfqps:
  3362. ArgNum = 3;
  3363. break;
  3364. case X86::BI__builtin_ia32_gatherd_pd:
  3365. case X86::BI__builtin_ia32_gatherd_pd256:
  3366. case X86::BI__builtin_ia32_gatherq_pd:
  3367. case X86::BI__builtin_ia32_gatherq_pd256:
  3368. case X86::BI__builtin_ia32_gatherd_ps:
  3369. case X86::BI__builtin_ia32_gatherd_ps256:
  3370. case X86::BI__builtin_ia32_gatherq_ps:
  3371. case X86::BI__builtin_ia32_gatherq_ps256:
  3372. case X86::BI__builtin_ia32_gatherd_q:
  3373. case X86::BI__builtin_ia32_gatherd_q256:
  3374. case X86::BI__builtin_ia32_gatherq_q:
  3375. case X86::BI__builtin_ia32_gatherq_q256:
  3376. case X86::BI__builtin_ia32_gatherd_d:
  3377. case X86::BI__builtin_ia32_gatherd_d256:
  3378. case X86::BI__builtin_ia32_gatherq_d:
  3379. case X86::BI__builtin_ia32_gatherq_d256:
  3380. case X86::BI__builtin_ia32_gather3div2df:
  3381. case X86::BI__builtin_ia32_gather3div2di:
  3382. case X86::BI__builtin_ia32_gather3div4df:
  3383. case X86::BI__builtin_ia32_gather3div4di:
  3384. case X86::BI__builtin_ia32_gather3div4sf:
  3385. case X86::BI__builtin_ia32_gather3div4si:
  3386. case X86::BI__builtin_ia32_gather3div8sf:
  3387. case X86::BI__builtin_ia32_gather3div8si:
  3388. case X86::BI__builtin_ia32_gather3siv2df:
  3389. case X86::BI__builtin_ia32_gather3siv2di:
  3390. case X86::BI__builtin_ia32_gather3siv4df:
  3391. case X86::BI__builtin_ia32_gather3siv4di:
  3392. case X86::BI__builtin_ia32_gather3siv4sf:
  3393. case X86::BI__builtin_ia32_gather3siv4si:
  3394. case X86::BI__builtin_ia32_gather3siv8sf:
  3395. case X86::BI__builtin_ia32_gather3siv8si:
  3396. case X86::BI__builtin_ia32_gathersiv8df:
  3397. case X86::BI__builtin_ia32_gathersiv16sf:
  3398. case X86::BI__builtin_ia32_gatherdiv8df:
  3399. case X86::BI__builtin_ia32_gatherdiv16sf:
  3400. case X86::BI__builtin_ia32_gathersiv8di:
  3401. case X86::BI__builtin_ia32_gathersiv16si:
  3402. case X86::BI__builtin_ia32_gatherdiv8di:
  3403. case X86::BI__builtin_ia32_gatherdiv16si:
  3404. case X86::BI__builtin_ia32_scatterdiv2df:
  3405. case X86::BI__builtin_ia32_scatterdiv2di:
  3406. case X86::BI__builtin_ia32_scatterdiv4df:
  3407. case X86::BI__builtin_ia32_scatterdiv4di:
  3408. case X86::BI__builtin_ia32_scatterdiv4sf:
  3409. case X86::BI__builtin_ia32_scatterdiv4si:
  3410. case X86::BI__builtin_ia32_scatterdiv8sf:
  3411. case X86::BI__builtin_ia32_scatterdiv8si:
  3412. case X86::BI__builtin_ia32_scattersiv2df:
  3413. case X86::BI__builtin_ia32_scattersiv2di:
  3414. case X86::BI__builtin_ia32_scattersiv4df:
  3415. case X86::BI__builtin_ia32_scattersiv4di:
  3416. case X86::BI__builtin_ia32_scattersiv4sf:
  3417. case X86::BI__builtin_ia32_scattersiv4si:
  3418. case X86::BI__builtin_ia32_scattersiv8sf:
  3419. case X86::BI__builtin_ia32_scattersiv8si:
  3420. case X86::BI__builtin_ia32_scattersiv8df:
  3421. case X86::BI__builtin_ia32_scattersiv16sf:
  3422. case X86::BI__builtin_ia32_scatterdiv8df:
  3423. case X86::BI__builtin_ia32_scatterdiv16sf:
  3424. case X86::BI__builtin_ia32_scattersiv8di:
  3425. case X86::BI__builtin_ia32_scattersiv16si:
  3426. case X86::BI__builtin_ia32_scatterdiv8di:
  3427. case X86::BI__builtin_ia32_scatterdiv16si:
  3428. ArgNum = 4;
  3429. break;
  3430. }
  3431. llvm::APSInt Result;
  3432. // We can't check the value of a dependent argument.
  3433. Expr *Arg = TheCall->getArg(ArgNum);
  3434. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3435. return false;
  3436. // Check constant-ness first.
  3437. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3438. return true;
  3439. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3440. return false;
  3441. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3442. << Arg->getSourceRange();
  3443. }
  3444. static bool isX86_32Builtin(unsigned BuiltinID) {
  3445. // These builtins only work on x86-32 targets.
  3446. switch (BuiltinID) {
  3447. case X86::BI__builtin_ia32_readeflags_u32:
  3448. case X86::BI__builtin_ia32_writeeflags_u32:
  3449. return true;
  3450. }
  3451. return false;
  3452. }
  3453. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3454. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3455. return SemaBuiltinCpuSupports(*this, TheCall);
  3456. if (BuiltinID == X86::BI__builtin_cpu_is)
  3457. return SemaBuiltinCpuIs(*this, TheCall);
  3458. // Check for 32-bit only builtins on a 64-bit target.
  3459. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3460. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3461. return Diag(TheCall->getCallee()->getBeginLoc(),
  3462. diag::err_32_bit_builtin_64_bit_tgt);
  3463. // If the intrinsic has rounding or SAE make sure its valid.
  3464. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3465. return true;
  3466. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3467. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3468. return true;
  3469. // For intrinsics which take an immediate value as part of the instruction,
  3470. // range check them here.
  3471. int i = 0, l = 0, u = 0;
  3472. switch (BuiltinID) {
  3473. default:
  3474. return false;
  3475. case X86::BI__builtin_ia32_vec_ext_v2si:
  3476. case X86::BI__builtin_ia32_vec_ext_v2di:
  3477. case X86::BI__builtin_ia32_vextractf128_pd256:
  3478. case X86::BI__builtin_ia32_vextractf128_ps256:
  3479. case X86::BI__builtin_ia32_vextractf128_si256:
  3480. case X86::BI__builtin_ia32_extract128i256:
  3481. case X86::BI__builtin_ia32_extractf64x4_mask:
  3482. case X86::BI__builtin_ia32_extracti64x4_mask:
  3483. case X86::BI__builtin_ia32_extractf32x8_mask:
  3484. case X86::BI__builtin_ia32_extracti32x8_mask:
  3485. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3486. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3487. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3488. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3489. i = 1; l = 0; u = 1;
  3490. break;
  3491. case X86::BI__builtin_ia32_vec_set_v2di:
  3492. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3493. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3494. case X86::BI__builtin_ia32_vinsertf128_si256:
  3495. case X86::BI__builtin_ia32_insert128i256:
  3496. case X86::BI__builtin_ia32_insertf32x8:
  3497. case X86::BI__builtin_ia32_inserti32x8:
  3498. case X86::BI__builtin_ia32_insertf64x4:
  3499. case X86::BI__builtin_ia32_inserti64x4:
  3500. case X86::BI__builtin_ia32_insertf64x2_256:
  3501. case X86::BI__builtin_ia32_inserti64x2_256:
  3502. case X86::BI__builtin_ia32_insertf32x4_256:
  3503. case X86::BI__builtin_ia32_inserti32x4_256:
  3504. i = 2; l = 0; u = 1;
  3505. break;
  3506. case X86::BI__builtin_ia32_vpermilpd:
  3507. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3508. case X86::BI__builtin_ia32_vec_ext_v4si:
  3509. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3510. case X86::BI__builtin_ia32_vec_ext_v4di:
  3511. case X86::BI__builtin_ia32_extractf32x4_mask:
  3512. case X86::BI__builtin_ia32_extracti32x4_mask:
  3513. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3514. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3515. i = 1; l = 0; u = 3;
  3516. break;
  3517. case X86::BI_mm_prefetch:
  3518. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3519. case X86::BI__builtin_ia32_vec_ext_v8si:
  3520. i = 1; l = 0; u = 7;
  3521. break;
  3522. case X86::BI__builtin_ia32_sha1rnds4:
  3523. case X86::BI__builtin_ia32_blendpd:
  3524. case X86::BI__builtin_ia32_shufpd:
  3525. case X86::BI__builtin_ia32_vec_set_v4hi:
  3526. case X86::BI__builtin_ia32_vec_set_v4si:
  3527. case X86::BI__builtin_ia32_vec_set_v4di:
  3528. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3529. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3530. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3531. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3532. case X86::BI__builtin_ia32_insertf64x2_512:
  3533. case X86::BI__builtin_ia32_inserti64x2_512:
  3534. case X86::BI__builtin_ia32_insertf32x4:
  3535. case X86::BI__builtin_ia32_inserti32x4:
  3536. i = 2; l = 0; u = 3;
  3537. break;
  3538. case X86::BI__builtin_ia32_vpermil2pd:
  3539. case X86::BI__builtin_ia32_vpermil2pd256:
  3540. case X86::BI__builtin_ia32_vpermil2ps:
  3541. case X86::BI__builtin_ia32_vpermil2ps256:
  3542. i = 3; l = 0; u = 3;
  3543. break;
  3544. case X86::BI__builtin_ia32_cmpb128_mask:
  3545. case X86::BI__builtin_ia32_cmpw128_mask:
  3546. case X86::BI__builtin_ia32_cmpd128_mask:
  3547. case X86::BI__builtin_ia32_cmpq128_mask:
  3548. case X86::BI__builtin_ia32_cmpb256_mask:
  3549. case X86::BI__builtin_ia32_cmpw256_mask:
  3550. case X86::BI__builtin_ia32_cmpd256_mask:
  3551. case X86::BI__builtin_ia32_cmpq256_mask:
  3552. case X86::BI__builtin_ia32_cmpb512_mask:
  3553. case X86::BI__builtin_ia32_cmpw512_mask:
  3554. case X86::BI__builtin_ia32_cmpd512_mask:
  3555. case X86::BI__builtin_ia32_cmpq512_mask:
  3556. case X86::BI__builtin_ia32_ucmpb128_mask:
  3557. case X86::BI__builtin_ia32_ucmpw128_mask:
  3558. case X86::BI__builtin_ia32_ucmpd128_mask:
  3559. case X86::BI__builtin_ia32_ucmpq128_mask:
  3560. case X86::BI__builtin_ia32_ucmpb256_mask:
  3561. case X86::BI__builtin_ia32_ucmpw256_mask:
  3562. case X86::BI__builtin_ia32_ucmpd256_mask:
  3563. case X86::BI__builtin_ia32_ucmpq256_mask:
  3564. case X86::BI__builtin_ia32_ucmpb512_mask:
  3565. case X86::BI__builtin_ia32_ucmpw512_mask:
  3566. case X86::BI__builtin_ia32_ucmpd512_mask:
  3567. case X86::BI__builtin_ia32_ucmpq512_mask:
  3568. case X86::BI__builtin_ia32_vpcomub:
  3569. case X86::BI__builtin_ia32_vpcomuw:
  3570. case X86::BI__builtin_ia32_vpcomud:
  3571. case X86::BI__builtin_ia32_vpcomuq:
  3572. case X86::BI__builtin_ia32_vpcomb:
  3573. case X86::BI__builtin_ia32_vpcomw:
  3574. case X86::BI__builtin_ia32_vpcomd:
  3575. case X86::BI__builtin_ia32_vpcomq:
  3576. case X86::BI__builtin_ia32_vec_set_v8hi:
  3577. case X86::BI__builtin_ia32_vec_set_v8si:
  3578. i = 2; l = 0; u = 7;
  3579. break;
  3580. case X86::BI__builtin_ia32_vpermilpd256:
  3581. case X86::BI__builtin_ia32_roundps:
  3582. case X86::BI__builtin_ia32_roundpd:
  3583. case X86::BI__builtin_ia32_roundps256:
  3584. case X86::BI__builtin_ia32_roundpd256:
  3585. case X86::BI__builtin_ia32_getmantpd128_mask:
  3586. case X86::BI__builtin_ia32_getmantpd256_mask:
  3587. case X86::BI__builtin_ia32_getmantps128_mask:
  3588. case X86::BI__builtin_ia32_getmantps256_mask:
  3589. case X86::BI__builtin_ia32_getmantpd512_mask:
  3590. case X86::BI__builtin_ia32_getmantps512_mask:
  3591. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3592. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3593. i = 1; l = 0; u = 15;
  3594. break;
  3595. case X86::BI__builtin_ia32_pblendd128:
  3596. case X86::BI__builtin_ia32_blendps:
  3597. case X86::BI__builtin_ia32_blendpd256:
  3598. case X86::BI__builtin_ia32_shufpd256:
  3599. case X86::BI__builtin_ia32_roundss:
  3600. case X86::BI__builtin_ia32_roundsd:
  3601. case X86::BI__builtin_ia32_rangepd128_mask:
  3602. case X86::BI__builtin_ia32_rangepd256_mask:
  3603. case X86::BI__builtin_ia32_rangepd512_mask:
  3604. case X86::BI__builtin_ia32_rangeps128_mask:
  3605. case X86::BI__builtin_ia32_rangeps256_mask:
  3606. case X86::BI__builtin_ia32_rangeps512_mask:
  3607. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3608. case X86::BI__builtin_ia32_getmantss_round_mask:
  3609. case X86::BI__builtin_ia32_vec_set_v16qi:
  3610. case X86::BI__builtin_ia32_vec_set_v16hi:
  3611. i = 2; l = 0; u = 15;
  3612. break;
  3613. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3614. i = 1; l = 0; u = 31;
  3615. break;
  3616. case X86::BI__builtin_ia32_cmpps:
  3617. case X86::BI__builtin_ia32_cmpss:
  3618. case X86::BI__builtin_ia32_cmppd:
  3619. case X86::BI__builtin_ia32_cmpsd:
  3620. case X86::BI__builtin_ia32_cmpps256:
  3621. case X86::BI__builtin_ia32_cmppd256:
  3622. case X86::BI__builtin_ia32_cmpps128_mask:
  3623. case X86::BI__builtin_ia32_cmppd128_mask:
  3624. case X86::BI__builtin_ia32_cmpps256_mask:
  3625. case X86::BI__builtin_ia32_cmppd256_mask:
  3626. case X86::BI__builtin_ia32_cmpps512_mask:
  3627. case X86::BI__builtin_ia32_cmppd512_mask:
  3628. case X86::BI__builtin_ia32_cmpsd_mask:
  3629. case X86::BI__builtin_ia32_cmpss_mask:
  3630. case X86::BI__builtin_ia32_vec_set_v32qi:
  3631. i = 2; l = 0; u = 31;
  3632. break;
  3633. case X86::BI__builtin_ia32_permdf256:
  3634. case X86::BI__builtin_ia32_permdi256:
  3635. case X86::BI__builtin_ia32_permdf512:
  3636. case X86::BI__builtin_ia32_permdi512:
  3637. case X86::BI__builtin_ia32_vpermilps:
  3638. case X86::BI__builtin_ia32_vpermilps256:
  3639. case X86::BI__builtin_ia32_vpermilpd512:
  3640. case X86::BI__builtin_ia32_vpermilps512:
  3641. case X86::BI__builtin_ia32_pshufd:
  3642. case X86::BI__builtin_ia32_pshufd256:
  3643. case X86::BI__builtin_ia32_pshufd512:
  3644. case X86::BI__builtin_ia32_pshufhw:
  3645. case X86::BI__builtin_ia32_pshufhw256:
  3646. case X86::BI__builtin_ia32_pshufhw512:
  3647. case X86::BI__builtin_ia32_pshuflw:
  3648. case X86::BI__builtin_ia32_pshuflw256:
  3649. case X86::BI__builtin_ia32_pshuflw512:
  3650. case X86::BI__builtin_ia32_vcvtps2ph:
  3651. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3652. case X86::BI__builtin_ia32_vcvtps2ph256:
  3653. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3654. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3655. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3656. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3657. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3658. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3659. case X86::BI__builtin_ia32_rndscaleps_mask:
  3660. case X86::BI__builtin_ia32_rndscalepd_mask:
  3661. case X86::BI__builtin_ia32_reducepd128_mask:
  3662. case X86::BI__builtin_ia32_reducepd256_mask:
  3663. case X86::BI__builtin_ia32_reducepd512_mask:
  3664. case X86::BI__builtin_ia32_reduceps128_mask:
  3665. case X86::BI__builtin_ia32_reduceps256_mask:
  3666. case X86::BI__builtin_ia32_reduceps512_mask:
  3667. case X86::BI__builtin_ia32_prold512:
  3668. case X86::BI__builtin_ia32_prolq512:
  3669. case X86::BI__builtin_ia32_prold128:
  3670. case X86::BI__builtin_ia32_prold256:
  3671. case X86::BI__builtin_ia32_prolq128:
  3672. case X86::BI__builtin_ia32_prolq256:
  3673. case X86::BI__builtin_ia32_prord512:
  3674. case X86::BI__builtin_ia32_prorq512:
  3675. case X86::BI__builtin_ia32_prord128:
  3676. case X86::BI__builtin_ia32_prord256:
  3677. case X86::BI__builtin_ia32_prorq128:
  3678. case X86::BI__builtin_ia32_prorq256:
  3679. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3680. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3681. case X86::BI__builtin_ia32_fpclassps128_mask:
  3682. case X86::BI__builtin_ia32_fpclassps256_mask:
  3683. case X86::BI__builtin_ia32_fpclassps512_mask:
  3684. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3685. case X86::BI__builtin_ia32_fpclasssd_mask:
  3686. case X86::BI__builtin_ia32_fpclassss_mask:
  3687. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3688. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3689. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3690. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3691. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3692. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3693. case X86::BI__builtin_ia32_kshiftliqi:
  3694. case X86::BI__builtin_ia32_kshiftlihi:
  3695. case X86::BI__builtin_ia32_kshiftlisi:
  3696. case X86::BI__builtin_ia32_kshiftlidi:
  3697. case X86::BI__builtin_ia32_kshiftriqi:
  3698. case X86::BI__builtin_ia32_kshiftrihi:
  3699. case X86::BI__builtin_ia32_kshiftrisi:
  3700. case X86::BI__builtin_ia32_kshiftridi:
  3701. i = 1; l = 0; u = 255;
  3702. break;
  3703. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3704. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3705. case X86::BI__builtin_ia32_vperm2f128_si256:
  3706. case X86::BI__builtin_ia32_permti256:
  3707. case X86::BI__builtin_ia32_pblendw128:
  3708. case X86::BI__builtin_ia32_pblendw256:
  3709. case X86::BI__builtin_ia32_blendps256:
  3710. case X86::BI__builtin_ia32_pblendd256:
  3711. case X86::BI__builtin_ia32_palignr128:
  3712. case X86::BI__builtin_ia32_palignr256:
  3713. case X86::BI__builtin_ia32_palignr512:
  3714. case X86::BI__builtin_ia32_alignq512:
  3715. case X86::BI__builtin_ia32_alignd512:
  3716. case X86::BI__builtin_ia32_alignd128:
  3717. case X86::BI__builtin_ia32_alignd256:
  3718. case X86::BI__builtin_ia32_alignq128:
  3719. case X86::BI__builtin_ia32_alignq256:
  3720. case X86::BI__builtin_ia32_vcomisd:
  3721. case X86::BI__builtin_ia32_vcomiss:
  3722. case X86::BI__builtin_ia32_shuf_f32x4:
  3723. case X86::BI__builtin_ia32_shuf_f64x2:
  3724. case X86::BI__builtin_ia32_shuf_i32x4:
  3725. case X86::BI__builtin_ia32_shuf_i64x2:
  3726. case X86::BI__builtin_ia32_shufpd512:
  3727. case X86::BI__builtin_ia32_shufps:
  3728. case X86::BI__builtin_ia32_shufps256:
  3729. case X86::BI__builtin_ia32_shufps512:
  3730. case X86::BI__builtin_ia32_dbpsadbw128:
  3731. case X86::BI__builtin_ia32_dbpsadbw256:
  3732. case X86::BI__builtin_ia32_dbpsadbw512:
  3733. case X86::BI__builtin_ia32_vpshldd128:
  3734. case X86::BI__builtin_ia32_vpshldd256:
  3735. case X86::BI__builtin_ia32_vpshldd512:
  3736. case X86::BI__builtin_ia32_vpshldq128:
  3737. case X86::BI__builtin_ia32_vpshldq256:
  3738. case X86::BI__builtin_ia32_vpshldq512:
  3739. case X86::BI__builtin_ia32_vpshldw128:
  3740. case X86::BI__builtin_ia32_vpshldw256:
  3741. case X86::BI__builtin_ia32_vpshldw512:
  3742. case X86::BI__builtin_ia32_vpshrdd128:
  3743. case X86::BI__builtin_ia32_vpshrdd256:
  3744. case X86::BI__builtin_ia32_vpshrdd512:
  3745. case X86::BI__builtin_ia32_vpshrdq128:
  3746. case X86::BI__builtin_ia32_vpshrdq256:
  3747. case X86::BI__builtin_ia32_vpshrdq512:
  3748. case X86::BI__builtin_ia32_vpshrdw128:
  3749. case X86::BI__builtin_ia32_vpshrdw256:
  3750. case X86::BI__builtin_ia32_vpshrdw512:
  3751. i = 2; l = 0; u = 255;
  3752. break;
  3753. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3754. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3755. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3756. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3757. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3758. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3759. case X86::BI__builtin_ia32_fixupimmss_mask:
  3760. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3761. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3762. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3763. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3764. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3765. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3766. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3767. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3768. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3769. case X86::BI__builtin_ia32_pternlogd512_mask:
  3770. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3771. case X86::BI__builtin_ia32_pternlogq512_mask:
  3772. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3773. case X86::BI__builtin_ia32_pternlogd128_mask:
  3774. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3775. case X86::BI__builtin_ia32_pternlogd256_mask:
  3776. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3777. case X86::BI__builtin_ia32_pternlogq128_mask:
  3778. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3779. case X86::BI__builtin_ia32_pternlogq256_mask:
  3780. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3781. i = 3; l = 0; u = 255;
  3782. break;
  3783. case X86::BI__builtin_ia32_gatherpfdpd:
  3784. case X86::BI__builtin_ia32_gatherpfdps:
  3785. case X86::BI__builtin_ia32_gatherpfqpd:
  3786. case X86::BI__builtin_ia32_gatherpfqps:
  3787. case X86::BI__builtin_ia32_scatterpfdpd:
  3788. case X86::BI__builtin_ia32_scatterpfdps:
  3789. case X86::BI__builtin_ia32_scatterpfqpd:
  3790. case X86::BI__builtin_ia32_scatterpfqps:
  3791. i = 4; l = 2; u = 3;
  3792. break;
  3793. case X86::BI__builtin_ia32_reducesd_mask:
  3794. case X86::BI__builtin_ia32_reducess_mask:
  3795. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3796. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3797. i = 4; l = 0; u = 255;
  3798. break;
  3799. }
  3800. // Note that we don't force a hard error on the range check here, allowing
  3801. // template-generated or macro-generated dead code to potentially have out-of-
  3802. // range values. These need to code generate, but don't need to necessarily
  3803. // make any sense. We use a warning that defaults to an error.
  3804. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3805. }
  3806. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3807. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3808. /// Returns true when the format fits the function and the FormatStringInfo has
  3809. /// been populated.
  3810. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3811. FormatStringInfo *FSI) {
  3812. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3813. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3814. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3815. // The way the format attribute works in GCC, the implicit this argument
  3816. // of member functions is counted. However, it doesn't appear in our own
  3817. // lists, so decrement format_idx in that case.
  3818. if (IsCXXMember) {
  3819. if(FSI->FormatIdx == 0)
  3820. return false;
  3821. --FSI->FormatIdx;
  3822. if (FSI->FirstDataArg != 0)
  3823. --FSI->FirstDataArg;
  3824. }
  3825. return true;
  3826. }
  3827. /// Checks if a the given expression evaluates to null.
  3828. ///
  3829. /// Returns true if the value evaluates to null.
  3830. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3831. // If the expression has non-null type, it doesn't evaluate to null.
  3832. if (auto nullability
  3833. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3834. if (*nullability == NullabilityKind::NonNull)
  3835. return false;
  3836. }
  3837. // As a special case, transparent unions initialized with zero are
  3838. // considered null for the purposes of the nonnull attribute.
  3839. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3840. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3841. if (const CompoundLiteralExpr *CLE =
  3842. dyn_cast<CompoundLiteralExpr>(Expr))
  3843. if (const InitListExpr *ILE =
  3844. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3845. Expr = ILE->getInit(0);
  3846. }
  3847. bool Result;
  3848. return (!Expr->isValueDependent() &&
  3849. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3850. !Result);
  3851. }
  3852. static void CheckNonNullArgument(Sema &S,
  3853. const Expr *ArgExpr,
  3854. SourceLocation CallSiteLoc) {
  3855. if (CheckNonNullExpr(S, ArgExpr))
  3856. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3857. S.PDiag(diag::warn_null_arg)
  3858. << ArgExpr->getSourceRange());
  3859. }
  3860. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3861. FormatStringInfo FSI;
  3862. if ((GetFormatStringType(Format) == FST_NSString) &&
  3863. getFormatStringInfo(Format, false, &FSI)) {
  3864. Idx = FSI.FormatIdx;
  3865. return true;
  3866. }
  3867. return false;
  3868. }
  3869. /// Diagnose use of %s directive in an NSString which is being passed
  3870. /// as formatting string to formatting method.
  3871. static void
  3872. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3873. const NamedDecl *FDecl,
  3874. Expr **Args,
  3875. unsigned NumArgs) {
  3876. unsigned Idx = 0;
  3877. bool Format = false;
  3878. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3879. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3880. Idx = 2;
  3881. Format = true;
  3882. }
  3883. else
  3884. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3885. if (S.GetFormatNSStringIdx(I, Idx)) {
  3886. Format = true;
  3887. break;
  3888. }
  3889. }
  3890. if (!Format || NumArgs <= Idx)
  3891. return;
  3892. const Expr *FormatExpr = Args[Idx];
  3893. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3894. FormatExpr = CSCE->getSubExpr();
  3895. const StringLiteral *FormatString;
  3896. if (const ObjCStringLiteral *OSL =
  3897. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3898. FormatString = OSL->getString();
  3899. else
  3900. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3901. if (!FormatString)
  3902. return;
  3903. if (S.FormatStringHasSArg(FormatString)) {
  3904. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3905. << "%s" << 1 << 1;
  3906. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3907. << FDecl->getDeclName();
  3908. }
  3909. }
  3910. /// Determine whether the given type has a non-null nullability annotation.
  3911. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3912. if (auto nullability = type->getNullability(ctx))
  3913. return *nullability == NullabilityKind::NonNull;
  3914. return false;
  3915. }
  3916. static void CheckNonNullArguments(Sema &S,
  3917. const NamedDecl *FDecl,
  3918. const FunctionProtoType *Proto,
  3919. ArrayRef<const Expr *> Args,
  3920. SourceLocation CallSiteLoc) {
  3921. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3922. // Already checked by by constant evaluator.
  3923. if (S.isConstantEvaluated())
  3924. return;
  3925. // Check the attributes attached to the method/function itself.
  3926. llvm::SmallBitVector NonNullArgs;
  3927. if (FDecl) {
  3928. // Handle the nonnull attribute on the function/method declaration itself.
  3929. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3930. if (!NonNull->args_size()) {
  3931. // Easy case: all pointer arguments are nonnull.
  3932. for (const auto *Arg : Args)
  3933. if (S.isValidPointerAttrType(Arg->getType()))
  3934. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3935. return;
  3936. }
  3937. for (const ParamIdx &Idx : NonNull->args()) {
  3938. unsigned IdxAST = Idx.getASTIndex();
  3939. if (IdxAST >= Args.size())
  3940. continue;
  3941. if (NonNullArgs.empty())
  3942. NonNullArgs.resize(Args.size());
  3943. NonNullArgs.set(IdxAST);
  3944. }
  3945. }
  3946. }
  3947. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3948. // Handle the nonnull attribute on the parameters of the
  3949. // function/method.
  3950. ArrayRef<ParmVarDecl*> parms;
  3951. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3952. parms = FD->parameters();
  3953. else
  3954. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3955. unsigned ParamIndex = 0;
  3956. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3957. I != E; ++I, ++ParamIndex) {
  3958. const ParmVarDecl *PVD = *I;
  3959. if (PVD->hasAttr<NonNullAttr>() ||
  3960. isNonNullType(S.Context, PVD->getType())) {
  3961. if (NonNullArgs.empty())
  3962. NonNullArgs.resize(Args.size());
  3963. NonNullArgs.set(ParamIndex);
  3964. }
  3965. }
  3966. } else {
  3967. // If we have a non-function, non-method declaration but no
  3968. // function prototype, try to dig out the function prototype.
  3969. if (!Proto) {
  3970. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3971. QualType type = VD->getType().getNonReferenceType();
  3972. if (auto pointerType = type->getAs<PointerType>())
  3973. type = pointerType->getPointeeType();
  3974. else if (auto blockType = type->getAs<BlockPointerType>())
  3975. type = blockType->getPointeeType();
  3976. // FIXME: data member pointers?
  3977. // Dig out the function prototype, if there is one.
  3978. Proto = type->getAs<FunctionProtoType>();
  3979. }
  3980. }
  3981. // Fill in non-null argument information from the nullability
  3982. // information on the parameter types (if we have them).
  3983. if (Proto) {
  3984. unsigned Index = 0;
  3985. for (auto paramType : Proto->getParamTypes()) {
  3986. if (isNonNullType(S.Context, paramType)) {
  3987. if (NonNullArgs.empty())
  3988. NonNullArgs.resize(Args.size());
  3989. NonNullArgs.set(Index);
  3990. }
  3991. ++Index;
  3992. }
  3993. }
  3994. }
  3995. // Check for non-null arguments.
  3996. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3997. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3998. if (NonNullArgs[ArgIndex])
  3999. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  4000. }
  4001. }
  4002. /// Handles the checks for format strings, non-POD arguments to vararg
  4003. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  4004. /// attributes.
  4005. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  4006. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  4007. bool IsMemberFunction, SourceLocation Loc,
  4008. SourceRange Range, VariadicCallType CallType) {
  4009. // FIXME: We should check as much as we can in the template definition.
  4010. if (CurContext->isDependentContext())
  4011. return;
  4012. // Printf and scanf checking.
  4013. llvm::SmallBitVector CheckedVarArgs;
  4014. if (FDecl) {
  4015. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  4016. // Only create vector if there are format attributes.
  4017. CheckedVarArgs.resize(Args.size());
  4018. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  4019. CheckedVarArgs);
  4020. }
  4021. }
  4022. // Refuse POD arguments that weren't caught by the format string
  4023. // checks above.
  4024. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  4025. if (CallType != VariadicDoesNotApply &&
  4026. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  4027. unsigned NumParams = Proto ? Proto->getNumParams()
  4028. : FDecl && isa<FunctionDecl>(FDecl)
  4029. ? cast<FunctionDecl>(FDecl)->getNumParams()
  4030. : FDecl && isa<ObjCMethodDecl>(FDecl)
  4031. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  4032. : 0;
  4033. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  4034. // Args[ArgIdx] can be null in malformed code.
  4035. if (const Expr *Arg = Args[ArgIdx]) {
  4036. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  4037. checkVariadicArgument(Arg, CallType);
  4038. }
  4039. }
  4040. }
  4041. if (FDecl || Proto) {
  4042. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  4043. // Type safety checking.
  4044. if (FDecl) {
  4045. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  4046. CheckArgumentWithTypeTag(I, Args, Loc);
  4047. }
  4048. }
  4049. if (FD)
  4050. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  4051. }
  4052. /// CheckConstructorCall - Check a constructor call for correctness and safety
  4053. /// properties not enforced by the C type system.
  4054. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  4055. ArrayRef<const Expr *> Args,
  4056. const FunctionProtoType *Proto,
  4057. SourceLocation Loc) {
  4058. VariadicCallType CallType =
  4059. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  4060. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  4061. Loc, SourceRange(), CallType);
  4062. }
  4063. /// CheckFunctionCall - Check a direct function call for various correctness
  4064. /// and safety properties not strictly enforced by the C type system.
  4065. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  4066. const FunctionProtoType *Proto) {
  4067. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  4068. isa<CXXMethodDecl>(FDecl);
  4069. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  4070. IsMemberOperatorCall;
  4071. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  4072. TheCall->getCallee());
  4073. Expr** Args = TheCall->getArgs();
  4074. unsigned NumArgs = TheCall->getNumArgs();
  4075. Expr *ImplicitThis = nullptr;
  4076. if (IsMemberOperatorCall) {
  4077. // If this is a call to a member operator, hide the first argument
  4078. // from checkCall.
  4079. // FIXME: Our choice of AST representation here is less than ideal.
  4080. ImplicitThis = Args[0];
  4081. ++Args;
  4082. --NumArgs;
  4083. } else if (IsMemberFunction)
  4084. ImplicitThis =
  4085. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  4086. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  4087. IsMemberFunction, TheCall->getRParenLoc(),
  4088. TheCall->getCallee()->getSourceRange(), CallType);
  4089. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4090. // None of the checks below are needed for functions that don't have
  4091. // simple names (e.g., C++ conversion functions).
  4092. if (!FnInfo)
  4093. return false;
  4094. CheckAbsoluteValueFunction(TheCall, FDecl);
  4095. CheckMaxUnsignedZero(TheCall, FDecl);
  4096. if (getLangOpts().ObjC)
  4097. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  4098. unsigned CMId = FDecl->getMemoryFunctionKind();
  4099. if (CMId == 0)
  4100. return false;
  4101. // Handle memory setting and copying functions.
  4102. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  4103. CheckStrlcpycatArguments(TheCall, FnInfo);
  4104. else if (CMId == Builtin::BIstrncat)
  4105. CheckStrncatArguments(TheCall, FnInfo);
  4106. else
  4107. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  4108. return false;
  4109. }
  4110. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  4111. ArrayRef<const Expr *> Args) {
  4112. VariadicCallType CallType =
  4113. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  4114. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  4115. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  4116. CallType);
  4117. return false;
  4118. }
  4119. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  4120. const FunctionProtoType *Proto) {
  4121. QualType Ty;
  4122. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  4123. Ty = V->getType().getNonReferenceType();
  4124. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  4125. Ty = F->getType().getNonReferenceType();
  4126. else
  4127. return false;
  4128. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  4129. !Ty->isFunctionProtoType())
  4130. return false;
  4131. VariadicCallType CallType;
  4132. if (!Proto || !Proto->isVariadic()) {
  4133. CallType = VariadicDoesNotApply;
  4134. } else if (Ty->isBlockPointerType()) {
  4135. CallType = VariadicBlock;
  4136. } else { // Ty->isFunctionPointerType()
  4137. CallType = VariadicFunction;
  4138. }
  4139. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  4140. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4141. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4142. TheCall->getCallee()->getSourceRange(), CallType);
  4143. return false;
  4144. }
  4145. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  4146. /// such as function pointers returned from functions.
  4147. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  4148. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  4149. TheCall->getCallee());
  4150. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  4151. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4152. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4153. TheCall->getCallee()->getSourceRange(), CallType);
  4154. return false;
  4155. }
  4156. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  4157. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  4158. return false;
  4159. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  4160. switch (Op) {
  4161. case AtomicExpr::AO__c11_atomic_init:
  4162. case AtomicExpr::AO__opencl_atomic_init:
  4163. llvm_unreachable("There is no ordering argument for an init");
  4164. case AtomicExpr::AO__c11_atomic_load:
  4165. case AtomicExpr::AO__opencl_atomic_load:
  4166. case AtomicExpr::AO__atomic_load_n:
  4167. case AtomicExpr::AO__atomic_load:
  4168. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  4169. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4170. case AtomicExpr::AO__c11_atomic_store:
  4171. case AtomicExpr::AO__opencl_atomic_store:
  4172. case AtomicExpr::AO__atomic_store:
  4173. case AtomicExpr::AO__atomic_store_n:
  4174. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  4175. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  4176. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4177. default:
  4178. return true;
  4179. }
  4180. }
  4181. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4182. AtomicExpr::AtomicOp Op) {
  4183. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4184. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4185. MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
  4186. return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
  4187. DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
  4188. Op);
  4189. }
  4190. ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
  4191. SourceLocation RParenLoc, MultiExprArg Args,
  4192. AtomicExpr::AtomicOp Op,
  4193. AtomicArgumentOrder ArgOrder) {
  4194. // All the non-OpenCL operations take one of the following forms.
  4195. // The OpenCL operations take the __c11 forms with one extra argument for
  4196. // synchronization scope.
  4197. enum {
  4198. // C __c11_atomic_init(A *, C)
  4199. Init,
  4200. // C __c11_atomic_load(A *, int)
  4201. Load,
  4202. // void __atomic_load(A *, CP, int)
  4203. LoadCopy,
  4204. // void __atomic_store(A *, CP, int)
  4205. Copy,
  4206. // C __c11_atomic_add(A *, M, int)
  4207. Arithmetic,
  4208. // C __atomic_exchange_n(A *, CP, int)
  4209. Xchg,
  4210. // void __atomic_exchange(A *, C *, CP, int)
  4211. GNUXchg,
  4212. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4213. C11CmpXchg,
  4214. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4215. GNUCmpXchg
  4216. } Form = Init;
  4217. const unsigned NumForm = GNUCmpXchg + 1;
  4218. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4219. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4220. // where:
  4221. // C is an appropriate type,
  4222. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4223. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4224. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4225. // the int parameters are for orderings.
  4226. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4227. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4228. "need to update code for modified forms");
  4229. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4230. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4231. AtomicExpr::AO__atomic_load,
  4232. "need to update code for modified C11 atomics");
  4233. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4234. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4235. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4236. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4237. IsOpenCL;
  4238. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4239. Op == AtomicExpr::AO__atomic_store_n ||
  4240. Op == AtomicExpr::AO__atomic_exchange_n ||
  4241. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4242. bool IsAddSub = false;
  4243. bool IsMinMax = false;
  4244. switch (Op) {
  4245. case AtomicExpr::AO__c11_atomic_init:
  4246. case AtomicExpr::AO__opencl_atomic_init:
  4247. Form = Init;
  4248. break;
  4249. case AtomicExpr::AO__c11_atomic_load:
  4250. case AtomicExpr::AO__opencl_atomic_load:
  4251. case AtomicExpr::AO__atomic_load_n:
  4252. Form = Load;
  4253. break;
  4254. case AtomicExpr::AO__atomic_load:
  4255. Form = LoadCopy;
  4256. break;
  4257. case AtomicExpr::AO__c11_atomic_store:
  4258. case AtomicExpr::AO__opencl_atomic_store:
  4259. case AtomicExpr::AO__atomic_store:
  4260. case AtomicExpr::AO__atomic_store_n:
  4261. Form = Copy;
  4262. break;
  4263. case AtomicExpr::AO__c11_atomic_fetch_add:
  4264. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4265. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4266. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4267. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4268. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4269. case AtomicExpr::AO__atomic_fetch_add:
  4270. case AtomicExpr::AO__atomic_fetch_sub:
  4271. case AtomicExpr::AO__atomic_add_fetch:
  4272. case AtomicExpr::AO__atomic_sub_fetch:
  4273. IsAddSub = true;
  4274. LLVM_FALLTHROUGH;
  4275. case AtomicExpr::AO__c11_atomic_fetch_and:
  4276. case AtomicExpr::AO__c11_atomic_fetch_or:
  4277. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4278. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4279. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4280. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4281. case AtomicExpr::AO__atomic_fetch_and:
  4282. case AtomicExpr::AO__atomic_fetch_or:
  4283. case AtomicExpr::AO__atomic_fetch_xor:
  4284. case AtomicExpr::AO__atomic_fetch_nand:
  4285. case AtomicExpr::AO__atomic_and_fetch:
  4286. case AtomicExpr::AO__atomic_or_fetch:
  4287. case AtomicExpr::AO__atomic_xor_fetch:
  4288. case AtomicExpr::AO__atomic_nand_fetch:
  4289. Form = Arithmetic;
  4290. break;
  4291. case AtomicExpr::AO__atomic_fetch_min:
  4292. case AtomicExpr::AO__atomic_fetch_max:
  4293. IsMinMax = true;
  4294. Form = Arithmetic;
  4295. break;
  4296. case AtomicExpr::AO__c11_atomic_exchange:
  4297. case AtomicExpr::AO__opencl_atomic_exchange:
  4298. case AtomicExpr::AO__atomic_exchange_n:
  4299. Form = Xchg;
  4300. break;
  4301. case AtomicExpr::AO__atomic_exchange:
  4302. Form = GNUXchg;
  4303. break;
  4304. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4305. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4306. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4307. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4308. Form = C11CmpXchg;
  4309. break;
  4310. case AtomicExpr::AO__atomic_compare_exchange:
  4311. case AtomicExpr::AO__atomic_compare_exchange_n:
  4312. Form = GNUCmpXchg;
  4313. break;
  4314. }
  4315. unsigned AdjustedNumArgs = NumArgs[Form];
  4316. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4317. ++AdjustedNumArgs;
  4318. // Check we have the right number of arguments.
  4319. if (Args.size() < AdjustedNumArgs) {
  4320. Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
  4321. << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
  4322. << ExprRange;
  4323. return ExprError();
  4324. } else if (Args.size() > AdjustedNumArgs) {
  4325. Diag(Args[AdjustedNumArgs]->getBeginLoc(),
  4326. diag::err_typecheck_call_too_many_args)
  4327. << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
  4328. << ExprRange;
  4329. return ExprError();
  4330. }
  4331. // Inspect the first argument of the atomic operation.
  4332. Expr *Ptr = Args[0];
  4333. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4334. if (ConvertedPtr.isInvalid())
  4335. return ExprError();
  4336. Ptr = ConvertedPtr.get();
  4337. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4338. if (!pointerType) {
  4339. Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
  4340. << Ptr->getType() << Ptr->getSourceRange();
  4341. return ExprError();
  4342. }
  4343. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4344. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4345. QualType ValType = AtomTy; // 'C'
  4346. if (IsC11) {
  4347. if (!AtomTy->isAtomicType()) {
  4348. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
  4349. << Ptr->getType() << Ptr->getSourceRange();
  4350. return ExprError();
  4351. }
  4352. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4353. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4354. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
  4355. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4356. << Ptr->getSourceRange();
  4357. return ExprError();
  4358. }
  4359. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4360. } else if (Form != Load && Form != LoadCopy) {
  4361. if (ValType.isConstQualified()) {
  4362. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
  4363. << Ptr->getType() << Ptr->getSourceRange();
  4364. return ExprError();
  4365. }
  4366. }
  4367. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4368. if (Form == Arithmetic) {
  4369. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4370. if (IsAddSub && !ValType->isIntegerType()
  4371. && !ValType->isPointerType()) {
  4372. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4373. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4374. return ExprError();
  4375. }
  4376. if (IsMinMax) {
  4377. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4378. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4379. BT->getKind() != BuiltinType::UInt)) {
  4380. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_int32_or_ptr);
  4381. return ExprError();
  4382. }
  4383. }
  4384. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4385. Diag(ExprRange.getBegin(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4386. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4387. return ExprError();
  4388. }
  4389. if (IsC11 && ValType->isPointerType() &&
  4390. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4391. diag::err_incomplete_type)) {
  4392. return ExprError();
  4393. }
  4394. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4395. // For __atomic_*_n operations, the value type must be a scalar integral or
  4396. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4397. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4398. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4399. return ExprError();
  4400. }
  4401. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4402. !AtomTy->isScalarType()) {
  4403. // For GNU atomics, require a trivially-copyable type. This is not part of
  4404. // the GNU atomics specification, but we enforce it for sanity.
  4405. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
  4406. << Ptr->getType() << Ptr->getSourceRange();
  4407. return ExprError();
  4408. }
  4409. switch (ValType.getObjCLifetime()) {
  4410. case Qualifiers::OCL_None:
  4411. case Qualifiers::OCL_ExplicitNone:
  4412. // okay
  4413. break;
  4414. case Qualifiers::OCL_Weak:
  4415. case Qualifiers::OCL_Strong:
  4416. case Qualifiers::OCL_Autoreleasing:
  4417. // FIXME: Can this happen? By this point, ValType should be known
  4418. // to be trivially copyable.
  4419. Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
  4420. << ValType << Ptr->getSourceRange();
  4421. return ExprError();
  4422. }
  4423. // All atomic operations have an overload which takes a pointer to a volatile
  4424. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4425. // into the result or the other operands. Similarly atomic_load takes a
  4426. // pointer to a const 'A'.
  4427. ValType.removeLocalVolatile();
  4428. ValType.removeLocalConst();
  4429. QualType ResultType = ValType;
  4430. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4431. Form == Init)
  4432. ResultType = Context.VoidTy;
  4433. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4434. ResultType = Context.BoolTy;
  4435. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4436. // arguments are actually passed as pointers.
  4437. QualType ByValType = ValType; // 'CP'
  4438. bool IsPassedByAddress = false;
  4439. if (!IsC11 && !IsN) {
  4440. ByValType = Ptr->getType();
  4441. IsPassedByAddress = true;
  4442. }
  4443. SmallVector<Expr *, 5> APIOrderedArgs;
  4444. if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
  4445. APIOrderedArgs.push_back(Args[0]);
  4446. switch (Form) {
  4447. case Init:
  4448. case Load:
  4449. APIOrderedArgs.push_back(Args[1]); // Val1/Order
  4450. break;
  4451. case LoadCopy:
  4452. case Copy:
  4453. case Arithmetic:
  4454. case Xchg:
  4455. APIOrderedArgs.push_back(Args[2]); // Val1
  4456. APIOrderedArgs.push_back(Args[1]); // Order
  4457. break;
  4458. case GNUXchg:
  4459. APIOrderedArgs.push_back(Args[2]); // Val1
  4460. APIOrderedArgs.push_back(Args[3]); // Val2
  4461. APIOrderedArgs.push_back(Args[1]); // Order
  4462. break;
  4463. case C11CmpXchg:
  4464. APIOrderedArgs.push_back(Args[2]); // Val1
  4465. APIOrderedArgs.push_back(Args[4]); // Val2
  4466. APIOrderedArgs.push_back(Args[1]); // Order
  4467. APIOrderedArgs.push_back(Args[3]); // OrderFail
  4468. break;
  4469. case GNUCmpXchg:
  4470. APIOrderedArgs.push_back(Args[2]); // Val1
  4471. APIOrderedArgs.push_back(Args[4]); // Val2
  4472. APIOrderedArgs.push_back(Args[5]); // Weak
  4473. APIOrderedArgs.push_back(Args[1]); // Order
  4474. APIOrderedArgs.push_back(Args[3]); // OrderFail
  4475. break;
  4476. }
  4477. } else
  4478. APIOrderedArgs.append(Args.begin(), Args.end());
  4479. // The first argument's non-CV pointer type is used to deduce the type of
  4480. // subsequent arguments, except for:
  4481. // - weak flag (always converted to bool)
  4482. // - memory order (always converted to int)
  4483. // - scope (always converted to int)
  4484. for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
  4485. QualType Ty;
  4486. if (i < NumVals[Form] + 1) {
  4487. switch (i) {
  4488. case 0:
  4489. // The first argument is always a pointer. It has a fixed type.
  4490. // It is always dereferenced, a nullptr is undefined.
  4491. CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
  4492. // Nothing else to do: we already know all we want about this pointer.
  4493. continue;
  4494. case 1:
  4495. // The second argument is the non-atomic operand. For arithmetic, this
  4496. // is always passed by value, and for a compare_exchange it is always
  4497. // passed by address. For the rest, GNU uses by-address and C11 uses
  4498. // by-value.
  4499. assert(Form != Load);
  4500. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4501. Ty = ValType;
  4502. else if (Form == Copy || Form == Xchg) {
  4503. if (IsPassedByAddress) {
  4504. // The value pointer is always dereferenced, a nullptr is undefined.
  4505. CheckNonNullArgument(*this, APIOrderedArgs[i],
  4506. ExprRange.getBegin());
  4507. }
  4508. Ty = ByValType;
  4509. } else if (Form == Arithmetic)
  4510. Ty = Context.getPointerDiffType();
  4511. else {
  4512. Expr *ValArg = APIOrderedArgs[i];
  4513. // The value pointer is always dereferenced, a nullptr is undefined.
  4514. CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
  4515. LangAS AS = LangAS::Default;
  4516. // Keep address space of non-atomic pointer type.
  4517. if (const PointerType *PtrTy =
  4518. ValArg->getType()->getAs<PointerType>()) {
  4519. AS = PtrTy->getPointeeType().getAddressSpace();
  4520. }
  4521. Ty = Context.getPointerType(
  4522. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4523. }
  4524. break;
  4525. case 2:
  4526. // The third argument to compare_exchange / GNU exchange is the desired
  4527. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4528. if (IsPassedByAddress)
  4529. CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
  4530. Ty = ByValType;
  4531. break;
  4532. case 3:
  4533. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4534. Ty = Context.BoolTy;
  4535. break;
  4536. }
  4537. } else {
  4538. // The order(s) and scope are always converted to int.
  4539. Ty = Context.IntTy;
  4540. }
  4541. InitializedEntity Entity =
  4542. InitializedEntity::InitializeParameter(Context, Ty, false);
  4543. ExprResult Arg = APIOrderedArgs[i];
  4544. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4545. if (Arg.isInvalid())
  4546. return true;
  4547. APIOrderedArgs[i] = Arg.get();
  4548. }
  4549. // Permute the arguments into a 'consistent' order.
  4550. SmallVector<Expr*, 5> SubExprs;
  4551. SubExprs.push_back(Ptr);
  4552. switch (Form) {
  4553. case Init:
  4554. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4555. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4556. break;
  4557. case Load:
  4558. SubExprs.push_back(APIOrderedArgs[1]); // Order
  4559. break;
  4560. case LoadCopy:
  4561. case Copy:
  4562. case Arithmetic:
  4563. case Xchg:
  4564. SubExprs.push_back(APIOrderedArgs[2]); // Order
  4565. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4566. break;
  4567. case GNUXchg:
  4568. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4569. SubExprs.push_back(APIOrderedArgs[3]); // Order
  4570. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4571. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  4572. break;
  4573. case C11CmpXchg:
  4574. SubExprs.push_back(APIOrderedArgs[3]); // Order
  4575. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4576. SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
  4577. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  4578. break;
  4579. case GNUCmpXchg:
  4580. SubExprs.push_back(APIOrderedArgs[4]); // Order
  4581. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4582. SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
  4583. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  4584. SubExprs.push_back(APIOrderedArgs[3]); // Weak
  4585. break;
  4586. }
  4587. if (SubExprs.size() >= 2 && Form != Init) {
  4588. llvm::APSInt Result(32);
  4589. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4590. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4591. Diag(SubExprs[1]->getBeginLoc(),
  4592. diag::warn_atomic_op_has_invalid_memory_order)
  4593. << SubExprs[1]->getSourceRange();
  4594. }
  4595. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4596. auto *Scope = Args[Args.size() - 1];
  4597. llvm::APSInt Result(32);
  4598. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4599. !ScopeModel->isValid(Result.getZExtValue())) {
  4600. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4601. << Scope->getSourceRange();
  4602. }
  4603. SubExprs.push_back(Scope);
  4604. }
  4605. AtomicExpr *AE = new (Context)
  4606. AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
  4607. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4608. Op == AtomicExpr::AO__c11_atomic_store ||
  4609. Op == AtomicExpr::AO__opencl_atomic_load ||
  4610. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4611. Context.AtomicUsesUnsupportedLibcall(AE))
  4612. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4613. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4614. Op == AtomicExpr::AO__opencl_atomic_load)
  4615. ? 0
  4616. : 1);
  4617. return AE;
  4618. }
  4619. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4620. /// normal type-checking on the given argument, updating the call in
  4621. /// place. This is useful when a builtin function requires custom
  4622. /// type-checking for some of its arguments but not necessarily all of
  4623. /// them.
  4624. ///
  4625. /// Returns true on error.
  4626. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4627. FunctionDecl *Fn = E->getDirectCallee();
  4628. assert(Fn && "builtin call without direct callee!");
  4629. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4630. InitializedEntity Entity =
  4631. InitializedEntity::InitializeParameter(S.Context, Param);
  4632. ExprResult Arg = E->getArg(0);
  4633. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4634. if (Arg.isInvalid())
  4635. return true;
  4636. E->setArg(ArgIndex, Arg.get());
  4637. return false;
  4638. }
  4639. /// We have a call to a function like __sync_fetch_and_add, which is an
  4640. /// overloaded function based on the pointer type of its first argument.
  4641. /// The main BuildCallExpr routines have already promoted the types of
  4642. /// arguments because all of these calls are prototyped as void(...).
  4643. ///
  4644. /// This function goes through and does final semantic checking for these
  4645. /// builtins, as well as generating any warnings.
  4646. ExprResult
  4647. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4648. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4649. Expr *Callee = TheCall->getCallee();
  4650. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4651. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4652. // Ensure that we have at least one argument to do type inference from.
  4653. if (TheCall->getNumArgs() < 1) {
  4654. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4655. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4656. return ExprError();
  4657. }
  4658. // Inspect the first argument of the atomic builtin. This should always be
  4659. // a pointer type, whose element is an integral scalar or pointer type.
  4660. // Because it is a pointer type, we don't have to worry about any implicit
  4661. // casts here.
  4662. // FIXME: We don't allow floating point scalars as input.
  4663. Expr *FirstArg = TheCall->getArg(0);
  4664. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4665. if (FirstArgResult.isInvalid())
  4666. return ExprError();
  4667. FirstArg = FirstArgResult.get();
  4668. TheCall->setArg(0, FirstArg);
  4669. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4670. if (!pointerType) {
  4671. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4672. << FirstArg->getType() << FirstArg->getSourceRange();
  4673. return ExprError();
  4674. }
  4675. QualType ValType = pointerType->getPointeeType();
  4676. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4677. !ValType->isBlockPointerType()) {
  4678. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4679. << FirstArg->getType() << FirstArg->getSourceRange();
  4680. return ExprError();
  4681. }
  4682. if (ValType.isConstQualified()) {
  4683. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4684. << FirstArg->getType() << FirstArg->getSourceRange();
  4685. return ExprError();
  4686. }
  4687. switch (ValType.getObjCLifetime()) {
  4688. case Qualifiers::OCL_None:
  4689. case Qualifiers::OCL_ExplicitNone:
  4690. // okay
  4691. break;
  4692. case Qualifiers::OCL_Weak:
  4693. case Qualifiers::OCL_Strong:
  4694. case Qualifiers::OCL_Autoreleasing:
  4695. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4696. << ValType << FirstArg->getSourceRange();
  4697. return ExprError();
  4698. }
  4699. // Strip any qualifiers off ValType.
  4700. ValType = ValType.getUnqualifiedType();
  4701. // The majority of builtins return a value, but a few have special return
  4702. // types, so allow them to override appropriately below.
  4703. QualType ResultType = ValType;
  4704. // We need to figure out which concrete builtin this maps onto. For example,
  4705. // __sync_fetch_and_add with a 2 byte object turns into
  4706. // __sync_fetch_and_add_2.
  4707. #define BUILTIN_ROW(x) \
  4708. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4709. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4710. static const unsigned BuiltinIndices[][5] = {
  4711. BUILTIN_ROW(__sync_fetch_and_add),
  4712. BUILTIN_ROW(__sync_fetch_and_sub),
  4713. BUILTIN_ROW(__sync_fetch_and_or),
  4714. BUILTIN_ROW(__sync_fetch_and_and),
  4715. BUILTIN_ROW(__sync_fetch_and_xor),
  4716. BUILTIN_ROW(__sync_fetch_and_nand),
  4717. BUILTIN_ROW(__sync_add_and_fetch),
  4718. BUILTIN_ROW(__sync_sub_and_fetch),
  4719. BUILTIN_ROW(__sync_and_and_fetch),
  4720. BUILTIN_ROW(__sync_or_and_fetch),
  4721. BUILTIN_ROW(__sync_xor_and_fetch),
  4722. BUILTIN_ROW(__sync_nand_and_fetch),
  4723. BUILTIN_ROW(__sync_val_compare_and_swap),
  4724. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4725. BUILTIN_ROW(__sync_lock_test_and_set),
  4726. BUILTIN_ROW(__sync_lock_release),
  4727. BUILTIN_ROW(__sync_swap)
  4728. };
  4729. #undef BUILTIN_ROW
  4730. // Determine the index of the size.
  4731. unsigned SizeIndex;
  4732. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4733. case 1: SizeIndex = 0; break;
  4734. case 2: SizeIndex = 1; break;
  4735. case 4: SizeIndex = 2; break;
  4736. case 8: SizeIndex = 3; break;
  4737. case 16: SizeIndex = 4; break;
  4738. default:
  4739. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4740. << FirstArg->getType() << FirstArg->getSourceRange();
  4741. return ExprError();
  4742. }
  4743. // Each of these builtins has one pointer argument, followed by some number of
  4744. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4745. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4746. // as the number of fixed args.
  4747. unsigned BuiltinID = FDecl->getBuiltinID();
  4748. unsigned BuiltinIndex, NumFixed = 1;
  4749. bool WarnAboutSemanticsChange = false;
  4750. switch (BuiltinID) {
  4751. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4752. case Builtin::BI__sync_fetch_and_add:
  4753. case Builtin::BI__sync_fetch_and_add_1:
  4754. case Builtin::BI__sync_fetch_and_add_2:
  4755. case Builtin::BI__sync_fetch_and_add_4:
  4756. case Builtin::BI__sync_fetch_and_add_8:
  4757. case Builtin::BI__sync_fetch_and_add_16:
  4758. BuiltinIndex = 0;
  4759. break;
  4760. case Builtin::BI__sync_fetch_and_sub:
  4761. case Builtin::BI__sync_fetch_and_sub_1:
  4762. case Builtin::BI__sync_fetch_and_sub_2:
  4763. case Builtin::BI__sync_fetch_and_sub_4:
  4764. case Builtin::BI__sync_fetch_and_sub_8:
  4765. case Builtin::BI__sync_fetch_and_sub_16:
  4766. BuiltinIndex = 1;
  4767. break;
  4768. case Builtin::BI__sync_fetch_and_or:
  4769. case Builtin::BI__sync_fetch_and_or_1:
  4770. case Builtin::BI__sync_fetch_and_or_2:
  4771. case Builtin::BI__sync_fetch_and_or_4:
  4772. case Builtin::BI__sync_fetch_and_or_8:
  4773. case Builtin::BI__sync_fetch_and_or_16:
  4774. BuiltinIndex = 2;
  4775. break;
  4776. case Builtin::BI__sync_fetch_and_and:
  4777. case Builtin::BI__sync_fetch_and_and_1:
  4778. case Builtin::BI__sync_fetch_and_and_2:
  4779. case Builtin::BI__sync_fetch_and_and_4:
  4780. case Builtin::BI__sync_fetch_and_and_8:
  4781. case Builtin::BI__sync_fetch_and_and_16:
  4782. BuiltinIndex = 3;
  4783. break;
  4784. case Builtin::BI__sync_fetch_and_xor:
  4785. case Builtin::BI__sync_fetch_and_xor_1:
  4786. case Builtin::BI__sync_fetch_and_xor_2:
  4787. case Builtin::BI__sync_fetch_and_xor_4:
  4788. case Builtin::BI__sync_fetch_and_xor_8:
  4789. case Builtin::BI__sync_fetch_and_xor_16:
  4790. BuiltinIndex = 4;
  4791. break;
  4792. case Builtin::BI__sync_fetch_and_nand:
  4793. case Builtin::BI__sync_fetch_and_nand_1:
  4794. case Builtin::BI__sync_fetch_and_nand_2:
  4795. case Builtin::BI__sync_fetch_and_nand_4:
  4796. case Builtin::BI__sync_fetch_and_nand_8:
  4797. case Builtin::BI__sync_fetch_and_nand_16:
  4798. BuiltinIndex = 5;
  4799. WarnAboutSemanticsChange = true;
  4800. break;
  4801. case Builtin::BI__sync_add_and_fetch:
  4802. case Builtin::BI__sync_add_and_fetch_1:
  4803. case Builtin::BI__sync_add_and_fetch_2:
  4804. case Builtin::BI__sync_add_and_fetch_4:
  4805. case Builtin::BI__sync_add_and_fetch_8:
  4806. case Builtin::BI__sync_add_and_fetch_16:
  4807. BuiltinIndex = 6;
  4808. break;
  4809. case Builtin::BI__sync_sub_and_fetch:
  4810. case Builtin::BI__sync_sub_and_fetch_1:
  4811. case Builtin::BI__sync_sub_and_fetch_2:
  4812. case Builtin::BI__sync_sub_and_fetch_4:
  4813. case Builtin::BI__sync_sub_and_fetch_8:
  4814. case Builtin::BI__sync_sub_and_fetch_16:
  4815. BuiltinIndex = 7;
  4816. break;
  4817. case Builtin::BI__sync_and_and_fetch:
  4818. case Builtin::BI__sync_and_and_fetch_1:
  4819. case Builtin::BI__sync_and_and_fetch_2:
  4820. case Builtin::BI__sync_and_and_fetch_4:
  4821. case Builtin::BI__sync_and_and_fetch_8:
  4822. case Builtin::BI__sync_and_and_fetch_16:
  4823. BuiltinIndex = 8;
  4824. break;
  4825. case Builtin::BI__sync_or_and_fetch:
  4826. case Builtin::BI__sync_or_and_fetch_1:
  4827. case Builtin::BI__sync_or_and_fetch_2:
  4828. case Builtin::BI__sync_or_and_fetch_4:
  4829. case Builtin::BI__sync_or_and_fetch_8:
  4830. case Builtin::BI__sync_or_and_fetch_16:
  4831. BuiltinIndex = 9;
  4832. break;
  4833. case Builtin::BI__sync_xor_and_fetch:
  4834. case Builtin::BI__sync_xor_and_fetch_1:
  4835. case Builtin::BI__sync_xor_and_fetch_2:
  4836. case Builtin::BI__sync_xor_and_fetch_4:
  4837. case Builtin::BI__sync_xor_and_fetch_8:
  4838. case Builtin::BI__sync_xor_and_fetch_16:
  4839. BuiltinIndex = 10;
  4840. break;
  4841. case Builtin::BI__sync_nand_and_fetch:
  4842. case Builtin::BI__sync_nand_and_fetch_1:
  4843. case Builtin::BI__sync_nand_and_fetch_2:
  4844. case Builtin::BI__sync_nand_and_fetch_4:
  4845. case Builtin::BI__sync_nand_and_fetch_8:
  4846. case Builtin::BI__sync_nand_and_fetch_16:
  4847. BuiltinIndex = 11;
  4848. WarnAboutSemanticsChange = true;
  4849. break;
  4850. case Builtin::BI__sync_val_compare_and_swap:
  4851. case Builtin::BI__sync_val_compare_and_swap_1:
  4852. case Builtin::BI__sync_val_compare_and_swap_2:
  4853. case Builtin::BI__sync_val_compare_and_swap_4:
  4854. case Builtin::BI__sync_val_compare_and_swap_8:
  4855. case Builtin::BI__sync_val_compare_and_swap_16:
  4856. BuiltinIndex = 12;
  4857. NumFixed = 2;
  4858. break;
  4859. case Builtin::BI__sync_bool_compare_and_swap:
  4860. case Builtin::BI__sync_bool_compare_and_swap_1:
  4861. case Builtin::BI__sync_bool_compare_and_swap_2:
  4862. case Builtin::BI__sync_bool_compare_and_swap_4:
  4863. case Builtin::BI__sync_bool_compare_and_swap_8:
  4864. case Builtin::BI__sync_bool_compare_and_swap_16:
  4865. BuiltinIndex = 13;
  4866. NumFixed = 2;
  4867. ResultType = Context.BoolTy;
  4868. break;
  4869. case Builtin::BI__sync_lock_test_and_set:
  4870. case Builtin::BI__sync_lock_test_and_set_1:
  4871. case Builtin::BI__sync_lock_test_and_set_2:
  4872. case Builtin::BI__sync_lock_test_and_set_4:
  4873. case Builtin::BI__sync_lock_test_and_set_8:
  4874. case Builtin::BI__sync_lock_test_and_set_16:
  4875. BuiltinIndex = 14;
  4876. break;
  4877. case Builtin::BI__sync_lock_release:
  4878. case Builtin::BI__sync_lock_release_1:
  4879. case Builtin::BI__sync_lock_release_2:
  4880. case Builtin::BI__sync_lock_release_4:
  4881. case Builtin::BI__sync_lock_release_8:
  4882. case Builtin::BI__sync_lock_release_16:
  4883. BuiltinIndex = 15;
  4884. NumFixed = 0;
  4885. ResultType = Context.VoidTy;
  4886. break;
  4887. case Builtin::BI__sync_swap:
  4888. case Builtin::BI__sync_swap_1:
  4889. case Builtin::BI__sync_swap_2:
  4890. case Builtin::BI__sync_swap_4:
  4891. case Builtin::BI__sync_swap_8:
  4892. case Builtin::BI__sync_swap_16:
  4893. BuiltinIndex = 16;
  4894. break;
  4895. }
  4896. // Now that we know how many fixed arguments we expect, first check that we
  4897. // have at least that many.
  4898. if (TheCall->getNumArgs() < 1+NumFixed) {
  4899. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4900. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4901. << Callee->getSourceRange();
  4902. return ExprError();
  4903. }
  4904. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4905. << Callee->getSourceRange();
  4906. if (WarnAboutSemanticsChange) {
  4907. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4908. << Callee->getSourceRange();
  4909. }
  4910. // Get the decl for the concrete builtin from this, we can tell what the
  4911. // concrete integer type we should convert to is.
  4912. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4913. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4914. FunctionDecl *NewBuiltinDecl;
  4915. if (NewBuiltinID == BuiltinID)
  4916. NewBuiltinDecl = FDecl;
  4917. else {
  4918. // Perform builtin lookup to avoid redeclaring it.
  4919. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4920. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4921. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4922. assert(Res.getFoundDecl());
  4923. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4924. if (!NewBuiltinDecl)
  4925. return ExprError();
  4926. }
  4927. // The first argument --- the pointer --- has a fixed type; we
  4928. // deduce the types of the rest of the arguments accordingly. Walk
  4929. // the remaining arguments, converting them to the deduced value type.
  4930. for (unsigned i = 0; i != NumFixed; ++i) {
  4931. ExprResult Arg = TheCall->getArg(i+1);
  4932. // GCC does an implicit conversion to the pointer or integer ValType. This
  4933. // can fail in some cases (1i -> int**), check for this error case now.
  4934. // Initialize the argument.
  4935. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4936. ValType, /*consume*/ false);
  4937. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4938. if (Arg.isInvalid())
  4939. return ExprError();
  4940. // Okay, we have something that *can* be converted to the right type. Check
  4941. // to see if there is a potentially weird extension going on here. This can
  4942. // happen when you do an atomic operation on something like an char* and
  4943. // pass in 42. The 42 gets converted to char. This is even more strange
  4944. // for things like 45.123 -> char, etc.
  4945. // FIXME: Do this check.
  4946. TheCall->setArg(i+1, Arg.get());
  4947. }
  4948. // Create a new DeclRefExpr to refer to the new decl.
  4949. DeclRefExpr *NewDRE = DeclRefExpr::Create(
  4950. Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
  4951. /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
  4952. DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
  4953. // Set the callee in the CallExpr.
  4954. // FIXME: This loses syntactic information.
  4955. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4956. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4957. CK_BuiltinFnToFnPtr);
  4958. TheCall->setCallee(PromotedCall.get());
  4959. // Change the result type of the call to match the original value type. This
  4960. // is arbitrary, but the codegen for these builtins ins design to handle it
  4961. // gracefully.
  4962. TheCall->setType(ResultType);
  4963. return TheCallResult;
  4964. }
  4965. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4966. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4967. /// overloaded function based on the pointer type of its last argument.
  4968. ///
  4969. /// This function goes through and does final semantic checking for these
  4970. /// builtins.
  4971. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4972. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4973. DeclRefExpr *DRE =
  4974. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4975. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4976. unsigned BuiltinID = FDecl->getBuiltinID();
  4977. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4978. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4979. "Unexpected nontemporal load/store builtin!");
  4980. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4981. unsigned numArgs = isStore ? 2 : 1;
  4982. // Ensure that we have the proper number of arguments.
  4983. if (checkArgCount(*this, TheCall, numArgs))
  4984. return ExprError();
  4985. // Inspect the last argument of the nontemporal builtin. This should always
  4986. // be a pointer type, from which we imply the type of the memory access.
  4987. // Because it is a pointer type, we don't have to worry about any implicit
  4988. // casts here.
  4989. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4990. ExprResult PointerArgResult =
  4991. DefaultFunctionArrayLvalueConversion(PointerArg);
  4992. if (PointerArgResult.isInvalid())
  4993. return ExprError();
  4994. PointerArg = PointerArgResult.get();
  4995. TheCall->setArg(numArgs - 1, PointerArg);
  4996. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4997. if (!pointerType) {
  4998. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  4999. << PointerArg->getType() << PointerArg->getSourceRange();
  5000. return ExprError();
  5001. }
  5002. QualType ValType = pointerType->getPointeeType();
  5003. // Strip any qualifiers off ValType.
  5004. ValType = ValType.getUnqualifiedType();
  5005. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  5006. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  5007. !ValType->isVectorType()) {
  5008. Diag(DRE->getBeginLoc(),
  5009. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  5010. << PointerArg->getType() << PointerArg->getSourceRange();
  5011. return ExprError();
  5012. }
  5013. if (!isStore) {
  5014. TheCall->setType(ValType);
  5015. return TheCallResult;
  5016. }
  5017. ExprResult ValArg = TheCall->getArg(0);
  5018. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5019. Context, ValType, /*consume*/ false);
  5020. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  5021. if (ValArg.isInvalid())
  5022. return ExprError();
  5023. TheCall->setArg(0, ValArg.get());
  5024. TheCall->setType(Context.VoidTy);
  5025. return TheCallResult;
  5026. }
  5027. /// CheckObjCString - Checks that the argument to the builtin
  5028. /// CFString constructor is correct
  5029. /// Note: It might also make sense to do the UTF-16 conversion here (would
  5030. /// simplify the backend).
  5031. bool Sema::CheckObjCString(Expr *Arg) {
  5032. Arg = Arg->IgnoreParenCasts();
  5033. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  5034. if (!Literal || !Literal->isAscii()) {
  5035. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  5036. << Arg->getSourceRange();
  5037. return true;
  5038. }
  5039. if (Literal->containsNonAsciiOrNull()) {
  5040. StringRef String = Literal->getString();
  5041. unsigned NumBytes = String.size();
  5042. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  5043. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  5044. llvm::UTF16 *ToPtr = &ToBuf[0];
  5045. llvm::ConversionResult Result =
  5046. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  5047. ToPtr + NumBytes, llvm::strictConversion);
  5048. // Check for conversion failure.
  5049. if (Result != llvm::conversionOK)
  5050. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  5051. << Arg->getSourceRange();
  5052. }
  5053. return false;
  5054. }
  5055. /// CheckObjCString - Checks that the format string argument to the os_log()
  5056. /// and os_trace() functions is correct, and converts it to const char *.
  5057. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  5058. Arg = Arg->IgnoreParenCasts();
  5059. auto *Literal = dyn_cast<StringLiteral>(Arg);
  5060. if (!Literal) {
  5061. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  5062. Literal = ObjcLiteral->getString();
  5063. }
  5064. }
  5065. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  5066. return ExprError(
  5067. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  5068. << Arg->getSourceRange());
  5069. }
  5070. ExprResult Result(Literal);
  5071. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  5072. InitializedEntity Entity =
  5073. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  5074. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  5075. return Result;
  5076. }
  5077. /// Check that the user is calling the appropriate va_start builtin for the
  5078. /// target and calling convention.
  5079. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  5080. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  5081. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  5082. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  5083. bool IsWindows = TT.isOSWindows();
  5084. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  5085. if (IsX64 || IsAArch64) {
  5086. CallingConv CC = CC_C;
  5087. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  5088. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  5089. if (IsMSVAStart) {
  5090. // Don't allow this in System V ABI functions.
  5091. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  5092. return S.Diag(Fn->getBeginLoc(),
  5093. diag::err_ms_va_start_used_in_sysv_function);
  5094. } else {
  5095. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  5096. // On x64 Windows, don't allow this in System V ABI functions.
  5097. // (Yes, that means there's no corresponding way to support variadic
  5098. // System V ABI functions on Windows.)
  5099. if ((IsWindows && CC == CC_X86_64SysV) ||
  5100. (!IsWindows && CC == CC_Win64))
  5101. return S.Diag(Fn->getBeginLoc(),
  5102. diag::err_va_start_used_in_wrong_abi_function)
  5103. << !IsWindows;
  5104. }
  5105. return false;
  5106. }
  5107. if (IsMSVAStart)
  5108. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  5109. return false;
  5110. }
  5111. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  5112. ParmVarDecl **LastParam = nullptr) {
  5113. // Determine whether the current function, block, or obj-c method is variadic
  5114. // and get its parameter list.
  5115. bool IsVariadic = false;
  5116. ArrayRef<ParmVarDecl *> Params;
  5117. DeclContext *Caller = S.CurContext;
  5118. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  5119. IsVariadic = Block->isVariadic();
  5120. Params = Block->parameters();
  5121. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  5122. IsVariadic = FD->isVariadic();
  5123. Params = FD->parameters();
  5124. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  5125. IsVariadic = MD->isVariadic();
  5126. // FIXME: This isn't correct for methods (results in bogus warning).
  5127. Params = MD->parameters();
  5128. } else if (isa<CapturedDecl>(Caller)) {
  5129. // We don't support va_start in a CapturedDecl.
  5130. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  5131. return true;
  5132. } else {
  5133. // This must be some other declcontext that parses exprs.
  5134. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  5135. return true;
  5136. }
  5137. if (!IsVariadic) {
  5138. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  5139. return true;
  5140. }
  5141. if (LastParam)
  5142. *LastParam = Params.empty() ? nullptr : Params.back();
  5143. return false;
  5144. }
  5145. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  5146. /// for validity. Emit an error and return true on failure; return false
  5147. /// on success.
  5148. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  5149. Expr *Fn = TheCall->getCallee();
  5150. if (checkVAStartABI(*this, BuiltinID, Fn))
  5151. return true;
  5152. if (TheCall->getNumArgs() > 2) {
  5153. Diag(TheCall->getArg(2)->getBeginLoc(),
  5154. diag::err_typecheck_call_too_many_args)
  5155. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5156. << Fn->getSourceRange()
  5157. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5158. (*(TheCall->arg_end() - 1))->getEndLoc());
  5159. return true;
  5160. }
  5161. if (TheCall->getNumArgs() < 2) {
  5162. return Diag(TheCall->getEndLoc(),
  5163. diag::err_typecheck_call_too_few_args_at_least)
  5164. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  5165. }
  5166. // Type-check the first argument normally.
  5167. if (checkBuiltinArgument(*this, TheCall, 0))
  5168. return true;
  5169. // Check that the current function is variadic, and get its last parameter.
  5170. ParmVarDecl *LastParam;
  5171. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  5172. return true;
  5173. // Verify that the second argument to the builtin is the last argument of the
  5174. // current function or method.
  5175. bool SecondArgIsLastNamedArgument = false;
  5176. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  5177. // These are valid if SecondArgIsLastNamedArgument is false after the next
  5178. // block.
  5179. QualType Type;
  5180. SourceLocation ParamLoc;
  5181. bool IsCRegister = false;
  5182. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  5183. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  5184. SecondArgIsLastNamedArgument = PV == LastParam;
  5185. Type = PV->getType();
  5186. ParamLoc = PV->getLocation();
  5187. IsCRegister =
  5188. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  5189. }
  5190. }
  5191. if (!SecondArgIsLastNamedArgument)
  5192. Diag(TheCall->getArg(1)->getBeginLoc(),
  5193. diag::warn_second_arg_of_va_start_not_last_named_param);
  5194. else if (IsCRegister || Type->isReferenceType() ||
  5195. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  5196. // Promotable integers are UB, but enumerations need a bit of
  5197. // extra checking to see what their promotable type actually is.
  5198. if (!Type->isPromotableIntegerType())
  5199. return false;
  5200. if (!Type->isEnumeralType())
  5201. return true;
  5202. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  5203. return !(ED &&
  5204. Context.typesAreCompatible(ED->getPromotionType(), Type));
  5205. }()) {
  5206. unsigned Reason = 0;
  5207. if (Type->isReferenceType()) Reason = 1;
  5208. else if (IsCRegister) Reason = 2;
  5209. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  5210. Diag(ParamLoc, diag::note_parameter_type) << Type;
  5211. }
  5212. TheCall->setType(Context.VoidTy);
  5213. return false;
  5214. }
  5215. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  5216. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5217. // const char *named_addr);
  5218. Expr *Func = Call->getCallee();
  5219. if (Call->getNumArgs() < 3)
  5220. return Diag(Call->getEndLoc(),
  5221. diag::err_typecheck_call_too_few_args_at_least)
  5222. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5223. // Type-check the first argument normally.
  5224. if (checkBuiltinArgument(*this, Call, 0))
  5225. return true;
  5226. // Check that the current function is variadic.
  5227. if (checkVAStartIsInVariadicFunction(*this, Func))
  5228. return true;
  5229. // __va_start on Windows does not validate the parameter qualifiers
  5230. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5231. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5232. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5233. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5234. const QualType &ConstCharPtrTy =
  5235. Context.getPointerType(Context.CharTy.withConst());
  5236. if (!Arg1Ty->isPointerType() ||
  5237. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5238. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5239. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5240. << 0 /* qualifier difference */
  5241. << 3 /* parameter mismatch */
  5242. << 2 << Arg1->getType() << ConstCharPtrTy;
  5243. const QualType SizeTy = Context.getSizeType();
  5244. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5245. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5246. << Arg2->getType() << SizeTy << 1 /* different class */
  5247. << 0 /* qualifier difference */
  5248. << 3 /* parameter mismatch */
  5249. << 3 << Arg2->getType() << SizeTy;
  5250. return false;
  5251. }
  5252. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5253. /// friends. This is declared to take (...), so we have to check everything.
  5254. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5255. if (TheCall->getNumArgs() < 2)
  5256. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5257. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5258. if (TheCall->getNumArgs() > 2)
  5259. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5260. diag::err_typecheck_call_too_many_args)
  5261. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5262. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5263. (*(TheCall->arg_end() - 1))->getEndLoc());
  5264. ExprResult OrigArg0 = TheCall->getArg(0);
  5265. ExprResult OrigArg1 = TheCall->getArg(1);
  5266. // Do standard promotions between the two arguments, returning their common
  5267. // type.
  5268. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5269. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5270. return true;
  5271. // Make sure any conversions are pushed back into the call; this is
  5272. // type safe since unordered compare builtins are declared as "_Bool
  5273. // foo(...)".
  5274. TheCall->setArg(0, OrigArg0.get());
  5275. TheCall->setArg(1, OrigArg1.get());
  5276. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5277. return false;
  5278. // If the common type isn't a real floating type, then the arguments were
  5279. // invalid for this operation.
  5280. if (Res.isNull() || !Res->isRealFloatingType())
  5281. return Diag(OrigArg0.get()->getBeginLoc(),
  5282. diag::err_typecheck_call_invalid_ordered_compare)
  5283. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5284. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5285. OrigArg1.get()->getEndLoc());
  5286. return false;
  5287. }
  5288. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5289. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5290. /// to check everything. We expect the last argument to be a floating point
  5291. /// value.
  5292. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5293. if (TheCall->getNumArgs() < NumArgs)
  5294. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5295. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5296. if (TheCall->getNumArgs() > NumArgs)
  5297. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5298. diag::err_typecheck_call_too_many_args)
  5299. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5300. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5301. (*(TheCall->arg_end() - 1))->getEndLoc());
  5302. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5303. if (OrigArg->isTypeDependent())
  5304. return false;
  5305. // This operation requires a non-_Complex floating-point number.
  5306. if (!OrigArg->getType()->isRealFloatingType())
  5307. return Diag(OrigArg->getBeginLoc(),
  5308. diag::err_typecheck_call_invalid_unary_fp)
  5309. << OrigArg->getType() << OrigArg->getSourceRange();
  5310. // If this is an implicit conversion from float -> float, double, or
  5311. // long double, remove it.
  5312. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5313. // Only remove standard FloatCasts, leaving other casts inplace
  5314. if (Cast->getCastKind() == CK_FloatingCast) {
  5315. Expr *CastArg = Cast->getSubExpr();
  5316. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5317. assert(
  5318. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5319. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5320. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5321. "promotion from float to either float, double, or long double is "
  5322. "the only expected cast here");
  5323. Cast->setSubExpr(nullptr);
  5324. TheCall->setArg(NumArgs-1, CastArg);
  5325. }
  5326. }
  5327. }
  5328. return false;
  5329. }
  5330. // Customized Sema Checking for VSX builtins that have the following signature:
  5331. // vector [...] builtinName(vector [...], vector [...], const int);
  5332. // Which takes the same type of vectors (any legal vector type) for the first
  5333. // two arguments and takes compile time constant for the third argument.
  5334. // Example builtins are :
  5335. // vector double vec_xxpermdi(vector double, vector double, int);
  5336. // vector short vec_xxsldwi(vector short, vector short, int);
  5337. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5338. unsigned ExpectedNumArgs = 3;
  5339. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5340. return Diag(TheCall->getEndLoc(),
  5341. diag::err_typecheck_call_too_few_args_at_least)
  5342. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5343. << TheCall->getSourceRange();
  5344. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5345. return Diag(TheCall->getEndLoc(),
  5346. diag::err_typecheck_call_too_many_args_at_most)
  5347. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5348. << TheCall->getSourceRange();
  5349. // Check the third argument is a compile time constant
  5350. llvm::APSInt Value;
  5351. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5352. return Diag(TheCall->getBeginLoc(),
  5353. diag::err_vsx_builtin_nonconstant_argument)
  5354. << 3 /* argument index */ << TheCall->getDirectCallee()
  5355. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5356. TheCall->getArg(2)->getEndLoc());
  5357. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5358. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5359. // Check the type of argument 1 and argument 2 are vectors.
  5360. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5361. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5362. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5363. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5364. << TheCall->getDirectCallee()
  5365. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5366. TheCall->getArg(1)->getEndLoc());
  5367. }
  5368. // Check the first two arguments are the same type.
  5369. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5370. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5371. << TheCall->getDirectCallee()
  5372. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5373. TheCall->getArg(1)->getEndLoc());
  5374. }
  5375. // When default clang type checking is turned off and the customized type
  5376. // checking is used, the returning type of the function must be explicitly
  5377. // set. Otherwise it is _Bool by default.
  5378. TheCall->setType(Arg1Ty);
  5379. return false;
  5380. }
  5381. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5382. // This is declared to take (...), so we have to check everything.
  5383. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5384. if (TheCall->getNumArgs() < 2)
  5385. return ExprError(Diag(TheCall->getEndLoc(),
  5386. diag::err_typecheck_call_too_few_args_at_least)
  5387. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5388. << TheCall->getSourceRange());
  5389. // Determine which of the following types of shufflevector we're checking:
  5390. // 1) unary, vector mask: (lhs, mask)
  5391. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5392. QualType resType = TheCall->getArg(0)->getType();
  5393. unsigned numElements = 0;
  5394. if (!TheCall->getArg(0)->isTypeDependent() &&
  5395. !TheCall->getArg(1)->isTypeDependent()) {
  5396. QualType LHSType = TheCall->getArg(0)->getType();
  5397. QualType RHSType = TheCall->getArg(1)->getType();
  5398. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5399. return ExprError(
  5400. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5401. << TheCall->getDirectCallee()
  5402. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5403. TheCall->getArg(1)->getEndLoc()));
  5404. numElements = LHSType->castAs<VectorType>()->getNumElements();
  5405. unsigned numResElements = TheCall->getNumArgs() - 2;
  5406. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5407. // with mask. If so, verify that RHS is an integer vector type with the
  5408. // same number of elts as lhs.
  5409. if (TheCall->getNumArgs() == 2) {
  5410. if (!RHSType->hasIntegerRepresentation() ||
  5411. RHSType->castAs<VectorType>()->getNumElements() != numElements)
  5412. return ExprError(Diag(TheCall->getBeginLoc(),
  5413. diag::err_vec_builtin_incompatible_vector)
  5414. << TheCall->getDirectCallee()
  5415. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5416. TheCall->getArg(1)->getEndLoc()));
  5417. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5418. return ExprError(Diag(TheCall->getBeginLoc(),
  5419. diag::err_vec_builtin_incompatible_vector)
  5420. << TheCall->getDirectCallee()
  5421. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5422. TheCall->getArg(1)->getEndLoc()));
  5423. } else if (numElements != numResElements) {
  5424. QualType eltType = LHSType->castAs<VectorType>()->getElementType();
  5425. resType = Context.getVectorType(eltType, numResElements,
  5426. VectorType::GenericVector);
  5427. }
  5428. }
  5429. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5430. if (TheCall->getArg(i)->isTypeDependent() ||
  5431. TheCall->getArg(i)->isValueDependent())
  5432. continue;
  5433. llvm::APSInt Result(32);
  5434. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5435. return ExprError(Diag(TheCall->getBeginLoc(),
  5436. diag::err_shufflevector_nonconstant_argument)
  5437. << TheCall->getArg(i)->getSourceRange());
  5438. // Allow -1 which will be translated to undef in the IR.
  5439. if (Result.isSigned() && Result.isAllOnesValue())
  5440. continue;
  5441. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5442. return ExprError(Diag(TheCall->getBeginLoc(),
  5443. diag::err_shufflevector_argument_too_large)
  5444. << TheCall->getArg(i)->getSourceRange());
  5445. }
  5446. SmallVector<Expr*, 32> exprs;
  5447. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5448. exprs.push_back(TheCall->getArg(i));
  5449. TheCall->setArg(i, nullptr);
  5450. }
  5451. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5452. TheCall->getCallee()->getBeginLoc(),
  5453. TheCall->getRParenLoc());
  5454. }
  5455. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5456. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5457. SourceLocation BuiltinLoc,
  5458. SourceLocation RParenLoc) {
  5459. ExprValueKind VK = VK_RValue;
  5460. ExprObjectKind OK = OK_Ordinary;
  5461. QualType DstTy = TInfo->getType();
  5462. QualType SrcTy = E->getType();
  5463. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5464. return ExprError(Diag(BuiltinLoc,
  5465. diag::err_convertvector_non_vector)
  5466. << E->getSourceRange());
  5467. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5468. return ExprError(Diag(BuiltinLoc,
  5469. diag::err_convertvector_non_vector_type));
  5470. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5471. unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
  5472. unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
  5473. if (SrcElts != DstElts)
  5474. return ExprError(Diag(BuiltinLoc,
  5475. diag::err_convertvector_incompatible_vector)
  5476. << E->getSourceRange());
  5477. }
  5478. return new (Context)
  5479. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5480. }
  5481. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5482. // This is declared to take (const void*, ...) and can take two
  5483. // optional constant int args.
  5484. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5485. unsigned NumArgs = TheCall->getNumArgs();
  5486. if (NumArgs > 3)
  5487. return Diag(TheCall->getEndLoc(),
  5488. diag::err_typecheck_call_too_many_args_at_most)
  5489. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5490. // Argument 0 is checked for us and the remaining arguments must be
  5491. // constant integers.
  5492. for (unsigned i = 1; i != NumArgs; ++i)
  5493. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5494. return true;
  5495. return false;
  5496. }
  5497. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5498. // __assume does not evaluate its arguments, and should warn if its argument
  5499. // has side effects.
  5500. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5501. Expr *Arg = TheCall->getArg(0);
  5502. if (Arg->isInstantiationDependent()) return false;
  5503. if (Arg->HasSideEffects(Context))
  5504. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5505. << Arg->getSourceRange()
  5506. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5507. return false;
  5508. }
  5509. /// Handle __builtin_alloca_with_align. This is declared
  5510. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5511. /// than 8.
  5512. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5513. // The alignment must be a constant integer.
  5514. Expr *Arg = TheCall->getArg(1);
  5515. // We can't check the value of a dependent argument.
  5516. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5517. if (const auto *UE =
  5518. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5519. if (UE->getKind() == UETT_AlignOf ||
  5520. UE->getKind() == UETT_PreferredAlignOf)
  5521. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5522. << Arg->getSourceRange();
  5523. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5524. if (!Result.isPowerOf2())
  5525. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5526. << Arg->getSourceRange();
  5527. if (Result < Context.getCharWidth())
  5528. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5529. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5530. if (Result > std::numeric_limits<int32_t>::max())
  5531. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5532. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5533. }
  5534. return false;
  5535. }
  5536. /// Handle __builtin_assume_aligned. This is declared
  5537. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5538. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5539. unsigned NumArgs = TheCall->getNumArgs();
  5540. if (NumArgs > 3)
  5541. return Diag(TheCall->getEndLoc(),
  5542. diag::err_typecheck_call_too_many_args_at_most)
  5543. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5544. // The alignment must be a constant integer.
  5545. Expr *Arg = TheCall->getArg(1);
  5546. // We can't check the value of a dependent argument.
  5547. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5548. llvm::APSInt Result;
  5549. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5550. return true;
  5551. if (!Result.isPowerOf2())
  5552. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5553. << Arg->getSourceRange();
  5554. }
  5555. if (NumArgs > 2) {
  5556. ExprResult Arg(TheCall->getArg(2));
  5557. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5558. Context.getSizeType(), false);
  5559. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5560. if (Arg.isInvalid()) return true;
  5561. TheCall->setArg(2, Arg.get());
  5562. }
  5563. return false;
  5564. }
  5565. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5566. unsigned BuiltinID =
  5567. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5568. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5569. unsigned NumArgs = TheCall->getNumArgs();
  5570. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5571. if (NumArgs < NumRequiredArgs) {
  5572. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5573. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5574. << TheCall->getSourceRange();
  5575. }
  5576. if (NumArgs >= NumRequiredArgs + 0x100) {
  5577. return Diag(TheCall->getEndLoc(),
  5578. diag::err_typecheck_call_too_many_args_at_most)
  5579. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5580. << TheCall->getSourceRange();
  5581. }
  5582. unsigned i = 0;
  5583. // For formatting call, check buffer arg.
  5584. if (!IsSizeCall) {
  5585. ExprResult Arg(TheCall->getArg(i));
  5586. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5587. Context, Context.VoidPtrTy, false);
  5588. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5589. if (Arg.isInvalid())
  5590. return true;
  5591. TheCall->setArg(i, Arg.get());
  5592. i++;
  5593. }
  5594. // Check string literal arg.
  5595. unsigned FormatIdx = i;
  5596. {
  5597. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5598. if (Arg.isInvalid())
  5599. return true;
  5600. TheCall->setArg(i, Arg.get());
  5601. i++;
  5602. }
  5603. // Make sure variadic args are scalar.
  5604. unsigned FirstDataArg = i;
  5605. while (i < NumArgs) {
  5606. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5607. TheCall->getArg(i), VariadicFunction, nullptr);
  5608. if (Arg.isInvalid())
  5609. return true;
  5610. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5611. if (ArgSize.getQuantity() >= 0x100) {
  5612. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5613. << i << (int)ArgSize.getQuantity() << 0xff
  5614. << TheCall->getSourceRange();
  5615. }
  5616. TheCall->setArg(i, Arg.get());
  5617. i++;
  5618. }
  5619. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5620. // call to avoid duplicate diagnostics.
  5621. if (!IsSizeCall) {
  5622. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5623. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5624. bool Success = CheckFormatArguments(
  5625. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5626. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5627. CheckedVarArgs);
  5628. if (!Success)
  5629. return true;
  5630. }
  5631. if (IsSizeCall) {
  5632. TheCall->setType(Context.getSizeType());
  5633. } else {
  5634. TheCall->setType(Context.VoidPtrTy);
  5635. }
  5636. return false;
  5637. }
  5638. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5639. /// TheCall is a constant expression.
  5640. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5641. llvm::APSInt &Result) {
  5642. Expr *Arg = TheCall->getArg(ArgNum);
  5643. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5644. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5645. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5646. if (!Arg->isIntegerConstantExpr(Result, Context))
  5647. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5648. << FDecl->getDeclName() << Arg->getSourceRange();
  5649. return false;
  5650. }
  5651. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5652. /// TheCall is a constant expression in the range [Low, High].
  5653. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5654. int Low, int High, bool RangeIsError) {
  5655. if (isConstantEvaluated())
  5656. return false;
  5657. llvm::APSInt Result;
  5658. // We can't check the value of a dependent argument.
  5659. Expr *Arg = TheCall->getArg(ArgNum);
  5660. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5661. return false;
  5662. // Check constant-ness first.
  5663. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5664. return true;
  5665. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5666. if (RangeIsError)
  5667. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5668. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5669. else
  5670. // Defer the warning until we know if the code will be emitted so that
  5671. // dead code can ignore this.
  5672. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5673. PDiag(diag::warn_argument_invalid_range)
  5674. << Result.toString(10) << Low << High
  5675. << Arg->getSourceRange());
  5676. }
  5677. return false;
  5678. }
  5679. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5680. /// TheCall is a constant expression is a multiple of Num..
  5681. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5682. unsigned Num) {
  5683. llvm::APSInt Result;
  5684. // We can't check the value of a dependent argument.
  5685. Expr *Arg = TheCall->getArg(ArgNum);
  5686. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5687. return false;
  5688. // Check constant-ness first.
  5689. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5690. return true;
  5691. if (Result.getSExtValue() % Num != 0)
  5692. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5693. << Num << Arg->getSourceRange();
  5694. return false;
  5695. }
  5696. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  5697. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  5698. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  5699. if (checkArgCount(*this, TheCall, 2))
  5700. return true;
  5701. Expr *Arg0 = TheCall->getArg(0);
  5702. Expr *Arg1 = TheCall->getArg(1);
  5703. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5704. if (FirstArg.isInvalid())
  5705. return true;
  5706. QualType FirstArgType = FirstArg.get()->getType();
  5707. if (!FirstArgType->isAnyPointerType())
  5708. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5709. << "first" << FirstArgType << Arg0->getSourceRange();
  5710. TheCall->setArg(0, FirstArg.get());
  5711. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  5712. if (SecArg.isInvalid())
  5713. return true;
  5714. QualType SecArgType = SecArg.get()->getType();
  5715. if (!SecArgType->isIntegerType())
  5716. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5717. << "second" << SecArgType << Arg1->getSourceRange();
  5718. // Derive the return type from the pointer argument.
  5719. TheCall->setType(FirstArgType);
  5720. return false;
  5721. }
  5722. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  5723. if (checkArgCount(*this, TheCall, 2))
  5724. return true;
  5725. Expr *Arg0 = TheCall->getArg(0);
  5726. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5727. if (FirstArg.isInvalid())
  5728. return true;
  5729. QualType FirstArgType = FirstArg.get()->getType();
  5730. if (!FirstArgType->isAnyPointerType())
  5731. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5732. << "first" << FirstArgType << Arg0->getSourceRange();
  5733. TheCall->setArg(0, FirstArg.get());
  5734. // Derive the return type from the pointer argument.
  5735. TheCall->setType(FirstArgType);
  5736. // Second arg must be an constant in range [0,15]
  5737. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5738. }
  5739. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  5740. if (checkArgCount(*this, TheCall, 2))
  5741. return true;
  5742. Expr *Arg0 = TheCall->getArg(0);
  5743. Expr *Arg1 = TheCall->getArg(1);
  5744. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5745. if (FirstArg.isInvalid())
  5746. return true;
  5747. QualType FirstArgType = FirstArg.get()->getType();
  5748. if (!FirstArgType->isAnyPointerType())
  5749. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5750. << "first" << FirstArgType << Arg0->getSourceRange();
  5751. QualType SecArgType = Arg1->getType();
  5752. if (!SecArgType->isIntegerType())
  5753. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5754. << "second" << SecArgType << Arg1->getSourceRange();
  5755. TheCall->setType(Context.IntTy);
  5756. return false;
  5757. }
  5758. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  5759. BuiltinID == AArch64::BI__builtin_arm_stg) {
  5760. if (checkArgCount(*this, TheCall, 1))
  5761. return true;
  5762. Expr *Arg0 = TheCall->getArg(0);
  5763. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5764. if (FirstArg.isInvalid())
  5765. return true;
  5766. QualType FirstArgType = FirstArg.get()->getType();
  5767. if (!FirstArgType->isAnyPointerType())
  5768. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5769. << "first" << FirstArgType << Arg0->getSourceRange();
  5770. TheCall->setArg(0, FirstArg.get());
  5771. // Derive the return type from the pointer argument.
  5772. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  5773. TheCall->setType(FirstArgType);
  5774. return false;
  5775. }
  5776. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  5777. Expr *ArgA = TheCall->getArg(0);
  5778. Expr *ArgB = TheCall->getArg(1);
  5779. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  5780. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  5781. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  5782. return true;
  5783. QualType ArgTypeA = ArgExprA.get()->getType();
  5784. QualType ArgTypeB = ArgExprB.get()->getType();
  5785. auto isNull = [&] (Expr *E) -> bool {
  5786. return E->isNullPointerConstant(
  5787. Context, Expr::NPC_ValueDependentIsNotNull); };
  5788. // argument should be either a pointer or null
  5789. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  5790. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5791. << "first" << ArgTypeA << ArgA->getSourceRange();
  5792. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  5793. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5794. << "second" << ArgTypeB << ArgB->getSourceRange();
  5795. // Ensure Pointee types are compatible
  5796. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  5797. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  5798. QualType pointeeA = ArgTypeA->getPointeeType();
  5799. QualType pointeeB = ArgTypeB->getPointeeType();
  5800. if (!Context.typesAreCompatible(
  5801. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  5802. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  5803. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  5804. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  5805. << ArgB->getSourceRange();
  5806. }
  5807. }
  5808. // at least one argument should be pointer type
  5809. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  5810. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  5811. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  5812. if (isNull(ArgA)) // adopt type of the other pointer
  5813. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  5814. if (isNull(ArgB))
  5815. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  5816. TheCall->setArg(0, ArgExprA.get());
  5817. TheCall->setArg(1, ArgExprB.get());
  5818. TheCall->setType(Context.LongLongTy);
  5819. return false;
  5820. }
  5821. assert(false && "Unhandled ARM MTE intrinsic");
  5822. return true;
  5823. }
  5824. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5825. /// TheCall is an ARM/AArch64 special register string literal.
  5826. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5827. int ArgNum, unsigned ExpectedFieldNum,
  5828. bool AllowName) {
  5829. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5830. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5831. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5832. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5833. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5834. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5835. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5836. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5837. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5838. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5839. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5840. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5841. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5842. // We can't check the value of a dependent argument.
  5843. Expr *Arg = TheCall->getArg(ArgNum);
  5844. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5845. return false;
  5846. // Check if the argument is a string literal.
  5847. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5848. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5849. << Arg->getSourceRange();
  5850. // Check the type of special register given.
  5851. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5852. SmallVector<StringRef, 6> Fields;
  5853. Reg.split(Fields, ":");
  5854. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5855. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5856. << Arg->getSourceRange();
  5857. // If the string is the name of a register then we cannot check that it is
  5858. // valid here but if the string is of one the forms described in ACLE then we
  5859. // can check that the supplied fields are integers and within the valid
  5860. // ranges.
  5861. if (Fields.size() > 1) {
  5862. bool FiveFields = Fields.size() == 5;
  5863. bool ValidString = true;
  5864. if (IsARMBuiltin) {
  5865. ValidString &= Fields[0].startswith_lower("cp") ||
  5866. Fields[0].startswith_lower("p");
  5867. if (ValidString)
  5868. Fields[0] =
  5869. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5870. ValidString &= Fields[2].startswith_lower("c");
  5871. if (ValidString)
  5872. Fields[2] = Fields[2].drop_front(1);
  5873. if (FiveFields) {
  5874. ValidString &= Fields[3].startswith_lower("c");
  5875. if (ValidString)
  5876. Fields[3] = Fields[3].drop_front(1);
  5877. }
  5878. }
  5879. SmallVector<int, 5> Ranges;
  5880. if (FiveFields)
  5881. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5882. else
  5883. Ranges.append({15, 7, 15});
  5884. for (unsigned i=0; i<Fields.size(); ++i) {
  5885. int IntField;
  5886. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5887. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5888. }
  5889. if (!ValidString)
  5890. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5891. << Arg->getSourceRange();
  5892. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5893. // If the register name is one of those that appear in the condition below
  5894. // and the special register builtin being used is one of the write builtins,
  5895. // then we require that the argument provided for writing to the register
  5896. // is an integer constant expression. This is because it will be lowered to
  5897. // an MSR (immediate) instruction, so we need to know the immediate at
  5898. // compile time.
  5899. if (TheCall->getNumArgs() != 2)
  5900. return false;
  5901. std::string RegLower = Reg.lower();
  5902. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5903. RegLower != "pan" && RegLower != "uao")
  5904. return false;
  5905. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5906. }
  5907. return false;
  5908. }
  5909. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5910. /// This checks that the target supports __builtin_longjmp and
  5911. /// that val is a constant 1.
  5912. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5913. if (!Context.getTargetInfo().hasSjLjLowering())
  5914. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5915. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5916. Expr *Arg = TheCall->getArg(1);
  5917. llvm::APSInt Result;
  5918. // TODO: This is less than ideal. Overload this to take a value.
  5919. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5920. return true;
  5921. if (Result != 1)
  5922. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5923. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5924. return false;
  5925. }
  5926. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5927. /// This checks that the target supports __builtin_setjmp.
  5928. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5929. if (!Context.getTargetInfo().hasSjLjLowering())
  5930. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5931. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5932. return false;
  5933. }
  5934. namespace {
  5935. class UncoveredArgHandler {
  5936. enum { Unknown = -1, AllCovered = -2 };
  5937. signed FirstUncoveredArg = Unknown;
  5938. SmallVector<const Expr *, 4> DiagnosticExprs;
  5939. public:
  5940. UncoveredArgHandler() = default;
  5941. bool hasUncoveredArg() const {
  5942. return (FirstUncoveredArg >= 0);
  5943. }
  5944. unsigned getUncoveredArg() const {
  5945. assert(hasUncoveredArg() && "no uncovered argument");
  5946. return FirstUncoveredArg;
  5947. }
  5948. void setAllCovered() {
  5949. // A string has been found with all arguments covered, so clear out
  5950. // the diagnostics.
  5951. DiagnosticExprs.clear();
  5952. FirstUncoveredArg = AllCovered;
  5953. }
  5954. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5955. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5956. // Don't update if a previous string covers all arguments.
  5957. if (FirstUncoveredArg == AllCovered)
  5958. return;
  5959. // UncoveredArgHandler tracks the highest uncovered argument index
  5960. // and with it all the strings that match this index.
  5961. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5962. DiagnosticExprs.push_back(StrExpr);
  5963. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5964. DiagnosticExprs.clear();
  5965. DiagnosticExprs.push_back(StrExpr);
  5966. FirstUncoveredArg = NewFirstUncoveredArg;
  5967. }
  5968. }
  5969. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5970. };
  5971. enum StringLiteralCheckType {
  5972. SLCT_NotALiteral,
  5973. SLCT_UncheckedLiteral,
  5974. SLCT_CheckedLiteral
  5975. };
  5976. } // namespace
  5977. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5978. BinaryOperatorKind BinOpKind,
  5979. bool AddendIsRight) {
  5980. unsigned BitWidth = Offset.getBitWidth();
  5981. unsigned AddendBitWidth = Addend.getBitWidth();
  5982. // There might be negative interim results.
  5983. if (Addend.isUnsigned()) {
  5984. Addend = Addend.zext(++AddendBitWidth);
  5985. Addend.setIsSigned(true);
  5986. }
  5987. // Adjust the bit width of the APSInts.
  5988. if (AddendBitWidth > BitWidth) {
  5989. Offset = Offset.sext(AddendBitWidth);
  5990. BitWidth = AddendBitWidth;
  5991. } else if (BitWidth > AddendBitWidth) {
  5992. Addend = Addend.sext(BitWidth);
  5993. }
  5994. bool Ov = false;
  5995. llvm::APSInt ResOffset = Offset;
  5996. if (BinOpKind == BO_Add)
  5997. ResOffset = Offset.sadd_ov(Addend, Ov);
  5998. else {
  5999. assert(AddendIsRight && BinOpKind == BO_Sub &&
  6000. "operator must be add or sub with addend on the right");
  6001. ResOffset = Offset.ssub_ov(Addend, Ov);
  6002. }
  6003. // We add an offset to a pointer here so we should support an offset as big as
  6004. // possible.
  6005. if (Ov) {
  6006. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  6007. "index (intermediate) result too big");
  6008. Offset = Offset.sext(2 * BitWidth);
  6009. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  6010. return;
  6011. }
  6012. Offset = ResOffset;
  6013. }
  6014. namespace {
  6015. // This is a wrapper class around StringLiteral to support offsetted string
  6016. // literals as format strings. It takes the offset into account when returning
  6017. // the string and its length or the source locations to display notes correctly.
  6018. class FormatStringLiteral {
  6019. const StringLiteral *FExpr;
  6020. int64_t Offset;
  6021. public:
  6022. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  6023. : FExpr(fexpr), Offset(Offset) {}
  6024. StringRef getString() const {
  6025. return FExpr->getString().drop_front(Offset);
  6026. }
  6027. unsigned getByteLength() const {
  6028. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  6029. }
  6030. unsigned getLength() const { return FExpr->getLength() - Offset; }
  6031. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  6032. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  6033. QualType getType() const { return FExpr->getType(); }
  6034. bool isAscii() const { return FExpr->isAscii(); }
  6035. bool isWide() const { return FExpr->isWide(); }
  6036. bool isUTF8() const { return FExpr->isUTF8(); }
  6037. bool isUTF16() const { return FExpr->isUTF16(); }
  6038. bool isUTF32() const { return FExpr->isUTF32(); }
  6039. bool isPascal() const { return FExpr->isPascal(); }
  6040. SourceLocation getLocationOfByte(
  6041. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  6042. const TargetInfo &Target, unsigned *StartToken = nullptr,
  6043. unsigned *StartTokenByteOffset = nullptr) const {
  6044. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  6045. StartToken, StartTokenByteOffset);
  6046. }
  6047. SourceLocation getBeginLoc() const LLVM_READONLY {
  6048. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  6049. }
  6050. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  6051. };
  6052. } // namespace
  6053. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  6054. const Expr *OrigFormatExpr,
  6055. ArrayRef<const Expr *> Args,
  6056. bool HasVAListArg, unsigned format_idx,
  6057. unsigned firstDataArg,
  6058. Sema::FormatStringType Type,
  6059. bool inFunctionCall,
  6060. Sema::VariadicCallType CallType,
  6061. llvm::SmallBitVector &CheckedVarArgs,
  6062. UncoveredArgHandler &UncoveredArg,
  6063. bool IgnoreStringsWithoutSpecifiers);
  6064. // Determine if an expression is a string literal or constant string.
  6065. // If this function returns false on the arguments to a function expecting a
  6066. // format string, we will usually need to emit a warning.
  6067. // True string literals are then checked by CheckFormatString.
  6068. static StringLiteralCheckType
  6069. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  6070. bool HasVAListArg, unsigned format_idx,
  6071. unsigned firstDataArg, Sema::FormatStringType Type,
  6072. Sema::VariadicCallType CallType, bool InFunctionCall,
  6073. llvm::SmallBitVector &CheckedVarArgs,
  6074. UncoveredArgHandler &UncoveredArg,
  6075. llvm::APSInt Offset,
  6076. bool IgnoreStringsWithoutSpecifiers = false) {
  6077. if (S.isConstantEvaluated())
  6078. return SLCT_NotALiteral;
  6079. tryAgain:
  6080. assert(Offset.isSigned() && "invalid offset");
  6081. if (E->isTypeDependent() || E->isValueDependent())
  6082. return SLCT_NotALiteral;
  6083. E = E->IgnoreParenCasts();
  6084. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  6085. // Technically -Wformat-nonliteral does not warn about this case.
  6086. // The behavior of printf and friends in this case is implementation
  6087. // dependent. Ideally if the format string cannot be null then
  6088. // it should have a 'nonnull' attribute in the function prototype.
  6089. return SLCT_UncheckedLiteral;
  6090. switch (E->getStmtClass()) {
  6091. case Stmt::BinaryConditionalOperatorClass:
  6092. case Stmt::ConditionalOperatorClass: {
  6093. // The expression is a literal if both sub-expressions were, and it was
  6094. // completely checked only if both sub-expressions were checked.
  6095. const AbstractConditionalOperator *C =
  6096. cast<AbstractConditionalOperator>(E);
  6097. // Determine whether it is necessary to check both sub-expressions, for
  6098. // example, because the condition expression is a constant that can be
  6099. // evaluated at compile time.
  6100. bool CheckLeft = true, CheckRight = true;
  6101. bool Cond;
  6102. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
  6103. S.isConstantEvaluated())) {
  6104. if (Cond)
  6105. CheckRight = false;
  6106. else
  6107. CheckLeft = false;
  6108. }
  6109. // We need to maintain the offsets for the right and the left hand side
  6110. // separately to check if every possible indexed expression is a valid
  6111. // string literal. They might have different offsets for different string
  6112. // literals in the end.
  6113. StringLiteralCheckType Left;
  6114. if (!CheckLeft)
  6115. Left = SLCT_UncheckedLiteral;
  6116. else {
  6117. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  6118. HasVAListArg, format_idx, firstDataArg,
  6119. Type, CallType, InFunctionCall,
  6120. CheckedVarArgs, UncoveredArg, Offset,
  6121. IgnoreStringsWithoutSpecifiers);
  6122. if (Left == SLCT_NotALiteral || !CheckRight) {
  6123. return Left;
  6124. }
  6125. }
  6126. StringLiteralCheckType Right = checkFormatStringExpr(
  6127. S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
  6128. Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6129. IgnoreStringsWithoutSpecifiers);
  6130. return (CheckLeft && Left < Right) ? Left : Right;
  6131. }
  6132. case Stmt::ImplicitCastExprClass:
  6133. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  6134. goto tryAgain;
  6135. case Stmt::OpaqueValueExprClass:
  6136. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  6137. E = src;
  6138. goto tryAgain;
  6139. }
  6140. return SLCT_NotALiteral;
  6141. case Stmt::PredefinedExprClass:
  6142. // While __func__, etc., are technically not string literals, they
  6143. // cannot contain format specifiers and thus are not a security
  6144. // liability.
  6145. return SLCT_UncheckedLiteral;
  6146. case Stmt::DeclRefExprClass: {
  6147. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6148. // As an exception, do not flag errors for variables binding to
  6149. // const string literals.
  6150. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  6151. bool isConstant = false;
  6152. QualType T = DR->getType();
  6153. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  6154. isConstant = AT->getElementType().isConstant(S.Context);
  6155. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  6156. isConstant = T.isConstant(S.Context) &&
  6157. PT->getPointeeType().isConstant(S.Context);
  6158. } else if (T->isObjCObjectPointerType()) {
  6159. // In ObjC, there is usually no "const ObjectPointer" type,
  6160. // so don't check if the pointee type is constant.
  6161. isConstant = T.isConstant(S.Context);
  6162. }
  6163. if (isConstant) {
  6164. if (const Expr *Init = VD->getAnyInitializer()) {
  6165. // Look through initializers like const char c[] = { "foo" }
  6166. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  6167. if (InitList->isStringLiteralInit())
  6168. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  6169. }
  6170. return checkFormatStringExpr(S, Init, Args,
  6171. HasVAListArg, format_idx,
  6172. firstDataArg, Type, CallType,
  6173. /*InFunctionCall*/ false, CheckedVarArgs,
  6174. UncoveredArg, Offset);
  6175. }
  6176. }
  6177. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  6178. // special check to see if the format string is a function parameter
  6179. // of the function calling the printf function. If the function
  6180. // has an attribute indicating it is a printf-like function, then we
  6181. // should suppress warnings concerning non-literals being used in a call
  6182. // to a vprintf function. For example:
  6183. //
  6184. // void
  6185. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  6186. // va_list ap;
  6187. // va_start(ap, fmt);
  6188. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  6189. // ...
  6190. // }
  6191. if (HasVAListArg) {
  6192. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  6193. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  6194. int PVIndex = PV->getFunctionScopeIndex() + 1;
  6195. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  6196. // adjust for implicit parameter
  6197. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6198. if (MD->isInstance())
  6199. ++PVIndex;
  6200. // We also check if the formats are compatible.
  6201. // We can't pass a 'scanf' string to a 'printf' function.
  6202. if (PVIndex == PVFormat->getFormatIdx() &&
  6203. Type == S.GetFormatStringType(PVFormat))
  6204. return SLCT_UncheckedLiteral;
  6205. }
  6206. }
  6207. }
  6208. }
  6209. }
  6210. return SLCT_NotALiteral;
  6211. }
  6212. case Stmt::CallExprClass:
  6213. case Stmt::CXXMemberCallExprClass: {
  6214. const CallExpr *CE = cast<CallExpr>(E);
  6215. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  6216. bool IsFirst = true;
  6217. StringLiteralCheckType CommonResult;
  6218. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  6219. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  6220. StringLiteralCheckType Result = checkFormatStringExpr(
  6221. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6222. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6223. IgnoreStringsWithoutSpecifiers);
  6224. if (IsFirst) {
  6225. CommonResult = Result;
  6226. IsFirst = false;
  6227. }
  6228. }
  6229. if (!IsFirst)
  6230. return CommonResult;
  6231. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  6232. unsigned BuiltinID = FD->getBuiltinID();
  6233. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  6234. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  6235. const Expr *Arg = CE->getArg(0);
  6236. return checkFormatStringExpr(S, Arg, Args,
  6237. HasVAListArg, format_idx,
  6238. firstDataArg, Type, CallType,
  6239. InFunctionCall, CheckedVarArgs,
  6240. UncoveredArg, Offset,
  6241. IgnoreStringsWithoutSpecifiers);
  6242. }
  6243. }
  6244. }
  6245. return SLCT_NotALiteral;
  6246. }
  6247. case Stmt::ObjCMessageExprClass: {
  6248. const auto *ME = cast<ObjCMessageExpr>(E);
  6249. if (const auto *MD = ME->getMethodDecl()) {
  6250. if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
  6251. // As a special case heuristic, if we're using the method -[NSBundle
  6252. // localizedStringForKey:value:table:], ignore any key strings that lack
  6253. // format specifiers. The idea is that if the key doesn't have any
  6254. // format specifiers then its probably just a key to map to the
  6255. // localized strings. If it does have format specifiers though, then its
  6256. // likely that the text of the key is the format string in the
  6257. // programmer's language, and should be checked.
  6258. const ObjCInterfaceDecl *IFace;
  6259. if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
  6260. IFace->getIdentifier()->isStr("NSBundle") &&
  6261. MD->getSelector().isKeywordSelector(
  6262. {"localizedStringForKey", "value", "table"})) {
  6263. IgnoreStringsWithoutSpecifiers = true;
  6264. }
  6265. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  6266. return checkFormatStringExpr(
  6267. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6268. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6269. IgnoreStringsWithoutSpecifiers);
  6270. }
  6271. }
  6272. return SLCT_NotALiteral;
  6273. }
  6274. case Stmt::ObjCStringLiteralClass:
  6275. case Stmt::StringLiteralClass: {
  6276. const StringLiteral *StrE = nullptr;
  6277. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  6278. StrE = ObjCFExpr->getString();
  6279. else
  6280. StrE = cast<StringLiteral>(E);
  6281. if (StrE) {
  6282. if (Offset.isNegative() || Offset > StrE->getLength()) {
  6283. // TODO: It would be better to have an explicit warning for out of
  6284. // bounds literals.
  6285. return SLCT_NotALiteral;
  6286. }
  6287. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  6288. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  6289. firstDataArg, Type, InFunctionCall, CallType,
  6290. CheckedVarArgs, UncoveredArg,
  6291. IgnoreStringsWithoutSpecifiers);
  6292. return SLCT_CheckedLiteral;
  6293. }
  6294. return SLCT_NotALiteral;
  6295. }
  6296. case Stmt::BinaryOperatorClass: {
  6297. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  6298. // A string literal + an int offset is still a string literal.
  6299. if (BinOp->isAdditiveOp()) {
  6300. Expr::EvalResult LResult, RResult;
  6301. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
  6302. LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6303. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
  6304. RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6305. if (LIsInt != RIsInt) {
  6306. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  6307. if (LIsInt) {
  6308. if (BinOpKind == BO_Add) {
  6309. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  6310. E = BinOp->getRHS();
  6311. goto tryAgain;
  6312. }
  6313. } else {
  6314. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  6315. E = BinOp->getLHS();
  6316. goto tryAgain;
  6317. }
  6318. }
  6319. }
  6320. return SLCT_NotALiteral;
  6321. }
  6322. case Stmt::UnaryOperatorClass: {
  6323. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  6324. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  6325. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  6326. Expr::EvalResult IndexResult;
  6327. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
  6328. Expr::SE_NoSideEffects,
  6329. S.isConstantEvaluated())) {
  6330. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  6331. /*RHS is int*/ true);
  6332. E = ASE->getBase();
  6333. goto tryAgain;
  6334. }
  6335. }
  6336. return SLCT_NotALiteral;
  6337. }
  6338. default:
  6339. return SLCT_NotALiteral;
  6340. }
  6341. }
  6342. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  6343. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  6344. .Case("scanf", FST_Scanf)
  6345. .Cases("printf", "printf0", FST_Printf)
  6346. .Cases("NSString", "CFString", FST_NSString)
  6347. .Case("strftime", FST_Strftime)
  6348. .Case("strfmon", FST_Strfmon)
  6349. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  6350. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  6351. .Case("os_trace", FST_OSLog)
  6352. .Case("os_log", FST_OSLog)
  6353. .Default(FST_Unknown);
  6354. }
  6355. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  6356. /// functions) for correct use of format strings.
  6357. /// Returns true if a format string has been fully checked.
  6358. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  6359. ArrayRef<const Expr *> Args,
  6360. bool IsCXXMember,
  6361. VariadicCallType CallType,
  6362. SourceLocation Loc, SourceRange Range,
  6363. llvm::SmallBitVector &CheckedVarArgs) {
  6364. FormatStringInfo FSI;
  6365. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  6366. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  6367. FSI.FirstDataArg, GetFormatStringType(Format),
  6368. CallType, Loc, Range, CheckedVarArgs);
  6369. return false;
  6370. }
  6371. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  6372. bool HasVAListArg, unsigned format_idx,
  6373. unsigned firstDataArg, FormatStringType Type,
  6374. VariadicCallType CallType,
  6375. SourceLocation Loc, SourceRange Range,
  6376. llvm::SmallBitVector &CheckedVarArgs) {
  6377. // CHECK: printf/scanf-like function is called with no format string.
  6378. if (format_idx >= Args.size()) {
  6379. Diag(Loc, diag::warn_missing_format_string) << Range;
  6380. return false;
  6381. }
  6382. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6383. // CHECK: format string is not a string literal.
  6384. //
  6385. // Dynamically generated format strings are difficult to
  6386. // automatically vet at compile time. Requiring that format strings
  6387. // are string literals: (1) permits the checking of format strings by
  6388. // the compiler and thereby (2) can practically remove the source of
  6389. // many format string exploits.
  6390. // Format string can be either ObjC string (e.g. @"%d") or
  6391. // C string (e.g. "%d")
  6392. // ObjC string uses the same format specifiers as C string, so we can use
  6393. // the same format string checking logic for both ObjC and C strings.
  6394. UncoveredArgHandler UncoveredArg;
  6395. StringLiteralCheckType CT =
  6396. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6397. format_idx, firstDataArg, Type, CallType,
  6398. /*IsFunctionCall*/ true, CheckedVarArgs,
  6399. UncoveredArg,
  6400. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6401. // Generate a diagnostic where an uncovered argument is detected.
  6402. if (UncoveredArg.hasUncoveredArg()) {
  6403. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6404. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6405. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6406. }
  6407. if (CT != SLCT_NotALiteral)
  6408. // Literal format string found, check done!
  6409. return CT == SLCT_CheckedLiteral;
  6410. // Strftime is particular as it always uses a single 'time' argument,
  6411. // so it is safe to pass a non-literal string.
  6412. if (Type == FST_Strftime)
  6413. return false;
  6414. // Do not emit diag when the string param is a macro expansion and the
  6415. // format is either NSString or CFString. This is a hack to prevent
  6416. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6417. // which are usually used in place of NS and CF string literals.
  6418. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6419. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6420. return false;
  6421. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6422. // warn only with -Wformat-nonliteral.
  6423. if (Args.size() == firstDataArg) {
  6424. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6425. << OrigFormatExpr->getSourceRange();
  6426. switch (Type) {
  6427. default:
  6428. break;
  6429. case FST_Kprintf:
  6430. case FST_FreeBSDKPrintf:
  6431. case FST_Printf:
  6432. Diag(FormatLoc, diag::note_format_security_fixit)
  6433. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6434. break;
  6435. case FST_NSString:
  6436. Diag(FormatLoc, diag::note_format_security_fixit)
  6437. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6438. break;
  6439. }
  6440. } else {
  6441. Diag(FormatLoc, diag::warn_format_nonliteral)
  6442. << OrigFormatExpr->getSourceRange();
  6443. }
  6444. return false;
  6445. }
  6446. namespace {
  6447. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6448. protected:
  6449. Sema &S;
  6450. const FormatStringLiteral *FExpr;
  6451. const Expr *OrigFormatExpr;
  6452. const Sema::FormatStringType FSType;
  6453. const unsigned FirstDataArg;
  6454. const unsigned NumDataArgs;
  6455. const char *Beg; // Start of format string.
  6456. const bool HasVAListArg;
  6457. ArrayRef<const Expr *> Args;
  6458. unsigned FormatIdx;
  6459. llvm::SmallBitVector CoveredArgs;
  6460. bool usesPositionalArgs = false;
  6461. bool atFirstArg = true;
  6462. bool inFunctionCall;
  6463. Sema::VariadicCallType CallType;
  6464. llvm::SmallBitVector &CheckedVarArgs;
  6465. UncoveredArgHandler &UncoveredArg;
  6466. public:
  6467. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6468. const Expr *origFormatExpr,
  6469. const Sema::FormatStringType type, unsigned firstDataArg,
  6470. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6471. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6472. bool inFunctionCall, Sema::VariadicCallType callType,
  6473. llvm::SmallBitVector &CheckedVarArgs,
  6474. UncoveredArgHandler &UncoveredArg)
  6475. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6476. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6477. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6478. inFunctionCall(inFunctionCall), CallType(callType),
  6479. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6480. CoveredArgs.resize(numDataArgs);
  6481. CoveredArgs.reset();
  6482. }
  6483. void DoneProcessing();
  6484. void HandleIncompleteSpecifier(const char *startSpecifier,
  6485. unsigned specifierLen) override;
  6486. void HandleInvalidLengthModifier(
  6487. const analyze_format_string::FormatSpecifier &FS,
  6488. const analyze_format_string::ConversionSpecifier &CS,
  6489. const char *startSpecifier, unsigned specifierLen,
  6490. unsigned DiagID);
  6491. void HandleNonStandardLengthModifier(
  6492. const analyze_format_string::FormatSpecifier &FS,
  6493. const char *startSpecifier, unsigned specifierLen);
  6494. void HandleNonStandardConversionSpecifier(
  6495. const analyze_format_string::ConversionSpecifier &CS,
  6496. const char *startSpecifier, unsigned specifierLen);
  6497. void HandlePosition(const char *startPos, unsigned posLen) override;
  6498. void HandleInvalidPosition(const char *startSpecifier,
  6499. unsigned specifierLen,
  6500. analyze_format_string::PositionContext p) override;
  6501. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6502. void HandleNullChar(const char *nullCharacter) override;
  6503. template <typename Range>
  6504. static void
  6505. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6506. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6507. bool IsStringLocation, Range StringRange,
  6508. ArrayRef<FixItHint> Fixit = None);
  6509. protected:
  6510. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6511. const char *startSpec,
  6512. unsigned specifierLen,
  6513. const char *csStart, unsigned csLen);
  6514. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6515. const char *startSpec,
  6516. unsigned specifierLen);
  6517. SourceRange getFormatStringRange();
  6518. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6519. unsigned specifierLen);
  6520. SourceLocation getLocationOfByte(const char *x);
  6521. const Expr *getDataArg(unsigned i) const;
  6522. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6523. const analyze_format_string::ConversionSpecifier &CS,
  6524. const char *startSpecifier, unsigned specifierLen,
  6525. unsigned argIndex);
  6526. template <typename Range>
  6527. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6528. bool IsStringLocation, Range StringRange,
  6529. ArrayRef<FixItHint> Fixit = None);
  6530. };
  6531. } // namespace
  6532. SourceRange CheckFormatHandler::getFormatStringRange() {
  6533. return OrigFormatExpr->getSourceRange();
  6534. }
  6535. CharSourceRange CheckFormatHandler::
  6536. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6537. SourceLocation Start = getLocationOfByte(startSpecifier);
  6538. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6539. // Advance the end SourceLocation by one due to half-open ranges.
  6540. End = End.getLocWithOffset(1);
  6541. return CharSourceRange::getCharRange(Start, End);
  6542. }
  6543. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6544. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6545. S.getLangOpts(), S.Context.getTargetInfo());
  6546. }
  6547. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6548. unsigned specifierLen){
  6549. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6550. getLocationOfByte(startSpecifier),
  6551. /*IsStringLocation*/true,
  6552. getSpecifierRange(startSpecifier, specifierLen));
  6553. }
  6554. void CheckFormatHandler::HandleInvalidLengthModifier(
  6555. const analyze_format_string::FormatSpecifier &FS,
  6556. const analyze_format_string::ConversionSpecifier &CS,
  6557. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6558. using namespace analyze_format_string;
  6559. const LengthModifier &LM = FS.getLengthModifier();
  6560. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6561. // See if we know how to fix this length modifier.
  6562. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6563. if (FixedLM) {
  6564. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6565. getLocationOfByte(LM.getStart()),
  6566. /*IsStringLocation*/true,
  6567. getSpecifierRange(startSpecifier, specifierLen));
  6568. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6569. << FixedLM->toString()
  6570. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6571. } else {
  6572. FixItHint Hint;
  6573. if (DiagID == diag::warn_format_nonsensical_length)
  6574. Hint = FixItHint::CreateRemoval(LMRange);
  6575. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6576. getLocationOfByte(LM.getStart()),
  6577. /*IsStringLocation*/true,
  6578. getSpecifierRange(startSpecifier, specifierLen),
  6579. Hint);
  6580. }
  6581. }
  6582. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6583. const analyze_format_string::FormatSpecifier &FS,
  6584. const char *startSpecifier, unsigned specifierLen) {
  6585. using namespace analyze_format_string;
  6586. const LengthModifier &LM = FS.getLengthModifier();
  6587. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6588. // See if we know how to fix this length modifier.
  6589. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6590. if (FixedLM) {
  6591. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6592. << LM.toString() << 0,
  6593. getLocationOfByte(LM.getStart()),
  6594. /*IsStringLocation*/true,
  6595. getSpecifierRange(startSpecifier, specifierLen));
  6596. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6597. << FixedLM->toString()
  6598. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6599. } else {
  6600. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6601. << LM.toString() << 0,
  6602. getLocationOfByte(LM.getStart()),
  6603. /*IsStringLocation*/true,
  6604. getSpecifierRange(startSpecifier, specifierLen));
  6605. }
  6606. }
  6607. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6608. const analyze_format_string::ConversionSpecifier &CS,
  6609. const char *startSpecifier, unsigned specifierLen) {
  6610. using namespace analyze_format_string;
  6611. // See if we know how to fix this conversion specifier.
  6612. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6613. if (FixedCS) {
  6614. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6615. << CS.toString() << /*conversion specifier*/1,
  6616. getLocationOfByte(CS.getStart()),
  6617. /*IsStringLocation*/true,
  6618. getSpecifierRange(startSpecifier, specifierLen));
  6619. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6620. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6621. << FixedCS->toString()
  6622. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6623. } else {
  6624. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6625. << CS.toString() << /*conversion specifier*/1,
  6626. getLocationOfByte(CS.getStart()),
  6627. /*IsStringLocation*/true,
  6628. getSpecifierRange(startSpecifier, specifierLen));
  6629. }
  6630. }
  6631. void CheckFormatHandler::HandlePosition(const char *startPos,
  6632. unsigned posLen) {
  6633. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6634. getLocationOfByte(startPos),
  6635. /*IsStringLocation*/true,
  6636. getSpecifierRange(startPos, posLen));
  6637. }
  6638. void
  6639. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6640. analyze_format_string::PositionContext p) {
  6641. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6642. << (unsigned) p,
  6643. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6644. getSpecifierRange(startPos, posLen));
  6645. }
  6646. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6647. unsigned posLen) {
  6648. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6649. getLocationOfByte(startPos),
  6650. /*IsStringLocation*/true,
  6651. getSpecifierRange(startPos, posLen));
  6652. }
  6653. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6654. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6655. // The presence of a null character is likely an error.
  6656. EmitFormatDiagnostic(
  6657. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6658. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6659. getFormatStringRange());
  6660. }
  6661. }
  6662. // Note that this may return NULL if there was an error parsing or building
  6663. // one of the argument expressions.
  6664. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6665. return Args[FirstDataArg + i];
  6666. }
  6667. void CheckFormatHandler::DoneProcessing() {
  6668. // Does the number of data arguments exceed the number of
  6669. // format conversions in the format string?
  6670. if (!HasVAListArg) {
  6671. // Find any arguments that weren't covered.
  6672. CoveredArgs.flip();
  6673. signed notCoveredArg = CoveredArgs.find_first();
  6674. if (notCoveredArg >= 0) {
  6675. assert((unsigned)notCoveredArg < NumDataArgs);
  6676. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6677. } else {
  6678. UncoveredArg.setAllCovered();
  6679. }
  6680. }
  6681. }
  6682. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6683. const Expr *ArgExpr) {
  6684. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6685. "Invalid state");
  6686. if (!ArgExpr)
  6687. return;
  6688. SourceLocation Loc = ArgExpr->getBeginLoc();
  6689. if (S.getSourceManager().isInSystemMacro(Loc))
  6690. return;
  6691. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6692. for (auto E : DiagnosticExprs)
  6693. PDiag << E->getSourceRange();
  6694. CheckFormatHandler::EmitFormatDiagnostic(
  6695. S, IsFunctionCall, DiagnosticExprs[0],
  6696. PDiag, Loc, /*IsStringLocation*/false,
  6697. DiagnosticExprs[0]->getSourceRange());
  6698. }
  6699. bool
  6700. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6701. SourceLocation Loc,
  6702. const char *startSpec,
  6703. unsigned specifierLen,
  6704. const char *csStart,
  6705. unsigned csLen) {
  6706. bool keepGoing = true;
  6707. if (argIndex < NumDataArgs) {
  6708. // Consider the argument coverered, even though the specifier doesn't
  6709. // make sense.
  6710. CoveredArgs.set(argIndex);
  6711. }
  6712. else {
  6713. // If argIndex exceeds the number of data arguments we
  6714. // don't issue a warning because that is just a cascade of warnings (and
  6715. // they may have intended '%%' anyway). We don't want to continue processing
  6716. // the format string after this point, however, as we will like just get
  6717. // gibberish when trying to match arguments.
  6718. keepGoing = false;
  6719. }
  6720. StringRef Specifier(csStart, csLen);
  6721. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6722. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6723. // hex value.
  6724. std::string CodePointStr;
  6725. if (!llvm::sys::locale::isPrint(*csStart)) {
  6726. llvm::UTF32 CodePoint;
  6727. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6728. const llvm::UTF8 *E =
  6729. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6730. llvm::ConversionResult Result =
  6731. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6732. if (Result != llvm::conversionOK) {
  6733. unsigned char FirstChar = *csStart;
  6734. CodePoint = (llvm::UTF32)FirstChar;
  6735. }
  6736. llvm::raw_string_ostream OS(CodePointStr);
  6737. if (CodePoint < 256)
  6738. OS << "\\x" << llvm::format("%02x", CodePoint);
  6739. else if (CodePoint <= 0xFFFF)
  6740. OS << "\\u" << llvm::format("%04x", CodePoint);
  6741. else
  6742. OS << "\\U" << llvm::format("%08x", CodePoint);
  6743. OS.flush();
  6744. Specifier = CodePointStr;
  6745. }
  6746. EmitFormatDiagnostic(
  6747. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6748. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6749. return keepGoing;
  6750. }
  6751. void
  6752. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6753. const char *startSpec,
  6754. unsigned specifierLen) {
  6755. EmitFormatDiagnostic(
  6756. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6757. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6758. }
  6759. bool
  6760. CheckFormatHandler::CheckNumArgs(
  6761. const analyze_format_string::FormatSpecifier &FS,
  6762. const analyze_format_string::ConversionSpecifier &CS,
  6763. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6764. if (argIndex >= NumDataArgs) {
  6765. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6766. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6767. << (argIndex+1) << NumDataArgs)
  6768. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6769. EmitFormatDiagnostic(
  6770. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6771. getSpecifierRange(startSpecifier, specifierLen));
  6772. // Since more arguments than conversion tokens are given, by extension
  6773. // all arguments are covered, so mark this as so.
  6774. UncoveredArg.setAllCovered();
  6775. return false;
  6776. }
  6777. return true;
  6778. }
  6779. template<typename Range>
  6780. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6781. SourceLocation Loc,
  6782. bool IsStringLocation,
  6783. Range StringRange,
  6784. ArrayRef<FixItHint> FixIt) {
  6785. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6786. Loc, IsStringLocation, StringRange, FixIt);
  6787. }
  6788. /// If the format string is not within the function call, emit a note
  6789. /// so that the function call and string are in diagnostic messages.
  6790. ///
  6791. /// \param InFunctionCall if true, the format string is within the function
  6792. /// call and only one diagnostic message will be produced. Otherwise, an
  6793. /// extra note will be emitted pointing to location of the format string.
  6794. ///
  6795. /// \param ArgumentExpr the expression that is passed as the format string
  6796. /// argument in the function call. Used for getting locations when two
  6797. /// diagnostics are emitted.
  6798. ///
  6799. /// \param PDiag the callee should already have provided any strings for the
  6800. /// diagnostic message. This function only adds locations and fixits
  6801. /// to diagnostics.
  6802. ///
  6803. /// \param Loc primary location for diagnostic. If two diagnostics are
  6804. /// required, one will be at Loc and a new SourceLocation will be created for
  6805. /// the other one.
  6806. ///
  6807. /// \param IsStringLocation if true, Loc points to the format string should be
  6808. /// used for the note. Otherwise, Loc points to the argument list and will
  6809. /// be used with PDiag.
  6810. ///
  6811. /// \param StringRange some or all of the string to highlight. This is
  6812. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6813. ///
  6814. /// \param FixIt optional fix it hint for the format string.
  6815. template <typename Range>
  6816. void CheckFormatHandler::EmitFormatDiagnostic(
  6817. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6818. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6819. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6820. if (InFunctionCall) {
  6821. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6822. D << StringRange;
  6823. D << FixIt;
  6824. } else {
  6825. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6826. << ArgumentExpr->getSourceRange();
  6827. const Sema::SemaDiagnosticBuilder &Note =
  6828. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6829. diag::note_format_string_defined);
  6830. Note << StringRange;
  6831. Note << FixIt;
  6832. }
  6833. }
  6834. //===--- CHECK: Printf format string checking ------------------------------===//
  6835. namespace {
  6836. class CheckPrintfHandler : public CheckFormatHandler {
  6837. public:
  6838. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6839. const Expr *origFormatExpr,
  6840. const Sema::FormatStringType type, unsigned firstDataArg,
  6841. unsigned numDataArgs, bool isObjC, const char *beg,
  6842. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6843. unsigned formatIdx, bool inFunctionCall,
  6844. Sema::VariadicCallType CallType,
  6845. llvm::SmallBitVector &CheckedVarArgs,
  6846. UncoveredArgHandler &UncoveredArg)
  6847. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6848. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6849. inFunctionCall, CallType, CheckedVarArgs,
  6850. UncoveredArg) {}
  6851. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6852. /// Returns true if '%@' specifiers are allowed in the format string.
  6853. bool allowsObjCArg() const {
  6854. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6855. FSType == Sema::FST_OSTrace;
  6856. }
  6857. bool HandleInvalidPrintfConversionSpecifier(
  6858. const analyze_printf::PrintfSpecifier &FS,
  6859. const char *startSpecifier,
  6860. unsigned specifierLen) override;
  6861. void handleInvalidMaskType(StringRef MaskType) override;
  6862. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6863. const char *startSpecifier,
  6864. unsigned specifierLen) override;
  6865. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6866. const char *StartSpecifier,
  6867. unsigned SpecifierLen,
  6868. const Expr *E);
  6869. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6870. const char *startSpecifier, unsigned specifierLen);
  6871. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6872. const analyze_printf::OptionalAmount &Amt,
  6873. unsigned type,
  6874. const char *startSpecifier, unsigned specifierLen);
  6875. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6876. const analyze_printf::OptionalFlag &flag,
  6877. const char *startSpecifier, unsigned specifierLen);
  6878. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6879. const analyze_printf::OptionalFlag &ignoredFlag,
  6880. const analyze_printf::OptionalFlag &flag,
  6881. const char *startSpecifier, unsigned specifierLen);
  6882. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6883. const Expr *E);
  6884. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6885. unsigned flagLen) override;
  6886. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6887. unsigned flagLen) override;
  6888. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6889. const char *flagsEnd,
  6890. const char *conversionPosition)
  6891. override;
  6892. };
  6893. } // namespace
  6894. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6895. const analyze_printf::PrintfSpecifier &FS,
  6896. const char *startSpecifier,
  6897. unsigned specifierLen) {
  6898. const analyze_printf::PrintfConversionSpecifier &CS =
  6899. FS.getConversionSpecifier();
  6900. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6901. getLocationOfByte(CS.getStart()),
  6902. startSpecifier, specifierLen,
  6903. CS.getStart(), CS.getLength());
  6904. }
  6905. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6906. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6907. }
  6908. bool CheckPrintfHandler::HandleAmount(
  6909. const analyze_format_string::OptionalAmount &Amt,
  6910. unsigned k, const char *startSpecifier,
  6911. unsigned specifierLen) {
  6912. if (Amt.hasDataArgument()) {
  6913. if (!HasVAListArg) {
  6914. unsigned argIndex = Amt.getArgIndex();
  6915. if (argIndex >= NumDataArgs) {
  6916. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6917. << k,
  6918. getLocationOfByte(Amt.getStart()),
  6919. /*IsStringLocation*/true,
  6920. getSpecifierRange(startSpecifier, specifierLen));
  6921. // Don't do any more checking. We will just emit
  6922. // spurious errors.
  6923. return false;
  6924. }
  6925. // Type check the data argument. It should be an 'int'.
  6926. // Although not in conformance with C99, we also allow the argument to be
  6927. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6928. // doesn't emit a warning for that case.
  6929. CoveredArgs.set(argIndex);
  6930. const Expr *Arg = getDataArg(argIndex);
  6931. if (!Arg)
  6932. return false;
  6933. QualType T = Arg->getType();
  6934. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6935. assert(AT.isValid());
  6936. if (!AT.matchesType(S.Context, T)) {
  6937. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6938. << k << AT.getRepresentativeTypeName(S.Context)
  6939. << T << Arg->getSourceRange(),
  6940. getLocationOfByte(Amt.getStart()),
  6941. /*IsStringLocation*/true,
  6942. getSpecifierRange(startSpecifier, specifierLen));
  6943. // Don't do any more checking. We will just emit
  6944. // spurious errors.
  6945. return false;
  6946. }
  6947. }
  6948. }
  6949. return true;
  6950. }
  6951. void CheckPrintfHandler::HandleInvalidAmount(
  6952. const analyze_printf::PrintfSpecifier &FS,
  6953. const analyze_printf::OptionalAmount &Amt,
  6954. unsigned type,
  6955. const char *startSpecifier,
  6956. unsigned specifierLen) {
  6957. const analyze_printf::PrintfConversionSpecifier &CS =
  6958. FS.getConversionSpecifier();
  6959. FixItHint fixit =
  6960. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6961. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6962. Amt.getConstantLength()))
  6963. : FixItHint();
  6964. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6965. << type << CS.toString(),
  6966. getLocationOfByte(Amt.getStart()),
  6967. /*IsStringLocation*/true,
  6968. getSpecifierRange(startSpecifier, specifierLen),
  6969. fixit);
  6970. }
  6971. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6972. const analyze_printf::OptionalFlag &flag,
  6973. const char *startSpecifier,
  6974. unsigned specifierLen) {
  6975. // Warn about pointless flag with a fixit removal.
  6976. const analyze_printf::PrintfConversionSpecifier &CS =
  6977. FS.getConversionSpecifier();
  6978. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6979. << flag.toString() << CS.toString(),
  6980. getLocationOfByte(flag.getPosition()),
  6981. /*IsStringLocation*/true,
  6982. getSpecifierRange(startSpecifier, specifierLen),
  6983. FixItHint::CreateRemoval(
  6984. getSpecifierRange(flag.getPosition(), 1)));
  6985. }
  6986. void CheckPrintfHandler::HandleIgnoredFlag(
  6987. const analyze_printf::PrintfSpecifier &FS,
  6988. const analyze_printf::OptionalFlag &ignoredFlag,
  6989. const analyze_printf::OptionalFlag &flag,
  6990. const char *startSpecifier,
  6991. unsigned specifierLen) {
  6992. // Warn about ignored flag with a fixit removal.
  6993. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6994. << ignoredFlag.toString() << flag.toString(),
  6995. getLocationOfByte(ignoredFlag.getPosition()),
  6996. /*IsStringLocation*/true,
  6997. getSpecifierRange(startSpecifier, specifierLen),
  6998. FixItHint::CreateRemoval(
  6999. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  7000. }
  7001. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  7002. unsigned flagLen) {
  7003. // Warn about an empty flag.
  7004. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  7005. getLocationOfByte(startFlag),
  7006. /*IsStringLocation*/true,
  7007. getSpecifierRange(startFlag, flagLen));
  7008. }
  7009. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  7010. unsigned flagLen) {
  7011. // Warn about an invalid flag.
  7012. auto Range = getSpecifierRange(startFlag, flagLen);
  7013. StringRef flag(startFlag, flagLen);
  7014. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  7015. getLocationOfByte(startFlag),
  7016. /*IsStringLocation*/true,
  7017. Range, FixItHint::CreateRemoval(Range));
  7018. }
  7019. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  7020. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  7021. // Warn about using '[...]' without a '@' conversion.
  7022. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  7023. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  7024. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  7025. getLocationOfByte(conversionPosition),
  7026. /*IsStringLocation*/true,
  7027. Range, FixItHint::CreateRemoval(Range));
  7028. }
  7029. // Determines if the specified is a C++ class or struct containing
  7030. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  7031. // "c_str()").
  7032. template<typename MemberKind>
  7033. static llvm::SmallPtrSet<MemberKind*, 1>
  7034. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  7035. const RecordType *RT = Ty->getAs<RecordType>();
  7036. llvm::SmallPtrSet<MemberKind*, 1> Results;
  7037. if (!RT)
  7038. return Results;
  7039. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  7040. if (!RD || !RD->getDefinition())
  7041. return Results;
  7042. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  7043. Sema::LookupMemberName);
  7044. R.suppressDiagnostics();
  7045. // We just need to include all members of the right kind turned up by the
  7046. // filter, at this point.
  7047. if (S.LookupQualifiedName(R, RT->getDecl()))
  7048. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  7049. NamedDecl *decl = (*I)->getUnderlyingDecl();
  7050. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  7051. Results.insert(FK);
  7052. }
  7053. return Results;
  7054. }
  7055. /// Check if we could call '.c_str()' on an object.
  7056. ///
  7057. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  7058. /// allow the call, or if it would be ambiguous).
  7059. bool Sema::hasCStrMethod(const Expr *E) {
  7060. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  7061. MethodSet Results =
  7062. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  7063. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  7064. MI != ME; ++MI)
  7065. if ((*MI)->getMinRequiredArguments() == 0)
  7066. return true;
  7067. return false;
  7068. }
  7069. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  7070. // better diagnostic if so. AT is assumed to be valid.
  7071. // Returns true when a c_str() conversion method is found.
  7072. bool CheckPrintfHandler::checkForCStrMembers(
  7073. const analyze_printf::ArgType &AT, const Expr *E) {
  7074. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  7075. MethodSet Results =
  7076. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  7077. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  7078. MI != ME; ++MI) {
  7079. const CXXMethodDecl *Method = *MI;
  7080. if (Method->getMinRequiredArguments() == 0 &&
  7081. AT.matchesType(S.Context, Method->getReturnType())) {
  7082. // FIXME: Suggest parens if the expression needs them.
  7083. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  7084. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  7085. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  7086. return true;
  7087. }
  7088. }
  7089. return false;
  7090. }
  7091. bool
  7092. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  7093. &FS,
  7094. const char *startSpecifier,
  7095. unsigned specifierLen) {
  7096. using namespace analyze_format_string;
  7097. using namespace analyze_printf;
  7098. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  7099. if (FS.consumesDataArgument()) {
  7100. if (atFirstArg) {
  7101. atFirstArg = false;
  7102. usesPositionalArgs = FS.usesPositionalArg();
  7103. }
  7104. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7105. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7106. startSpecifier, specifierLen);
  7107. return false;
  7108. }
  7109. }
  7110. // First check if the field width, precision, and conversion specifier
  7111. // have matching data arguments.
  7112. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  7113. startSpecifier, specifierLen)) {
  7114. return false;
  7115. }
  7116. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  7117. startSpecifier, specifierLen)) {
  7118. return false;
  7119. }
  7120. if (!CS.consumesDataArgument()) {
  7121. // FIXME: Technically specifying a precision or field width here
  7122. // makes no sense. Worth issuing a warning at some point.
  7123. return true;
  7124. }
  7125. // Consume the argument.
  7126. unsigned argIndex = FS.getArgIndex();
  7127. if (argIndex < NumDataArgs) {
  7128. // The check to see if the argIndex is valid will come later.
  7129. // We set the bit here because we may exit early from this
  7130. // function if we encounter some other error.
  7131. CoveredArgs.set(argIndex);
  7132. }
  7133. // FreeBSD kernel extensions.
  7134. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  7135. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  7136. // We need at least two arguments.
  7137. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  7138. return false;
  7139. // Claim the second argument.
  7140. CoveredArgs.set(argIndex + 1);
  7141. // Type check the first argument (int for %b, pointer for %D)
  7142. const Expr *Ex = getDataArg(argIndex);
  7143. const analyze_printf::ArgType &AT =
  7144. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  7145. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  7146. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  7147. EmitFormatDiagnostic(
  7148. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7149. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  7150. << false << Ex->getSourceRange(),
  7151. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7152. getSpecifierRange(startSpecifier, specifierLen));
  7153. // Type check the second argument (char * for both %b and %D)
  7154. Ex = getDataArg(argIndex + 1);
  7155. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  7156. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  7157. EmitFormatDiagnostic(
  7158. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7159. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  7160. << false << Ex->getSourceRange(),
  7161. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7162. getSpecifierRange(startSpecifier, specifierLen));
  7163. return true;
  7164. }
  7165. // Check for using an Objective-C specific conversion specifier
  7166. // in a non-ObjC literal.
  7167. if (!allowsObjCArg() && CS.isObjCArg()) {
  7168. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7169. specifierLen);
  7170. }
  7171. // %P can only be used with os_log.
  7172. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  7173. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7174. specifierLen);
  7175. }
  7176. // %n is not allowed with os_log.
  7177. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  7178. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  7179. getLocationOfByte(CS.getStart()),
  7180. /*IsStringLocation*/ false,
  7181. getSpecifierRange(startSpecifier, specifierLen));
  7182. return true;
  7183. }
  7184. // Only scalars are allowed for os_trace.
  7185. if (FSType == Sema::FST_OSTrace &&
  7186. (CS.getKind() == ConversionSpecifier::PArg ||
  7187. CS.getKind() == ConversionSpecifier::sArg ||
  7188. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  7189. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7190. specifierLen);
  7191. }
  7192. // Check for use of public/private annotation outside of os_log().
  7193. if (FSType != Sema::FST_OSLog) {
  7194. if (FS.isPublic().isSet()) {
  7195. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7196. << "public",
  7197. getLocationOfByte(FS.isPublic().getPosition()),
  7198. /*IsStringLocation*/ false,
  7199. getSpecifierRange(startSpecifier, specifierLen));
  7200. }
  7201. if (FS.isPrivate().isSet()) {
  7202. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7203. << "private",
  7204. getLocationOfByte(FS.isPrivate().getPosition()),
  7205. /*IsStringLocation*/ false,
  7206. getSpecifierRange(startSpecifier, specifierLen));
  7207. }
  7208. }
  7209. // Check for invalid use of field width
  7210. if (!FS.hasValidFieldWidth()) {
  7211. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  7212. startSpecifier, specifierLen);
  7213. }
  7214. // Check for invalid use of precision
  7215. if (!FS.hasValidPrecision()) {
  7216. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  7217. startSpecifier, specifierLen);
  7218. }
  7219. // Precision is mandatory for %P specifier.
  7220. if (CS.getKind() == ConversionSpecifier::PArg &&
  7221. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  7222. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  7223. getLocationOfByte(startSpecifier),
  7224. /*IsStringLocation*/ false,
  7225. getSpecifierRange(startSpecifier, specifierLen));
  7226. }
  7227. // Check each flag does not conflict with any other component.
  7228. if (!FS.hasValidThousandsGroupingPrefix())
  7229. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  7230. if (!FS.hasValidLeadingZeros())
  7231. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  7232. if (!FS.hasValidPlusPrefix())
  7233. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  7234. if (!FS.hasValidSpacePrefix())
  7235. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  7236. if (!FS.hasValidAlternativeForm())
  7237. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  7238. if (!FS.hasValidLeftJustified())
  7239. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  7240. // Check that flags are not ignored by another flag
  7241. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  7242. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  7243. startSpecifier, specifierLen);
  7244. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  7245. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  7246. startSpecifier, specifierLen);
  7247. // Check the length modifier is valid with the given conversion specifier.
  7248. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7249. S.getLangOpts()))
  7250. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7251. diag::warn_format_nonsensical_length);
  7252. else if (!FS.hasStandardLengthModifier())
  7253. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7254. else if (!FS.hasStandardLengthConversionCombination())
  7255. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7256. diag::warn_format_non_standard_conversion_spec);
  7257. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7258. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7259. // The remaining checks depend on the data arguments.
  7260. if (HasVAListArg)
  7261. return true;
  7262. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7263. return false;
  7264. const Expr *Arg = getDataArg(argIndex);
  7265. if (!Arg)
  7266. return true;
  7267. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  7268. }
  7269. static bool requiresParensToAddCast(const Expr *E) {
  7270. // FIXME: We should have a general way to reason about operator
  7271. // precedence and whether parens are actually needed here.
  7272. // Take care of a few common cases where they aren't.
  7273. const Expr *Inside = E->IgnoreImpCasts();
  7274. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  7275. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  7276. switch (Inside->getStmtClass()) {
  7277. case Stmt::ArraySubscriptExprClass:
  7278. case Stmt::CallExprClass:
  7279. case Stmt::CharacterLiteralClass:
  7280. case Stmt::CXXBoolLiteralExprClass:
  7281. case Stmt::DeclRefExprClass:
  7282. case Stmt::FloatingLiteralClass:
  7283. case Stmt::IntegerLiteralClass:
  7284. case Stmt::MemberExprClass:
  7285. case Stmt::ObjCArrayLiteralClass:
  7286. case Stmt::ObjCBoolLiteralExprClass:
  7287. case Stmt::ObjCBoxedExprClass:
  7288. case Stmt::ObjCDictionaryLiteralClass:
  7289. case Stmt::ObjCEncodeExprClass:
  7290. case Stmt::ObjCIvarRefExprClass:
  7291. case Stmt::ObjCMessageExprClass:
  7292. case Stmt::ObjCPropertyRefExprClass:
  7293. case Stmt::ObjCStringLiteralClass:
  7294. case Stmt::ObjCSubscriptRefExprClass:
  7295. case Stmt::ParenExprClass:
  7296. case Stmt::StringLiteralClass:
  7297. case Stmt::UnaryOperatorClass:
  7298. return false;
  7299. default:
  7300. return true;
  7301. }
  7302. }
  7303. static std::pair<QualType, StringRef>
  7304. shouldNotPrintDirectly(const ASTContext &Context,
  7305. QualType IntendedTy,
  7306. const Expr *E) {
  7307. // Use a 'while' to peel off layers of typedefs.
  7308. QualType TyTy = IntendedTy;
  7309. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  7310. StringRef Name = UserTy->getDecl()->getName();
  7311. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  7312. .Case("CFIndex", Context.getNSIntegerType())
  7313. .Case("NSInteger", Context.getNSIntegerType())
  7314. .Case("NSUInteger", Context.getNSUIntegerType())
  7315. .Case("SInt32", Context.IntTy)
  7316. .Case("UInt32", Context.UnsignedIntTy)
  7317. .Default(QualType());
  7318. if (!CastTy.isNull())
  7319. return std::make_pair(CastTy, Name);
  7320. TyTy = UserTy->desugar();
  7321. }
  7322. // Strip parens if necessary.
  7323. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  7324. return shouldNotPrintDirectly(Context,
  7325. PE->getSubExpr()->getType(),
  7326. PE->getSubExpr());
  7327. // If this is a conditional expression, then its result type is constructed
  7328. // via usual arithmetic conversions and thus there might be no necessary
  7329. // typedef sugar there. Recurse to operands to check for NSInteger &
  7330. // Co. usage condition.
  7331. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7332. QualType TrueTy, FalseTy;
  7333. StringRef TrueName, FalseName;
  7334. std::tie(TrueTy, TrueName) =
  7335. shouldNotPrintDirectly(Context,
  7336. CO->getTrueExpr()->getType(),
  7337. CO->getTrueExpr());
  7338. std::tie(FalseTy, FalseName) =
  7339. shouldNotPrintDirectly(Context,
  7340. CO->getFalseExpr()->getType(),
  7341. CO->getFalseExpr());
  7342. if (TrueTy == FalseTy)
  7343. return std::make_pair(TrueTy, TrueName);
  7344. else if (TrueTy.isNull())
  7345. return std::make_pair(FalseTy, FalseName);
  7346. else if (FalseTy.isNull())
  7347. return std::make_pair(TrueTy, TrueName);
  7348. }
  7349. return std::make_pair(QualType(), StringRef());
  7350. }
  7351. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  7352. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  7353. /// type do not count.
  7354. static bool
  7355. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  7356. QualType From = ICE->getSubExpr()->getType();
  7357. QualType To = ICE->getType();
  7358. // It's an integer promotion if the destination type is the promoted
  7359. // source type.
  7360. if (ICE->getCastKind() == CK_IntegralCast &&
  7361. From->isPromotableIntegerType() &&
  7362. S.Context.getPromotedIntegerType(From) == To)
  7363. return true;
  7364. // Look through vector types, since we do default argument promotion for
  7365. // those in OpenCL.
  7366. if (const auto *VecTy = From->getAs<ExtVectorType>())
  7367. From = VecTy->getElementType();
  7368. if (const auto *VecTy = To->getAs<ExtVectorType>())
  7369. To = VecTy->getElementType();
  7370. // It's a floating promotion if the source type is a lower rank.
  7371. return ICE->getCastKind() == CK_FloatingCast &&
  7372. S.Context.getFloatingTypeOrder(From, To) < 0;
  7373. }
  7374. bool
  7375. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  7376. const char *StartSpecifier,
  7377. unsigned SpecifierLen,
  7378. const Expr *E) {
  7379. using namespace analyze_format_string;
  7380. using namespace analyze_printf;
  7381. // Now type check the data expression that matches the
  7382. // format specifier.
  7383. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  7384. if (!AT.isValid())
  7385. return true;
  7386. QualType ExprTy = E->getType();
  7387. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  7388. ExprTy = TET->getUnderlyingExpr()->getType();
  7389. }
  7390. // Diagnose attempts to print a boolean value as a character. Unlike other
  7391. // -Wformat diagnostics, this is fine from a type perspective, but it still
  7392. // doesn't make sense.
  7393. if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
  7394. E->isKnownToHaveBooleanValue()) {
  7395. const CharSourceRange &CSR =
  7396. getSpecifierRange(StartSpecifier, SpecifierLen);
  7397. SmallString<4> FSString;
  7398. llvm::raw_svector_ostream os(FSString);
  7399. FS.toString(os);
  7400. EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
  7401. << FSString,
  7402. E->getExprLoc(), false, CSR);
  7403. return true;
  7404. }
  7405. const analyze_printf::ArgType::MatchKind Match =
  7406. AT.matchesType(S.Context, ExprTy);
  7407. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  7408. if (Match == analyze_printf::ArgType::Match)
  7409. return true;
  7410. // Look through argument promotions for our error message's reported type.
  7411. // This includes the integral and floating promotions, but excludes array
  7412. // and function pointer decay (seeing that an argument intended to be a
  7413. // string has type 'char [6]' is probably more confusing than 'char *') and
  7414. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  7415. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7416. if (isArithmeticArgumentPromotion(S, ICE)) {
  7417. E = ICE->getSubExpr();
  7418. ExprTy = E->getType();
  7419. // Check if we didn't match because of an implicit cast from a 'char'
  7420. // or 'short' to an 'int'. This is done because printf is a varargs
  7421. // function.
  7422. if (ICE->getType() == S.Context.IntTy ||
  7423. ICE->getType() == S.Context.UnsignedIntTy) {
  7424. // All further checking is done on the subexpression
  7425. const analyze_printf::ArgType::MatchKind ImplicitMatch =
  7426. AT.matchesType(S.Context, ExprTy);
  7427. if (ImplicitMatch == analyze_printf::ArgType::Match)
  7428. return true;
  7429. if (ImplicitMatch == analyze_printf::ArgType::NoMatchPedantic)
  7430. Pedantic = true;
  7431. }
  7432. }
  7433. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7434. // Special case for 'a', which has type 'int' in C.
  7435. // Note, however, that we do /not/ want to treat multibyte constants like
  7436. // 'MooV' as characters! This form is deprecated but still exists.
  7437. if (ExprTy == S.Context.IntTy)
  7438. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7439. ExprTy = S.Context.CharTy;
  7440. }
  7441. // Look through enums to their underlying type.
  7442. bool IsEnum = false;
  7443. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7444. ExprTy = EnumTy->getDecl()->getIntegerType();
  7445. IsEnum = true;
  7446. }
  7447. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7448. // If the argument is an integer of some kind, believe the %C and suggest
  7449. // a cast instead of changing the conversion specifier.
  7450. QualType IntendedTy = ExprTy;
  7451. if (isObjCContext() &&
  7452. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7453. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7454. !ExprTy->isCharType()) {
  7455. // 'unichar' is defined as a typedef of unsigned short, but we should
  7456. // prefer using the typedef if it is visible.
  7457. IntendedTy = S.Context.UnsignedShortTy;
  7458. // While we are here, check if the value is an IntegerLiteral that happens
  7459. // to be within the valid range.
  7460. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7461. const llvm::APInt &V = IL->getValue();
  7462. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7463. return true;
  7464. }
  7465. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7466. Sema::LookupOrdinaryName);
  7467. if (S.LookupName(Result, S.getCurScope())) {
  7468. NamedDecl *ND = Result.getFoundDecl();
  7469. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7470. if (TD->getUnderlyingType() == IntendedTy)
  7471. IntendedTy = S.Context.getTypedefType(TD);
  7472. }
  7473. }
  7474. }
  7475. // Special-case some of Darwin's platform-independence types by suggesting
  7476. // casts to primitive types that are known to be large enough.
  7477. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7478. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7479. QualType CastTy;
  7480. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7481. if (!CastTy.isNull()) {
  7482. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7483. // (long in ASTContext). Only complain to pedants.
  7484. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7485. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7486. AT.matchesType(S.Context, CastTy))
  7487. Pedantic = true;
  7488. IntendedTy = CastTy;
  7489. ShouldNotPrintDirectly = true;
  7490. }
  7491. }
  7492. // We may be able to offer a FixItHint if it is a supported type.
  7493. PrintfSpecifier fixedFS = FS;
  7494. bool Success =
  7495. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7496. if (Success) {
  7497. // Get the fix string from the fixed format specifier
  7498. SmallString<16> buf;
  7499. llvm::raw_svector_ostream os(buf);
  7500. fixedFS.toString(os);
  7501. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7502. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7503. unsigned Diag =
  7504. Pedantic
  7505. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7506. : diag::warn_format_conversion_argument_type_mismatch;
  7507. // In this case, the specifier is wrong and should be changed to match
  7508. // the argument.
  7509. EmitFormatDiagnostic(S.PDiag(Diag)
  7510. << AT.getRepresentativeTypeName(S.Context)
  7511. << IntendedTy << IsEnum << E->getSourceRange(),
  7512. E->getBeginLoc(),
  7513. /*IsStringLocation*/ false, SpecRange,
  7514. FixItHint::CreateReplacement(SpecRange, os.str()));
  7515. } else {
  7516. // The canonical type for formatting this value is different from the
  7517. // actual type of the expression. (This occurs, for example, with Darwin's
  7518. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7519. // should be printed as 'long' for 64-bit compatibility.)
  7520. // Rather than emitting a normal format/argument mismatch, we want to
  7521. // add a cast to the recommended type (and correct the format string
  7522. // if necessary).
  7523. SmallString<16> CastBuf;
  7524. llvm::raw_svector_ostream CastFix(CastBuf);
  7525. CastFix << "(";
  7526. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7527. CastFix << ")";
  7528. SmallVector<FixItHint,4> Hints;
  7529. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7530. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7531. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7532. // If there's already a cast present, just replace it.
  7533. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7534. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7535. } else if (!requiresParensToAddCast(E)) {
  7536. // If the expression has high enough precedence,
  7537. // just write the C-style cast.
  7538. Hints.push_back(
  7539. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7540. } else {
  7541. // Otherwise, add parens around the expression as well as the cast.
  7542. CastFix << "(";
  7543. Hints.push_back(
  7544. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7545. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7546. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7547. }
  7548. if (ShouldNotPrintDirectly) {
  7549. // The expression has a type that should not be printed directly.
  7550. // We extract the name from the typedef because we don't want to show
  7551. // the underlying type in the diagnostic.
  7552. StringRef Name;
  7553. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7554. Name = TypedefTy->getDecl()->getName();
  7555. else
  7556. Name = CastTyName;
  7557. unsigned Diag = Pedantic
  7558. ? diag::warn_format_argument_needs_cast_pedantic
  7559. : diag::warn_format_argument_needs_cast;
  7560. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7561. << E->getSourceRange(),
  7562. E->getBeginLoc(), /*IsStringLocation=*/false,
  7563. SpecRange, Hints);
  7564. } else {
  7565. // In this case, the expression could be printed using a different
  7566. // specifier, but we've decided that the specifier is probably correct
  7567. // and we should cast instead. Just use the normal warning message.
  7568. EmitFormatDiagnostic(
  7569. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7570. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7571. << E->getSourceRange(),
  7572. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7573. }
  7574. }
  7575. } else {
  7576. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7577. SpecifierLen);
  7578. // Since the warning for passing non-POD types to variadic functions
  7579. // was deferred until now, we emit a warning for non-POD
  7580. // arguments here.
  7581. switch (S.isValidVarArgType(ExprTy)) {
  7582. case Sema::VAK_Valid:
  7583. case Sema::VAK_ValidInCXX11: {
  7584. unsigned Diag =
  7585. Pedantic
  7586. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7587. : diag::warn_format_conversion_argument_type_mismatch;
  7588. EmitFormatDiagnostic(
  7589. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7590. << IsEnum << CSR << E->getSourceRange(),
  7591. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7592. break;
  7593. }
  7594. case Sema::VAK_Undefined:
  7595. case Sema::VAK_MSVCUndefined:
  7596. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7597. << S.getLangOpts().CPlusPlus11 << ExprTy
  7598. << CallType
  7599. << AT.getRepresentativeTypeName(S.Context) << CSR
  7600. << E->getSourceRange(),
  7601. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7602. checkForCStrMembers(AT, E);
  7603. break;
  7604. case Sema::VAK_Invalid:
  7605. if (ExprTy->isObjCObjectType())
  7606. EmitFormatDiagnostic(
  7607. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7608. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7609. << AT.getRepresentativeTypeName(S.Context) << CSR
  7610. << E->getSourceRange(),
  7611. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7612. else
  7613. // FIXME: If this is an initializer list, suggest removing the braces
  7614. // or inserting a cast to the target type.
  7615. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7616. << isa<InitListExpr>(E) << ExprTy << CallType
  7617. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7618. break;
  7619. }
  7620. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7621. "format string specifier index out of range");
  7622. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7623. }
  7624. return true;
  7625. }
  7626. //===--- CHECK: Scanf format string checking ------------------------------===//
  7627. namespace {
  7628. class CheckScanfHandler : public CheckFormatHandler {
  7629. public:
  7630. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7631. const Expr *origFormatExpr, Sema::FormatStringType type,
  7632. unsigned firstDataArg, unsigned numDataArgs,
  7633. const char *beg, bool hasVAListArg,
  7634. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7635. bool inFunctionCall, Sema::VariadicCallType CallType,
  7636. llvm::SmallBitVector &CheckedVarArgs,
  7637. UncoveredArgHandler &UncoveredArg)
  7638. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7639. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7640. inFunctionCall, CallType, CheckedVarArgs,
  7641. UncoveredArg) {}
  7642. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7643. const char *startSpecifier,
  7644. unsigned specifierLen) override;
  7645. bool HandleInvalidScanfConversionSpecifier(
  7646. const analyze_scanf::ScanfSpecifier &FS,
  7647. const char *startSpecifier,
  7648. unsigned specifierLen) override;
  7649. void HandleIncompleteScanList(const char *start, const char *end) override;
  7650. };
  7651. } // namespace
  7652. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7653. const char *end) {
  7654. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7655. getLocationOfByte(end), /*IsStringLocation*/true,
  7656. getSpecifierRange(start, end - start));
  7657. }
  7658. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7659. const analyze_scanf::ScanfSpecifier &FS,
  7660. const char *startSpecifier,
  7661. unsigned specifierLen) {
  7662. const analyze_scanf::ScanfConversionSpecifier &CS =
  7663. FS.getConversionSpecifier();
  7664. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7665. getLocationOfByte(CS.getStart()),
  7666. startSpecifier, specifierLen,
  7667. CS.getStart(), CS.getLength());
  7668. }
  7669. bool CheckScanfHandler::HandleScanfSpecifier(
  7670. const analyze_scanf::ScanfSpecifier &FS,
  7671. const char *startSpecifier,
  7672. unsigned specifierLen) {
  7673. using namespace analyze_scanf;
  7674. using namespace analyze_format_string;
  7675. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7676. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7677. // be used to decide if we are using positional arguments consistently.
  7678. if (FS.consumesDataArgument()) {
  7679. if (atFirstArg) {
  7680. atFirstArg = false;
  7681. usesPositionalArgs = FS.usesPositionalArg();
  7682. }
  7683. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7684. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7685. startSpecifier, specifierLen);
  7686. return false;
  7687. }
  7688. }
  7689. // Check if the field with is non-zero.
  7690. const OptionalAmount &Amt = FS.getFieldWidth();
  7691. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7692. if (Amt.getConstantAmount() == 0) {
  7693. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7694. Amt.getConstantLength());
  7695. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7696. getLocationOfByte(Amt.getStart()),
  7697. /*IsStringLocation*/true, R,
  7698. FixItHint::CreateRemoval(R));
  7699. }
  7700. }
  7701. if (!FS.consumesDataArgument()) {
  7702. // FIXME: Technically specifying a precision or field width here
  7703. // makes no sense. Worth issuing a warning at some point.
  7704. return true;
  7705. }
  7706. // Consume the argument.
  7707. unsigned argIndex = FS.getArgIndex();
  7708. if (argIndex < NumDataArgs) {
  7709. // The check to see if the argIndex is valid will come later.
  7710. // We set the bit here because we may exit early from this
  7711. // function if we encounter some other error.
  7712. CoveredArgs.set(argIndex);
  7713. }
  7714. // Check the length modifier is valid with the given conversion specifier.
  7715. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7716. S.getLangOpts()))
  7717. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7718. diag::warn_format_nonsensical_length);
  7719. else if (!FS.hasStandardLengthModifier())
  7720. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7721. else if (!FS.hasStandardLengthConversionCombination())
  7722. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7723. diag::warn_format_non_standard_conversion_spec);
  7724. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7725. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7726. // The remaining checks depend on the data arguments.
  7727. if (HasVAListArg)
  7728. return true;
  7729. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7730. return false;
  7731. // Check that the argument type matches the format specifier.
  7732. const Expr *Ex = getDataArg(argIndex);
  7733. if (!Ex)
  7734. return true;
  7735. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7736. if (!AT.isValid()) {
  7737. return true;
  7738. }
  7739. analyze_format_string::ArgType::MatchKind Match =
  7740. AT.matchesType(S.Context, Ex->getType());
  7741. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7742. if (Match == analyze_format_string::ArgType::Match)
  7743. return true;
  7744. ScanfSpecifier fixedFS = FS;
  7745. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7746. S.getLangOpts(), S.Context);
  7747. unsigned Diag =
  7748. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7749. : diag::warn_format_conversion_argument_type_mismatch;
  7750. if (Success) {
  7751. // Get the fix string from the fixed format specifier.
  7752. SmallString<128> buf;
  7753. llvm::raw_svector_ostream os(buf);
  7754. fixedFS.toString(os);
  7755. EmitFormatDiagnostic(
  7756. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7757. << Ex->getType() << false << Ex->getSourceRange(),
  7758. Ex->getBeginLoc(),
  7759. /*IsStringLocation*/ false,
  7760. getSpecifierRange(startSpecifier, specifierLen),
  7761. FixItHint::CreateReplacement(
  7762. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7763. } else {
  7764. EmitFormatDiagnostic(S.PDiag(Diag)
  7765. << AT.getRepresentativeTypeName(S.Context)
  7766. << Ex->getType() << false << Ex->getSourceRange(),
  7767. Ex->getBeginLoc(),
  7768. /*IsStringLocation*/ false,
  7769. getSpecifierRange(startSpecifier, specifierLen));
  7770. }
  7771. return true;
  7772. }
  7773. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7774. const Expr *OrigFormatExpr,
  7775. ArrayRef<const Expr *> Args,
  7776. bool HasVAListArg, unsigned format_idx,
  7777. unsigned firstDataArg,
  7778. Sema::FormatStringType Type,
  7779. bool inFunctionCall,
  7780. Sema::VariadicCallType CallType,
  7781. llvm::SmallBitVector &CheckedVarArgs,
  7782. UncoveredArgHandler &UncoveredArg,
  7783. bool IgnoreStringsWithoutSpecifiers) {
  7784. // CHECK: is the format string a wide literal?
  7785. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7786. CheckFormatHandler::EmitFormatDiagnostic(
  7787. S, inFunctionCall, Args[format_idx],
  7788. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7789. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7790. return;
  7791. }
  7792. // Str - The format string. NOTE: this is NOT null-terminated!
  7793. StringRef StrRef = FExpr->getString();
  7794. const char *Str = StrRef.data();
  7795. // Account for cases where the string literal is truncated in a declaration.
  7796. const ConstantArrayType *T =
  7797. S.Context.getAsConstantArrayType(FExpr->getType());
  7798. assert(T && "String literal not of constant array type!");
  7799. size_t TypeSize = T->getSize().getZExtValue();
  7800. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7801. const unsigned numDataArgs = Args.size() - firstDataArg;
  7802. if (IgnoreStringsWithoutSpecifiers &&
  7803. !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
  7804. Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
  7805. return;
  7806. // Emit a warning if the string literal is truncated and does not contain an
  7807. // embedded null character.
  7808. if (TypeSize <= StrRef.size() &&
  7809. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7810. CheckFormatHandler::EmitFormatDiagnostic(
  7811. S, inFunctionCall, Args[format_idx],
  7812. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7813. FExpr->getBeginLoc(),
  7814. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7815. return;
  7816. }
  7817. // CHECK: empty format string?
  7818. if (StrLen == 0 && numDataArgs > 0) {
  7819. CheckFormatHandler::EmitFormatDiagnostic(
  7820. S, inFunctionCall, Args[format_idx],
  7821. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7822. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7823. return;
  7824. }
  7825. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7826. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7827. Type == Sema::FST_OSTrace) {
  7828. CheckPrintfHandler H(
  7829. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7830. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7831. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7832. CheckedVarArgs, UncoveredArg);
  7833. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7834. S.getLangOpts(),
  7835. S.Context.getTargetInfo(),
  7836. Type == Sema::FST_FreeBSDKPrintf))
  7837. H.DoneProcessing();
  7838. } else if (Type == Sema::FST_Scanf) {
  7839. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7840. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7841. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7842. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7843. S.getLangOpts(),
  7844. S.Context.getTargetInfo()))
  7845. H.DoneProcessing();
  7846. } // TODO: handle other formats
  7847. }
  7848. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7849. // Str - The format string. NOTE: this is NOT null-terminated!
  7850. StringRef StrRef = FExpr->getString();
  7851. const char *Str = StrRef.data();
  7852. // Account for cases where the string literal is truncated in a declaration.
  7853. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7854. assert(T && "String literal not of constant array type!");
  7855. size_t TypeSize = T->getSize().getZExtValue();
  7856. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7857. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7858. getLangOpts(),
  7859. Context.getTargetInfo());
  7860. }
  7861. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7862. // Returns the related absolute value function that is larger, of 0 if one
  7863. // does not exist.
  7864. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7865. switch (AbsFunction) {
  7866. default:
  7867. return 0;
  7868. case Builtin::BI__builtin_abs:
  7869. return Builtin::BI__builtin_labs;
  7870. case Builtin::BI__builtin_labs:
  7871. return Builtin::BI__builtin_llabs;
  7872. case Builtin::BI__builtin_llabs:
  7873. return 0;
  7874. case Builtin::BI__builtin_fabsf:
  7875. return Builtin::BI__builtin_fabs;
  7876. case Builtin::BI__builtin_fabs:
  7877. return Builtin::BI__builtin_fabsl;
  7878. case Builtin::BI__builtin_fabsl:
  7879. return 0;
  7880. case Builtin::BI__builtin_cabsf:
  7881. return Builtin::BI__builtin_cabs;
  7882. case Builtin::BI__builtin_cabs:
  7883. return Builtin::BI__builtin_cabsl;
  7884. case Builtin::BI__builtin_cabsl:
  7885. return 0;
  7886. case Builtin::BIabs:
  7887. return Builtin::BIlabs;
  7888. case Builtin::BIlabs:
  7889. return Builtin::BIllabs;
  7890. case Builtin::BIllabs:
  7891. return 0;
  7892. case Builtin::BIfabsf:
  7893. return Builtin::BIfabs;
  7894. case Builtin::BIfabs:
  7895. return Builtin::BIfabsl;
  7896. case Builtin::BIfabsl:
  7897. return 0;
  7898. case Builtin::BIcabsf:
  7899. return Builtin::BIcabs;
  7900. case Builtin::BIcabs:
  7901. return Builtin::BIcabsl;
  7902. case Builtin::BIcabsl:
  7903. return 0;
  7904. }
  7905. }
  7906. // Returns the argument type of the absolute value function.
  7907. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7908. unsigned AbsType) {
  7909. if (AbsType == 0)
  7910. return QualType();
  7911. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7912. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7913. if (Error != ASTContext::GE_None)
  7914. return QualType();
  7915. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7916. if (!FT)
  7917. return QualType();
  7918. if (FT->getNumParams() != 1)
  7919. return QualType();
  7920. return FT->getParamType(0);
  7921. }
  7922. // Returns the best absolute value function, or zero, based on type and
  7923. // current absolute value function.
  7924. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7925. unsigned AbsFunctionKind) {
  7926. unsigned BestKind = 0;
  7927. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7928. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7929. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7930. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7931. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7932. if (BestKind == 0)
  7933. BestKind = Kind;
  7934. else if (Context.hasSameType(ParamType, ArgType)) {
  7935. BestKind = Kind;
  7936. break;
  7937. }
  7938. }
  7939. }
  7940. return BestKind;
  7941. }
  7942. enum AbsoluteValueKind {
  7943. AVK_Integer,
  7944. AVK_Floating,
  7945. AVK_Complex
  7946. };
  7947. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7948. if (T->isIntegralOrEnumerationType())
  7949. return AVK_Integer;
  7950. if (T->isRealFloatingType())
  7951. return AVK_Floating;
  7952. if (T->isAnyComplexType())
  7953. return AVK_Complex;
  7954. llvm_unreachable("Type not integer, floating, or complex");
  7955. }
  7956. // Changes the absolute value function to a different type. Preserves whether
  7957. // the function is a builtin.
  7958. static unsigned changeAbsFunction(unsigned AbsKind,
  7959. AbsoluteValueKind ValueKind) {
  7960. switch (ValueKind) {
  7961. case AVK_Integer:
  7962. switch (AbsKind) {
  7963. default:
  7964. return 0;
  7965. case Builtin::BI__builtin_fabsf:
  7966. case Builtin::BI__builtin_fabs:
  7967. case Builtin::BI__builtin_fabsl:
  7968. case Builtin::BI__builtin_cabsf:
  7969. case Builtin::BI__builtin_cabs:
  7970. case Builtin::BI__builtin_cabsl:
  7971. return Builtin::BI__builtin_abs;
  7972. case Builtin::BIfabsf:
  7973. case Builtin::BIfabs:
  7974. case Builtin::BIfabsl:
  7975. case Builtin::BIcabsf:
  7976. case Builtin::BIcabs:
  7977. case Builtin::BIcabsl:
  7978. return Builtin::BIabs;
  7979. }
  7980. case AVK_Floating:
  7981. switch (AbsKind) {
  7982. default:
  7983. return 0;
  7984. case Builtin::BI__builtin_abs:
  7985. case Builtin::BI__builtin_labs:
  7986. case Builtin::BI__builtin_llabs:
  7987. case Builtin::BI__builtin_cabsf:
  7988. case Builtin::BI__builtin_cabs:
  7989. case Builtin::BI__builtin_cabsl:
  7990. return Builtin::BI__builtin_fabsf;
  7991. case Builtin::BIabs:
  7992. case Builtin::BIlabs:
  7993. case Builtin::BIllabs:
  7994. case Builtin::BIcabsf:
  7995. case Builtin::BIcabs:
  7996. case Builtin::BIcabsl:
  7997. return Builtin::BIfabsf;
  7998. }
  7999. case AVK_Complex:
  8000. switch (AbsKind) {
  8001. default:
  8002. return 0;
  8003. case Builtin::BI__builtin_abs:
  8004. case Builtin::BI__builtin_labs:
  8005. case Builtin::BI__builtin_llabs:
  8006. case Builtin::BI__builtin_fabsf:
  8007. case Builtin::BI__builtin_fabs:
  8008. case Builtin::BI__builtin_fabsl:
  8009. return Builtin::BI__builtin_cabsf;
  8010. case Builtin::BIabs:
  8011. case Builtin::BIlabs:
  8012. case Builtin::BIllabs:
  8013. case Builtin::BIfabsf:
  8014. case Builtin::BIfabs:
  8015. case Builtin::BIfabsl:
  8016. return Builtin::BIcabsf;
  8017. }
  8018. }
  8019. llvm_unreachable("Unable to convert function");
  8020. }
  8021. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  8022. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  8023. if (!FnInfo)
  8024. return 0;
  8025. switch (FDecl->getBuiltinID()) {
  8026. default:
  8027. return 0;
  8028. case Builtin::BI__builtin_abs:
  8029. case Builtin::BI__builtin_fabs:
  8030. case Builtin::BI__builtin_fabsf:
  8031. case Builtin::BI__builtin_fabsl:
  8032. case Builtin::BI__builtin_labs:
  8033. case Builtin::BI__builtin_llabs:
  8034. case Builtin::BI__builtin_cabs:
  8035. case Builtin::BI__builtin_cabsf:
  8036. case Builtin::BI__builtin_cabsl:
  8037. case Builtin::BIabs:
  8038. case Builtin::BIlabs:
  8039. case Builtin::BIllabs:
  8040. case Builtin::BIfabs:
  8041. case Builtin::BIfabsf:
  8042. case Builtin::BIfabsl:
  8043. case Builtin::BIcabs:
  8044. case Builtin::BIcabsf:
  8045. case Builtin::BIcabsl:
  8046. return FDecl->getBuiltinID();
  8047. }
  8048. llvm_unreachable("Unknown Builtin type");
  8049. }
  8050. // If the replacement is valid, emit a note with replacement function.
  8051. // Additionally, suggest including the proper header if not already included.
  8052. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  8053. unsigned AbsKind, QualType ArgType) {
  8054. bool EmitHeaderHint = true;
  8055. const char *HeaderName = nullptr;
  8056. const char *FunctionName = nullptr;
  8057. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  8058. FunctionName = "std::abs";
  8059. if (ArgType->isIntegralOrEnumerationType()) {
  8060. HeaderName = "cstdlib";
  8061. } else if (ArgType->isRealFloatingType()) {
  8062. HeaderName = "cmath";
  8063. } else {
  8064. llvm_unreachable("Invalid Type");
  8065. }
  8066. // Lookup all std::abs
  8067. if (NamespaceDecl *Std = S.getStdNamespace()) {
  8068. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  8069. R.suppressDiagnostics();
  8070. S.LookupQualifiedName(R, Std);
  8071. for (const auto *I : R) {
  8072. const FunctionDecl *FDecl = nullptr;
  8073. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  8074. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  8075. } else {
  8076. FDecl = dyn_cast<FunctionDecl>(I);
  8077. }
  8078. if (!FDecl)
  8079. continue;
  8080. // Found std::abs(), check that they are the right ones.
  8081. if (FDecl->getNumParams() != 1)
  8082. continue;
  8083. // Check that the parameter type can handle the argument.
  8084. QualType ParamType = FDecl->getParamDecl(0)->getType();
  8085. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  8086. S.Context.getTypeSize(ArgType) <=
  8087. S.Context.getTypeSize(ParamType)) {
  8088. // Found a function, don't need the header hint.
  8089. EmitHeaderHint = false;
  8090. break;
  8091. }
  8092. }
  8093. }
  8094. } else {
  8095. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  8096. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  8097. if (HeaderName) {
  8098. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  8099. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  8100. R.suppressDiagnostics();
  8101. S.LookupName(R, S.getCurScope());
  8102. if (R.isSingleResult()) {
  8103. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  8104. if (FD && FD->getBuiltinID() == AbsKind) {
  8105. EmitHeaderHint = false;
  8106. } else {
  8107. return;
  8108. }
  8109. } else if (!R.empty()) {
  8110. return;
  8111. }
  8112. }
  8113. }
  8114. S.Diag(Loc, diag::note_replace_abs_function)
  8115. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  8116. if (!HeaderName)
  8117. return;
  8118. if (!EmitHeaderHint)
  8119. return;
  8120. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  8121. << FunctionName;
  8122. }
  8123. template <std::size_t StrLen>
  8124. static bool IsStdFunction(const FunctionDecl *FDecl,
  8125. const char (&Str)[StrLen]) {
  8126. if (!FDecl)
  8127. return false;
  8128. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  8129. return false;
  8130. if (!FDecl->isInStdNamespace())
  8131. return false;
  8132. return true;
  8133. }
  8134. // Warn when using the wrong abs() function.
  8135. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  8136. const FunctionDecl *FDecl) {
  8137. if (Call->getNumArgs() != 1)
  8138. return;
  8139. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  8140. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  8141. if (AbsKind == 0 && !IsStdAbs)
  8142. return;
  8143. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8144. QualType ParamType = Call->getArg(0)->getType();
  8145. // Unsigned types cannot be negative. Suggest removing the absolute value
  8146. // function call.
  8147. if (ArgType->isUnsignedIntegerType()) {
  8148. const char *FunctionName =
  8149. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  8150. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  8151. Diag(Call->getExprLoc(), diag::note_remove_abs)
  8152. << FunctionName
  8153. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  8154. return;
  8155. }
  8156. // Taking the absolute value of a pointer is very suspicious, they probably
  8157. // wanted to index into an array, dereference a pointer, call a function, etc.
  8158. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  8159. unsigned DiagType = 0;
  8160. if (ArgType->isFunctionType())
  8161. DiagType = 1;
  8162. else if (ArgType->isArrayType())
  8163. DiagType = 2;
  8164. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  8165. return;
  8166. }
  8167. // std::abs has overloads which prevent most of the absolute value problems
  8168. // from occurring.
  8169. if (IsStdAbs)
  8170. return;
  8171. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  8172. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  8173. // The argument and parameter are the same kind. Check if they are the right
  8174. // size.
  8175. if (ArgValueKind == ParamValueKind) {
  8176. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  8177. return;
  8178. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  8179. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  8180. << FDecl << ArgType << ParamType;
  8181. if (NewAbsKind == 0)
  8182. return;
  8183. emitReplacement(*this, Call->getExprLoc(),
  8184. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8185. return;
  8186. }
  8187. // ArgValueKind != ParamValueKind
  8188. // The wrong type of absolute value function was used. Attempt to find the
  8189. // proper one.
  8190. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  8191. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  8192. if (NewAbsKind == 0)
  8193. return;
  8194. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  8195. << FDecl << ParamValueKind << ArgValueKind;
  8196. emitReplacement(*this, Call->getExprLoc(),
  8197. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8198. }
  8199. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  8200. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  8201. const FunctionDecl *FDecl) {
  8202. if (!Call || !FDecl) return;
  8203. // Ignore template specializations and macros.
  8204. if (inTemplateInstantiation()) return;
  8205. if (Call->getExprLoc().isMacroID()) return;
  8206. // Only care about the one template argument, two function parameter std::max
  8207. if (Call->getNumArgs() != 2) return;
  8208. if (!IsStdFunction(FDecl, "max")) return;
  8209. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  8210. if (!ArgList) return;
  8211. if (ArgList->size() != 1) return;
  8212. // Check that template type argument is unsigned integer.
  8213. const auto& TA = ArgList->get(0);
  8214. if (TA.getKind() != TemplateArgument::Type) return;
  8215. QualType ArgType = TA.getAsType();
  8216. if (!ArgType->isUnsignedIntegerType()) return;
  8217. // See if either argument is a literal zero.
  8218. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  8219. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  8220. if (!MTE) return false;
  8221. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  8222. if (!Num) return false;
  8223. if (Num->getValue() != 0) return false;
  8224. return true;
  8225. };
  8226. const Expr *FirstArg = Call->getArg(0);
  8227. const Expr *SecondArg = Call->getArg(1);
  8228. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  8229. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  8230. // Only warn when exactly one argument is zero.
  8231. if (IsFirstArgZero == IsSecondArgZero) return;
  8232. SourceRange FirstRange = FirstArg->getSourceRange();
  8233. SourceRange SecondRange = SecondArg->getSourceRange();
  8234. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  8235. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  8236. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  8237. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  8238. SourceRange RemovalRange;
  8239. if (IsFirstArgZero) {
  8240. RemovalRange = SourceRange(FirstRange.getBegin(),
  8241. SecondRange.getBegin().getLocWithOffset(-1));
  8242. } else {
  8243. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  8244. SecondRange.getEnd());
  8245. }
  8246. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  8247. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  8248. << FixItHint::CreateRemoval(RemovalRange);
  8249. }
  8250. //===--- CHECK: Standard memory functions ---------------------------------===//
  8251. /// Takes the expression passed to the size_t parameter of functions
  8252. /// such as memcmp, strncat, etc and warns if it's a comparison.
  8253. ///
  8254. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  8255. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  8256. IdentifierInfo *FnName,
  8257. SourceLocation FnLoc,
  8258. SourceLocation RParenLoc) {
  8259. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  8260. if (!Size)
  8261. return false;
  8262. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  8263. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  8264. return false;
  8265. SourceRange SizeRange = Size->getSourceRange();
  8266. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  8267. << SizeRange << FnName;
  8268. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  8269. << FnName
  8270. << FixItHint::CreateInsertion(
  8271. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  8272. << FixItHint::CreateRemoval(RParenLoc);
  8273. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  8274. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  8275. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  8276. ")");
  8277. return true;
  8278. }
  8279. /// Determine whether the given type is or contains a dynamic class type
  8280. /// (e.g., whether it has a vtable).
  8281. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  8282. bool &IsContained) {
  8283. // Look through array types while ignoring qualifiers.
  8284. const Type *Ty = T->getBaseElementTypeUnsafe();
  8285. IsContained = false;
  8286. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  8287. RD = RD ? RD->getDefinition() : nullptr;
  8288. if (!RD || RD->isInvalidDecl())
  8289. return nullptr;
  8290. if (RD->isDynamicClass())
  8291. return RD;
  8292. // Check all the fields. If any bases were dynamic, the class is dynamic.
  8293. // It's impossible for a class to transitively contain itself by value, so
  8294. // infinite recursion is impossible.
  8295. for (auto *FD : RD->fields()) {
  8296. bool SubContained;
  8297. if (const CXXRecordDecl *ContainedRD =
  8298. getContainedDynamicClass(FD->getType(), SubContained)) {
  8299. IsContained = true;
  8300. return ContainedRD;
  8301. }
  8302. }
  8303. return nullptr;
  8304. }
  8305. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  8306. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  8307. if (Unary->getKind() == UETT_SizeOf)
  8308. return Unary;
  8309. return nullptr;
  8310. }
  8311. /// If E is a sizeof expression, returns its argument expression,
  8312. /// otherwise returns NULL.
  8313. static const Expr *getSizeOfExprArg(const Expr *E) {
  8314. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8315. if (!SizeOf->isArgumentType())
  8316. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  8317. return nullptr;
  8318. }
  8319. /// If E is a sizeof expression, returns its argument type.
  8320. static QualType getSizeOfArgType(const Expr *E) {
  8321. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8322. return SizeOf->getTypeOfArgument();
  8323. return QualType();
  8324. }
  8325. namespace {
  8326. struct SearchNonTrivialToInitializeField
  8327. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  8328. using Super =
  8329. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  8330. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  8331. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  8332. SourceLocation SL) {
  8333. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8334. asDerived().visitArray(PDIK, AT, SL);
  8335. return;
  8336. }
  8337. Super::visitWithKind(PDIK, FT, SL);
  8338. }
  8339. void visitARCStrong(QualType FT, SourceLocation SL) {
  8340. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8341. }
  8342. void visitARCWeak(QualType FT, SourceLocation SL) {
  8343. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8344. }
  8345. void visitStruct(QualType FT, SourceLocation SL) {
  8346. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8347. visit(FD->getType(), FD->getLocation());
  8348. }
  8349. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  8350. const ArrayType *AT, SourceLocation SL) {
  8351. visit(getContext().getBaseElementType(AT), SL);
  8352. }
  8353. void visitTrivial(QualType FT, SourceLocation SL) {}
  8354. static void diag(QualType RT, const Expr *E, Sema &S) {
  8355. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  8356. }
  8357. ASTContext &getContext() { return S.getASTContext(); }
  8358. const Expr *E;
  8359. Sema &S;
  8360. };
  8361. struct SearchNonTrivialToCopyField
  8362. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  8363. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  8364. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  8365. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  8366. SourceLocation SL) {
  8367. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8368. asDerived().visitArray(PCK, AT, SL);
  8369. return;
  8370. }
  8371. Super::visitWithKind(PCK, FT, SL);
  8372. }
  8373. void visitARCStrong(QualType FT, SourceLocation SL) {
  8374. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8375. }
  8376. void visitARCWeak(QualType FT, SourceLocation SL) {
  8377. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8378. }
  8379. void visitStruct(QualType FT, SourceLocation SL) {
  8380. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8381. visit(FD->getType(), FD->getLocation());
  8382. }
  8383. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  8384. SourceLocation SL) {
  8385. visit(getContext().getBaseElementType(AT), SL);
  8386. }
  8387. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  8388. SourceLocation SL) {}
  8389. void visitTrivial(QualType FT, SourceLocation SL) {}
  8390. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  8391. static void diag(QualType RT, const Expr *E, Sema &S) {
  8392. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  8393. }
  8394. ASTContext &getContext() { return S.getASTContext(); }
  8395. const Expr *E;
  8396. Sema &S;
  8397. };
  8398. }
  8399. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  8400. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  8401. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  8402. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  8403. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  8404. return false;
  8405. return doesExprLikelyComputeSize(BO->getLHS()) ||
  8406. doesExprLikelyComputeSize(BO->getRHS());
  8407. }
  8408. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  8409. }
  8410. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  8411. ///
  8412. /// \code
  8413. /// #define MACRO 0
  8414. /// foo(MACRO);
  8415. /// foo(0);
  8416. /// \endcode
  8417. ///
  8418. /// This should return true for the first call to foo, but not for the second
  8419. /// (regardless of whether foo is a macro or function).
  8420. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  8421. SourceLocation CallLoc,
  8422. SourceLocation ArgLoc) {
  8423. if (!CallLoc.isMacroID())
  8424. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8425. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8426. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8427. }
  8428. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8429. /// last two arguments transposed.
  8430. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8431. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8432. return;
  8433. const Expr *SizeArg =
  8434. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8435. auto isLiteralZero = [](const Expr *E) {
  8436. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8437. };
  8438. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8439. SourceLocation CallLoc = Call->getRParenLoc();
  8440. SourceManager &SM = S.getSourceManager();
  8441. if (isLiteralZero(SizeArg) &&
  8442. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8443. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8444. // Some platforms #define bzero to __builtin_memset. See if this is the
  8445. // case, and if so, emit a better diagnostic.
  8446. if (BId == Builtin::BIbzero ||
  8447. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8448. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8449. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8450. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8451. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8452. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8453. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8454. }
  8455. return;
  8456. }
  8457. // If the second argument to a memset is a sizeof expression and the third
  8458. // isn't, this is also likely an error. This should catch
  8459. // 'memset(buf, sizeof(buf), 0xff)'.
  8460. if (BId == Builtin::BImemset &&
  8461. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8462. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8463. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8464. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8465. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8466. return;
  8467. }
  8468. }
  8469. /// Check for dangerous or invalid arguments to memset().
  8470. ///
  8471. /// This issues warnings on known problematic, dangerous or unspecified
  8472. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8473. /// function calls.
  8474. ///
  8475. /// \param Call The call expression to diagnose.
  8476. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8477. unsigned BId,
  8478. IdentifierInfo *FnName) {
  8479. assert(BId != 0);
  8480. // It is possible to have a non-standard definition of memset. Validate
  8481. // we have enough arguments, and if not, abort further checking.
  8482. unsigned ExpectedNumArgs =
  8483. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8484. if (Call->getNumArgs() < ExpectedNumArgs)
  8485. return;
  8486. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8487. BId == Builtin::BIstrndup ? 1 : 2);
  8488. unsigned LenArg =
  8489. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8490. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8491. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8492. Call->getBeginLoc(), Call->getRParenLoc()))
  8493. return;
  8494. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8495. CheckMemaccessSize(*this, BId, Call);
  8496. // We have special checking when the length is a sizeof expression.
  8497. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8498. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8499. llvm::FoldingSetNodeID SizeOfArgID;
  8500. // Although widely used, 'bzero' is not a standard function. Be more strict
  8501. // with the argument types before allowing diagnostics and only allow the
  8502. // form bzero(ptr, sizeof(...)).
  8503. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8504. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8505. return;
  8506. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8507. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8508. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8509. QualType DestTy = Dest->getType();
  8510. QualType PointeeTy;
  8511. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8512. PointeeTy = DestPtrTy->getPointeeType();
  8513. // Never warn about void type pointers. This can be used to suppress
  8514. // false positives.
  8515. if (PointeeTy->isVoidType())
  8516. continue;
  8517. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8518. // actually comparing the expressions for equality. Because computing the
  8519. // expression IDs can be expensive, we only do this if the diagnostic is
  8520. // enabled.
  8521. if (SizeOfArg &&
  8522. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8523. SizeOfArg->getExprLoc())) {
  8524. // We only compute IDs for expressions if the warning is enabled, and
  8525. // cache the sizeof arg's ID.
  8526. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8527. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8528. llvm::FoldingSetNodeID DestID;
  8529. Dest->Profile(DestID, Context, true);
  8530. if (DestID == SizeOfArgID) {
  8531. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8532. // over sizeof(src) as well.
  8533. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8534. StringRef ReadableName = FnName->getName();
  8535. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8536. if (UnaryOp->getOpcode() == UO_AddrOf)
  8537. ActionIdx = 1; // If its an address-of operator, just remove it.
  8538. if (!PointeeTy->isIncompleteType() &&
  8539. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8540. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8541. // suggest an explicit length.
  8542. // If the function is defined as a builtin macro, do not show macro
  8543. // expansion.
  8544. SourceLocation SL = SizeOfArg->getExprLoc();
  8545. SourceRange DSR = Dest->getSourceRange();
  8546. SourceRange SSR = SizeOfArg->getSourceRange();
  8547. SourceManager &SM = getSourceManager();
  8548. if (SM.isMacroArgExpansion(SL)) {
  8549. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8550. SL = SM.getSpellingLoc(SL);
  8551. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8552. SM.getSpellingLoc(DSR.getEnd()));
  8553. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8554. SM.getSpellingLoc(SSR.getEnd()));
  8555. }
  8556. DiagRuntimeBehavior(SL, SizeOfArg,
  8557. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8558. << ReadableName
  8559. << PointeeTy
  8560. << DestTy
  8561. << DSR
  8562. << SSR);
  8563. DiagRuntimeBehavior(SL, SizeOfArg,
  8564. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8565. << ActionIdx
  8566. << SSR);
  8567. break;
  8568. }
  8569. }
  8570. // Also check for cases where the sizeof argument is the exact same
  8571. // type as the memory argument, and where it points to a user-defined
  8572. // record type.
  8573. if (SizeOfArgTy != QualType()) {
  8574. if (PointeeTy->isRecordType() &&
  8575. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8576. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8577. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8578. << FnName << SizeOfArgTy << ArgIdx
  8579. << PointeeTy << Dest->getSourceRange()
  8580. << LenExpr->getSourceRange());
  8581. break;
  8582. }
  8583. }
  8584. } else if (DestTy->isArrayType()) {
  8585. PointeeTy = DestTy;
  8586. }
  8587. if (PointeeTy == QualType())
  8588. continue;
  8589. // Always complain about dynamic classes.
  8590. bool IsContained;
  8591. if (const CXXRecordDecl *ContainedRD =
  8592. getContainedDynamicClass(PointeeTy, IsContained)) {
  8593. unsigned OperationType = 0;
  8594. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  8595. // "overwritten" if we're warning about the destination for any call
  8596. // but memcmp; otherwise a verb appropriate to the call.
  8597. if (ArgIdx != 0 || IsCmp) {
  8598. if (BId == Builtin::BImemcpy)
  8599. OperationType = 1;
  8600. else if(BId == Builtin::BImemmove)
  8601. OperationType = 2;
  8602. else if (IsCmp)
  8603. OperationType = 3;
  8604. }
  8605. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8606. PDiag(diag::warn_dyn_class_memaccess)
  8607. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  8608. << IsContained << ContainedRD << OperationType
  8609. << Call->getCallee()->getSourceRange());
  8610. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8611. BId != Builtin::BImemset)
  8612. DiagRuntimeBehavior(
  8613. Dest->getExprLoc(), Dest,
  8614. PDiag(diag::warn_arc_object_memaccess)
  8615. << ArgIdx << FnName << PointeeTy
  8616. << Call->getCallee()->getSourceRange());
  8617. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8618. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8619. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8620. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8621. PDiag(diag::warn_cstruct_memaccess)
  8622. << ArgIdx << FnName << PointeeTy << 0);
  8623. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8624. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8625. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8626. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8627. PDiag(diag::warn_cstruct_memaccess)
  8628. << ArgIdx << FnName << PointeeTy << 1);
  8629. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8630. } else {
  8631. continue;
  8632. }
  8633. } else
  8634. continue;
  8635. DiagRuntimeBehavior(
  8636. Dest->getExprLoc(), Dest,
  8637. PDiag(diag::note_bad_memaccess_silence)
  8638. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8639. break;
  8640. }
  8641. }
  8642. // A little helper routine: ignore addition and subtraction of integer literals.
  8643. // This intentionally does not ignore all integer constant expressions because
  8644. // we don't want to remove sizeof().
  8645. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8646. Ex = Ex->IgnoreParenCasts();
  8647. while (true) {
  8648. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8649. if (!BO || !BO->isAdditiveOp())
  8650. break;
  8651. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8652. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8653. if (isa<IntegerLiteral>(RHS))
  8654. Ex = LHS;
  8655. else if (isa<IntegerLiteral>(LHS))
  8656. Ex = RHS;
  8657. else
  8658. break;
  8659. }
  8660. return Ex;
  8661. }
  8662. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8663. ASTContext &Context) {
  8664. // Only handle constant-sized or VLAs, but not flexible members.
  8665. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8666. // Only issue the FIXIT for arrays of size > 1.
  8667. if (CAT->getSize().getSExtValue() <= 1)
  8668. return false;
  8669. } else if (!Ty->isVariableArrayType()) {
  8670. return false;
  8671. }
  8672. return true;
  8673. }
  8674. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8675. // be the size of the source, instead of the destination.
  8676. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8677. IdentifierInfo *FnName) {
  8678. // Don't crash if the user has the wrong number of arguments
  8679. unsigned NumArgs = Call->getNumArgs();
  8680. if ((NumArgs != 3) && (NumArgs != 4))
  8681. return;
  8682. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8683. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8684. const Expr *CompareWithSrc = nullptr;
  8685. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8686. Call->getBeginLoc(), Call->getRParenLoc()))
  8687. return;
  8688. // Look for 'strlcpy(dst, x, sizeof(x))'
  8689. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8690. CompareWithSrc = Ex;
  8691. else {
  8692. // Look for 'strlcpy(dst, x, strlen(x))'
  8693. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8694. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8695. SizeCall->getNumArgs() == 1)
  8696. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8697. }
  8698. }
  8699. if (!CompareWithSrc)
  8700. return;
  8701. // Determine if the argument to sizeof/strlen is equal to the source
  8702. // argument. In principle there's all kinds of things you could do
  8703. // here, for instance creating an == expression and evaluating it with
  8704. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8705. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8706. if (!SrcArgDRE)
  8707. return;
  8708. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8709. if (!CompareWithSrcDRE ||
  8710. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8711. return;
  8712. const Expr *OriginalSizeArg = Call->getArg(2);
  8713. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8714. << OriginalSizeArg->getSourceRange() << FnName;
  8715. // Output a FIXIT hint if the destination is an array (rather than a
  8716. // pointer to an array). This could be enhanced to handle some
  8717. // pointers if we know the actual size, like if DstArg is 'array+2'
  8718. // we could say 'sizeof(array)-2'.
  8719. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8720. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8721. return;
  8722. SmallString<128> sizeString;
  8723. llvm::raw_svector_ostream OS(sizeString);
  8724. OS << "sizeof(";
  8725. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8726. OS << ")";
  8727. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8728. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8729. OS.str());
  8730. }
  8731. /// Check if two expressions refer to the same declaration.
  8732. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8733. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8734. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8735. return D1->getDecl() == D2->getDecl();
  8736. return false;
  8737. }
  8738. static const Expr *getStrlenExprArg(const Expr *E) {
  8739. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8740. const FunctionDecl *FD = CE->getDirectCallee();
  8741. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8742. return nullptr;
  8743. return CE->getArg(0)->IgnoreParenCasts();
  8744. }
  8745. return nullptr;
  8746. }
  8747. // Warn on anti-patterns as the 'size' argument to strncat.
  8748. // The correct size argument should look like following:
  8749. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8750. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8751. IdentifierInfo *FnName) {
  8752. // Don't crash if the user has the wrong number of arguments.
  8753. if (CE->getNumArgs() < 3)
  8754. return;
  8755. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8756. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8757. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8758. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8759. CE->getRParenLoc()))
  8760. return;
  8761. // Identify common expressions, which are wrongly used as the size argument
  8762. // to strncat and may lead to buffer overflows.
  8763. unsigned PatternType = 0;
  8764. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8765. // - sizeof(dst)
  8766. if (referToTheSameDecl(SizeOfArg, DstArg))
  8767. PatternType = 1;
  8768. // - sizeof(src)
  8769. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8770. PatternType = 2;
  8771. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8772. if (BE->getOpcode() == BO_Sub) {
  8773. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8774. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8775. // - sizeof(dst) - strlen(dst)
  8776. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8777. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8778. PatternType = 1;
  8779. // - sizeof(src) - (anything)
  8780. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8781. PatternType = 2;
  8782. }
  8783. }
  8784. if (PatternType == 0)
  8785. return;
  8786. // Generate the diagnostic.
  8787. SourceLocation SL = LenArg->getBeginLoc();
  8788. SourceRange SR = LenArg->getSourceRange();
  8789. SourceManager &SM = getSourceManager();
  8790. // If the function is defined as a builtin macro, do not show macro expansion.
  8791. if (SM.isMacroArgExpansion(SL)) {
  8792. SL = SM.getSpellingLoc(SL);
  8793. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8794. SM.getSpellingLoc(SR.getEnd()));
  8795. }
  8796. // Check if the destination is an array (rather than a pointer to an array).
  8797. QualType DstTy = DstArg->getType();
  8798. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8799. Context);
  8800. if (!isKnownSizeArray) {
  8801. if (PatternType == 1)
  8802. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8803. else
  8804. Diag(SL, diag::warn_strncat_src_size) << SR;
  8805. return;
  8806. }
  8807. if (PatternType == 1)
  8808. Diag(SL, diag::warn_strncat_large_size) << SR;
  8809. else
  8810. Diag(SL, diag::warn_strncat_src_size) << SR;
  8811. SmallString<128> sizeString;
  8812. llvm::raw_svector_ostream OS(sizeString);
  8813. OS << "sizeof(";
  8814. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8815. OS << ") - ";
  8816. OS << "strlen(";
  8817. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8818. OS << ") - 1";
  8819. Diag(SL, diag::note_strncat_wrong_size)
  8820. << FixItHint::CreateReplacement(SR, OS.str());
  8821. }
  8822. void
  8823. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8824. SourceLocation ReturnLoc,
  8825. bool isObjCMethod,
  8826. const AttrVec *Attrs,
  8827. const FunctionDecl *FD) {
  8828. // Check if the return value is null but should not be.
  8829. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8830. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8831. CheckNonNullExpr(*this, RetValExp))
  8832. Diag(ReturnLoc, diag::warn_null_ret)
  8833. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8834. // C++11 [basic.stc.dynamic.allocation]p4:
  8835. // If an allocation function declared with a non-throwing
  8836. // exception-specification fails to allocate storage, it shall return
  8837. // a null pointer. Any other allocation function that fails to allocate
  8838. // storage shall indicate failure only by throwing an exception [...]
  8839. if (FD) {
  8840. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8841. if (Op == OO_New || Op == OO_Array_New) {
  8842. const FunctionProtoType *Proto
  8843. = FD->getType()->castAs<FunctionProtoType>();
  8844. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8845. CheckNonNullExpr(*this, RetValExp))
  8846. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8847. << FD << getLangOpts().CPlusPlus11;
  8848. }
  8849. }
  8850. }
  8851. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8852. /// Check for comparisons of floating point operands using != and ==.
  8853. /// Issue a warning if these are no self-comparisons, as they are not likely
  8854. /// to do what the programmer intended.
  8855. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8856. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8857. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8858. // Special case: check for x == x (which is OK).
  8859. // Do not emit warnings for such cases.
  8860. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8861. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8862. if (DRL->getDecl() == DRR->getDecl())
  8863. return;
  8864. // Special case: check for comparisons against literals that can be exactly
  8865. // represented by APFloat. In such cases, do not emit a warning. This
  8866. // is a heuristic: often comparison against such literals are used to
  8867. // detect if a value in a variable has not changed. This clearly can
  8868. // lead to false negatives.
  8869. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8870. if (FLL->isExact())
  8871. return;
  8872. } else
  8873. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8874. if (FLR->isExact())
  8875. return;
  8876. // Check for comparisons with builtin types.
  8877. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8878. if (CL->getBuiltinCallee())
  8879. return;
  8880. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8881. if (CR->getBuiltinCallee())
  8882. return;
  8883. // Emit the diagnostic.
  8884. Diag(Loc, diag::warn_floatingpoint_eq)
  8885. << LHS->getSourceRange() << RHS->getSourceRange();
  8886. }
  8887. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8888. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8889. namespace {
  8890. /// Structure recording the 'active' range of an integer-valued
  8891. /// expression.
  8892. struct IntRange {
  8893. /// The number of bits active in the int.
  8894. unsigned Width;
  8895. /// True if the int is known not to have negative values.
  8896. bool NonNegative;
  8897. IntRange(unsigned Width, bool NonNegative)
  8898. : Width(Width), NonNegative(NonNegative) {}
  8899. /// Returns the range of the bool type.
  8900. static IntRange forBoolType() {
  8901. return IntRange(1, true);
  8902. }
  8903. /// Returns the range of an opaque value of the given integral type.
  8904. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8905. return forValueOfCanonicalType(C,
  8906. T->getCanonicalTypeInternal().getTypePtr());
  8907. }
  8908. /// Returns the range of an opaque value of a canonical integral type.
  8909. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8910. assert(T->isCanonicalUnqualified());
  8911. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8912. T = VT->getElementType().getTypePtr();
  8913. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8914. T = CT->getElementType().getTypePtr();
  8915. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8916. T = AT->getValueType().getTypePtr();
  8917. if (!C.getLangOpts().CPlusPlus) {
  8918. // For enum types in C code, use the underlying datatype.
  8919. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8920. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8921. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8922. // For enum types in C++, use the known bit width of the enumerators.
  8923. EnumDecl *Enum = ET->getDecl();
  8924. // In C++11, enums can have a fixed underlying type. Use this type to
  8925. // compute the range.
  8926. if (Enum->isFixed()) {
  8927. return IntRange(C.getIntWidth(QualType(T, 0)),
  8928. !ET->isSignedIntegerOrEnumerationType());
  8929. }
  8930. unsigned NumPositive = Enum->getNumPositiveBits();
  8931. unsigned NumNegative = Enum->getNumNegativeBits();
  8932. if (NumNegative == 0)
  8933. return IntRange(NumPositive, true/*NonNegative*/);
  8934. else
  8935. return IntRange(std::max(NumPositive + 1, NumNegative),
  8936. false/*NonNegative*/);
  8937. }
  8938. const BuiltinType *BT = cast<BuiltinType>(T);
  8939. assert(BT->isInteger());
  8940. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8941. }
  8942. /// Returns the "target" range of a canonical integral type, i.e.
  8943. /// the range of values expressible in the type.
  8944. ///
  8945. /// This matches forValueOfCanonicalType except that enums have the
  8946. /// full range of their type, not the range of their enumerators.
  8947. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8948. assert(T->isCanonicalUnqualified());
  8949. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8950. T = VT->getElementType().getTypePtr();
  8951. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8952. T = CT->getElementType().getTypePtr();
  8953. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8954. T = AT->getValueType().getTypePtr();
  8955. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8956. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8957. const BuiltinType *BT = cast<BuiltinType>(T);
  8958. assert(BT->isInteger());
  8959. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8960. }
  8961. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8962. static IntRange join(IntRange L, IntRange R) {
  8963. return IntRange(std::max(L.Width, R.Width),
  8964. L.NonNegative && R.NonNegative);
  8965. }
  8966. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8967. static IntRange meet(IntRange L, IntRange R) {
  8968. return IntRange(std::min(L.Width, R.Width),
  8969. L.NonNegative || R.NonNegative);
  8970. }
  8971. };
  8972. } // namespace
  8973. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8974. unsigned MaxWidth) {
  8975. if (value.isSigned() && value.isNegative())
  8976. return IntRange(value.getMinSignedBits(), false);
  8977. if (value.getBitWidth() > MaxWidth)
  8978. value = value.trunc(MaxWidth);
  8979. // isNonNegative() just checks the sign bit without considering
  8980. // signedness.
  8981. return IntRange(value.getActiveBits(), true);
  8982. }
  8983. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8984. unsigned MaxWidth) {
  8985. if (result.isInt())
  8986. return GetValueRange(C, result.getInt(), MaxWidth);
  8987. if (result.isVector()) {
  8988. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8989. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8990. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8991. R = IntRange::join(R, El);
  8992. }
  8993. return R;
  8994. }
  8995. if (result.isComplexInt()) {
  8996. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8997. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8998. return IntRange::join(R, I);
  8999. }
  9000. // This can happen with lossless casts to intptr_t of "based" lvalues.
  9001. // Assume it might use arbitrary bits.
  9002. // FIXME: The only reason we need to pass the type in here is to get
  9003. // the sign right on this one case. It would be nice if APValue
  9004. // preserved this.
  9005. assert(result.isLValue() || result.isAddrLabelDiff());
  9006. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  9007. }
  9008. static QualType GetExprType(const Expr *E) {
  9009. QualType Ty = E->getType();
  9010. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  9011. Ty = AtomicRHS->getValueType();
  9012. return Ty;
  9013. }
  9014. /// Pseudo-evaluate the given integer expression, estimating the
  9015. /// range of values it might take.
  9016. ///
  9017. /// \param MaxWidth - the width to which the value will be truncated
  9018. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
  9019. bool InConstantContext) {
  9020. E = E->IgnoreParens();
  9021. // Try a full evaluation first.
  9022. Expr::EvalResult result;
  9023. if (E->EvaluateAsRValue(result, C, InConstantContext))
  9024. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  9025. // I think we only want to look through implicit casts here; if the
  9026. // user has an explicit widening cast, we should treat the value as
  9027. // being of the new, wider type.
  9028. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  9029. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  9030. return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
  9031. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  9032. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  9033. CE->getCastKind() == CK_BooleanToSignedIntegral;
  9034. // Assume that non-integer casts can span the full range of the type.
  9035. if (!isIntegerCast)
  9036. return OutputTypeRange;
  9037. IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
  9038. std::min(MaxWidth, OutputTypeRange.Width),
  9039. InConstantContext);
  9040. // Bail out if the subexpr's range is as wide as the cast type.
  9041. if (SubRange.Width >= OutputTypeRange.Width)
  9042. return OutputTypeRange;
  9043. // Otherwise, we take the smaller width, and we're non-negative if
  9044. // either the output type or the subexpr is.
  9045. return IntRange(SubRange.Width,
  9046. SubRange.NonNegative || OutputTypeRange.NonNegative);
  9047. }
  9048. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  9049. // If we can fold the condition, just take that operand.
  9050. bool CondResult;
  9051. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  9052. return GetExprRange(C,
  9053. CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
  9054. MaxWidth, InConstantContext);
  9055. // Otherwise, conservatively merge.
  9056. IntRange L =
  9057. GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
  9058. IntRange R =
  9059. GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
  9060. return IntRange::join(L, R);
  9061. }
  9062. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  9063. switch (BO->getOpcode()) {
  9064. case BO_Cmp:
  9065. llvm_unreachable("builtin <=> should have class type");
  9066. // Boolean-valued operations are single-bit and positive.
  9067. case BO_LAnd:
  9068. case BO_LOr:
  9069. case BO_LT:
  9070. case BO_GT:
  9071. case BO_LE:
  9072. case BO_GE:
  9073. case BO_EQ:
  9074. case BO_NE:
  9075. return IntRange::forBoolType();
  9076. // The type of the assignments is the type of the LHS, so the RHS
  9077. // is not necessarily the same type.
  9078. case BO_MulAssign:
  9079. case BO_DivAssign:
  9080. case BO_RemAssign:
  9081. case BO_AddAssign:
  9082. case BO_SubAssign:
  9083. case BO_XorAssign:
  9084. case BO_OrAssign:
  9085. // TODO: bitfields?
  9086. return IntRange::forValueOfType(C, GetExprType(E));
  9087. // Simple assignments just pass through the RHS, which will have
  9088. // been coerced to the LHS type.
  9089. case BO_Assign:
  9090. // TODO: bitfields?
  9091. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9092. // Operations with opaque sources are black-listed.
  9093. case BO_PtrMemD:
  9094. case BO_PtrMemI:
  9095. return IntRange::forValueOfType(C, GetExprType(E));
  9096. // Bitwise-and uses the *infinum* of the two source ranges.
  9097. case BO_And:
  9098. case BO_AndAssign:
  9099. return IntRange::meet(
  9100. GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
  9101. GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
  9102. // Left shift gets black-listed based on a judgement call.
  9103. case BO_Shl:
  9104. // ...except that we want to treat '1 << (blah)' as logically
  9105. // positive. It's an important idiom.
  9106. if (IntegerLiteral *I
  9107. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  9108. if (I->getValue() == 1) {
  9109. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  9110. return IntRange(R.Width, /*NonNegative*/ true);
  9111. }
  9112. }
  9113. LLVM_FALLTHROUGH;
  9114. case BO_ShlAssign:
  9115. return IntRange::forValueOfType(C, GetExprType(E));
  9116. // Right shift by a constant can narrow its left argument.
  9117. case BO_Shr:
  9118. case BO_ShrAssign: {
  9119. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9120. // If the shift amount is a positive constant, drop the width by
  9121. // that much.
  9122. llvm::APSInt shift;
  9123. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  9124. shift.isNonNegative()) {
  9125. unsigned zext = shift.getZExtValue();
  9126. if (zext >= L.Width)
  9127. L.Width = (L.NonNegative ? 0 : 1);
  9128. else
  9129. L.Width -= zext;
  9130. }
  9131. return L;
  9132. }
  9133. // Comma acts as its right operand.
  9134. case BO_Comma:
  9135. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9136. // Black-list pointer subtractions.
  9137. case BO_Sub:
  9138. if (BO->getLHS()->getType()->isPointerType())
  9139. return IntRange::forValueOfType(C, GetExprType(E));
  9140. break;
  9141. // The width of a division result is mostly determined by the size
  9142. // of the LHS.
  9143. case BO_Div: {
  9144. // Don't 'pre-truncate' the operands.
  9145. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9146. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9147. // If the divisor is constant, use that.
  9148. llvm::APSInt divisor;
  9149. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  9150. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  9151. if (log2 >= L.Width)
  9152. L.Width = (L.NonNegative ? 0 : 1);
  9153. else
  9154. L.Width = std::min(L.Width - log2, MaxWidth);
  9155. return L;
  9156. }
  9157. // Otherwise, just use the LHS's width.
  9158. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9159. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  9160. }
  9161. // The result of a remainder can't be larger than the result of
  9162. // either side.
  9163. case BO_Rem: {
  9164. // Don't 'pre-truncate' the operands.
  9165. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9166. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9167. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9168. IntRange meet = IntRange::meet(L, R);
  9169. meet.Width = std::min(meet.Width, MaxWidth);
  9170. return meet;
  9171. }
  9172. // The default behavior is okay for these.
  9173. case BO_Mul:
  9174. case BO_Add:
  9175. case BO_Xor:
  9176. case BO_Or:
  9177. break;
  9178. }
  9179. // The default case is to treat the operation as if it were closed
  9180. // on the narrowest type that encompasses both operands.
  9181. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9182. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9183. return IntRange::join(L, R);
  9184. }
  9185. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  9186. switch (UO->getOpcode()) {
  9187. // Boolean-valued operations are white-listed.
  9188. case UO_LNot:
  9189. return IntRange::forBoolType();
  9190. // Operations with opaque sources are black-listed.
  9191. case UO_Deref:
  9192. case UO_AddrOf: // should be impossible
  9193. return IntRange::forValueOfType(C, GetExprType(E));
  9194. default:
  9195. return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
  9196. }
  9197. }
  9198. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  9199. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
  9200. if (const auto *BitField = E->getSourceBitField())
  9201. return IntRange(BitField->getBitWidthValue(C),
  9202. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  9203. return IntRange::forValueOfType(C, GetExprType(E));
  9204. }
  9205. static IntRange GetExprRange(ASTContext &C, const Expr *E,
  9206. bool InConstantContext) {
  9207. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
  9208. }
  9209. /// Checks whether the given value, which currently has the given
  9210. /// source semantics, has the same value when coerced through the
  9211. /// target semantics.
  9212. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  9213. const llvm::fltSemantics &Src,
  9214. const llvm::fltSemantics &Tgt) {
  9215. llvm::APFloat truncated = value;
  9216. bool ignored;
  9217. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9218. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9219. return truncated.bitwiseIsEqual(value);
  9220. }
  9221. /// Checks whether the given value, which currently has the given
  9222. /// source semantics, has the same value when coerced through the
  9223. /// target semantics.
  9224. ///
  9225. /// The value might be a vector of floats (or a complex number).
  9226. static bool IsSameFloatAfterCast(const APValue &value,
  9227. const llvm::fltSemantics &Src,
  9228. const llvm::fltSemantics &Tgt) {
  9229. if (value.isFloat())
  9230. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  9231. if (value.isVector()) {
  9232. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  9233. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  9234. return false;
  9235. return true;
  9236. }
  9237. assert(value.isComplexFloat());
  9238. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  9239. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  9240. }
  9241. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
  9242. bool IsListInit = false);
  9243. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  9244. // Suppress cases where we are comparing against an enum constant.
  9245. if (const DeclRefExpr *DR =
  9246. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  9247. if (isa<EnumConstantDecl>(DR->getDecl()))
  9248. return true;
  9249. // Suppress cases where the value is expanded from a macro, unless that macro
  9250. // is how a language represents a boolean literal. This is the case in both C
  9251. // and Objective-C.
  9252. SourceLocation BeginLoc = E->getBeginLoc();
  9253. if (BeginLoc.isMacroID()) {
  9254. StringRef MacroName = Lexer::getImmediateMacroName(
  9255. BeginLoc, S.getSourceManager(), S.getLangOpts());
  9256. return MacroName != "YES" && MacroName != "NO" &&
  9257. MacroName != "true" && MacroName != "false";
  9258. }
  9259. return false;
  9260. }
  9261. static bool isKnownToHaveUnsignedValue(Expr *E) {
  9262. return E->getType()->isIntegerType() &&
  9263. (!E->getType()->isSignedIntegerType() ||
  9264. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  9265. }
  9266. namespace {
  9267. /// The promoted range of values of a type. In general this has the
  9268. /// following structure:
  9269. ///
  9270. /// |-----------| . . . |-----------|
  9271. /// ^ ^ ^ ^
  9272. /// Min HoleMin HoleMax Max
  9273. ///
  9274. /// ... where there is only a hole if a signed type is promoted to unsigned
  9275. /// (in which case Min and Max are the smallest and largest representable
  9276. /// values).
  9277. struct PromotedRange {
  9278. // Min, or HoleMax if there is a hole.
  9279. llvm::APSInt PromotedMin;
  9280. // Max, or HoleMin if there is a hole.
  9281. llvm::APSInt PromotedMax;
  9282. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  9283. if (R.Width == 0)
  9284. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  9285. else if (R.Width >= BitWidth && !Unsigned) {
  9286. // Promotion made the type *narrower*. This happens when promoting
  9287. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  9288. // Treat all values of 'signed int' as being in range for now.
  9289. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  9290. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  9291. } else {
  9292. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  9293. .extOrTrunc(BitWidth);
  9294. PromotedMin.setIsUnsigned(Unsigned);
  9295. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  9296. .extOrTrunc(BitWidth);
  9297. PromotedMax.setIsUnsigned(Unsigned);
  9298. }
  9299. }
  9300. // Determine whether this range is contiguous (has no hole).
  9301. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  9302. // Where a constant value is within the range.
  9303. enum ComparisonResult {
  9304. LT = 0x1,
  9305. LE = 0x2,
  9306. GT = 0x4,
  9307. GE = 0x8,
  9308. EQ = 0x10,
  9309. NE = 0x20,
  9310. InRangeFlag = 0x40,
  9311. Less = LE | LT | NE,
  9312. Min = LE | InRangeFlag,
  9313. InRange = InRangeFlag,
  9314. Max = GE | InRangeFlag,
  9315. Greater = GE | GT | NE,
  9316. OnlyValue = LE | GE | EQ | InRangeFlag,
  9317. InHole = NE
  9318. };
  9319. ComparisonResult compare(const llvm::APSInt &Value) const {
  9320. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  9321. Value.isUnsigned() == PromotedMin.isUnsigned());
  9322. if (!isContiguous()) {
  9323. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  9324. if (Value.isMinValue()) return Min;
  9325. if (Value.isMaxValue()) return Max;
  9326. if (Value >= PromotedMin) return InRange;
  9327. if (Value <= PromotedMax) return InRange;
  9328. return InHole;
  9329. }
  9330. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  9331. case -1: return Less;
  9332. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  9333. case 1:
  9334. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  9335. case -1: return InRange;
  9336. case 0: return Max;
  9337. case 1: return Greater;
  9338. }
  9339. }
  9340. llvm_unreachable("impossible compare result");
  9341. }
  9342. static llvm::Optional<StringRef>
  9343. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  9344. if (Op == BO_Cmp) {
  9345. ComparisonResult LTFlag = LT, GTFlag = GT;
  9346. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  9347. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  9348. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  9349. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  9350. return llvm::None;
  9351. }
  9352. ComparisonResult TrueFlag, FalseFlag;
  9353. if (Op == BO_EQ) {
  9354. TrueFlag = EQ;
  9355. FalseFlag = NE;
  9356. } else if (Op == BO_NE) {
  9357. TrueFlag = NE;
  9358. FalseFlag = EQ;
  9359. } else {
  9360. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  9361. TrueFlag = LT;
  9362. FalseFlag = GE;
  9363. } else {
  9364. TrueFlag = GT;
  9365. FalseFlag = LE;
  9366. }
  9367. if (Op == BO_GE || Op == BO_LE)
  9368. std::swap(TrueFlag, FalseFlag);
  9369. }
  9370. if (R & TrueFlag)
  9371. return StringRef("true");
  9372. if (R & FalseFlag)
  9373. return StringRef("false");
  9374. return llvm::None;
  9375. }
  9376. };
  9377. }
  9378. static bool HasEnumType(Expr *E) {
  9379. // Strip off implicit integral promotions.
  9380. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9381. if (ICE->getCastKind() != CK_IntegralCast &&
  9382. ICE->getCastKind() != CK_NoOp)
  9383. break;
  9384. E = ICE->getSubExpr();
  9385. }
  9386. return E->getType()->isEnumeralType();
  9387. }
  9388. static int classifyConstantValue(Expr *Constant) {
  9389. // The values of this enumeration are used in the diagnostics
  9390. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  9391. enum ConstantValueKind {
  9392. Miscellaneous = 0,
  9393. LiteralTrue,
  9394. LiteralFalse
  9395. };
  9396. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  9397. return BL->getValue() ? ConstantValueKind::LiteralTrue
  9398. : ConstantValueKind::LiteralFalse;
  9399. return ConstantValueKind::Miscellaneous;
  9400. }
  9401. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  9402. Expr *Constant, Expr *Other,
  9403. const llvm::APSInt &Value,
  9404. bool RhsConstant) {
  9405. if (S.inTemplateInstantiation())
  9406. return false;
  9407. Expr *OriginalOther = Other;
  9408. Constant = Constant->IgnoreParenImpCasts();
  9409. Other = Other->IgnoreParenImpCasts();
  9410. // Suppress warnings on tautological comparisons between values of the same
  9411. // enumeration type. There are only two ways we could warn on this:
  9412. // - If the constant is outside the range of representable values of
  9413. // the enumeration. In such a case, we should warn about the cast
  9414. // to enumeration type, not about the comparison.
  9415. // - If the constant is the maximum / minimum in-range value. For an
  9416. // enumeratin type, such comparisons can be meaningful and useful.
  9417. if (Constant->getType()->isEnumeralType() &&
  9418. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  9419. return false;
  9420. // TODO: Investigate using GetExprRange() to get tighter bounds
  9421. // on the bit ranges.
  9422. QualType OtherT = Other->getType();
  9423. if (const auto *AT = OtherT->getAs<AtomicType>())
  9424. OtherT = AT->getValueType();
  9425. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  9426. // Special case for ObjC BOOL on targets where its a typedef for a signed char
  9427. // (Namely, macOS).
  9428. bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
  9429. S.NSAPIObj->isObjCBOOLType(OtherT) &&
  9430. OtherT->isSpecificBuiltinType(BuiltinType::SChar);
  9431. // Whether we're treating Other as being a bool because of the form of
  9432. // expression despite it having another type (typically 'int' in C).
  9433. bool OtherIsBooleanDespiteType =
  9434. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  9435. if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
  9436. OtherRange = IntRange::forBoolType();
  9437. // Determine the promoted range of the other type and see if a comparison of
  9438. // the constant against that range is tautological.
  9439. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  9440. Value.isUnsigned());
  9441. auto Cmp = OtherPromotedRange.compare(Value);
  9442. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9443. if (!Result)
  9444. return false;
  9445. // Suppress the diagnostic for an in-range comparison if the constant comes
  9446. // from a macro or enumerator. We don't want to diagnose
  9447. //
  9448. // some_long_value <= INT_MAX
  9449. //
  9450. // when sizeof(int) == sizeof(long).
  9451. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9452. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9453. return false;
  9454. // If this is a comparison to an enum constant, include that
  9455. // constant in the diagnostic.
  9456. const EnumConstantDecl *ED = nullptr;
  9457. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9458. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9459. // Should be enough for uint128 (39 decimal digits)
  9460. SmallString<64> PrettySourceValue;
  9461. llvm::raw_svector_ostream OS(PrettySourceValue);
  9462. if (ED) {
  9463. OS << '\'' << *ED << "' (" << Value << ")";
  9464. } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
  9465. Constant->IgnoreParenImpCasts())) {
  9466. OS << (BL->getValue() ? "YES" : "NO");
  9467. } else {
  9468. OS << Value;
  9469. }
  9470. if (IsObjCSignedCharBool) {
  9471. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9472. S.PDiag(diag::warn_tautological_compare_objc_bool)
  9473. << OS.str() << *Result);
  9474. return true;
  9475. }
  9476. // FIXME: We use a somewhat different formatting for the in-range cases and
  9477. // cases involving boolean values for historical reasons. We should pick a
  9478. // consistent way of presenting these diagnostics.
  9479. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9480. S.DiagRuntimeBehavior(
  9481. E->getOperatorLoc(), E,
  9482. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9483. : diag::warn_tautological_bool_compare)
  9484. << OS.str() << classifyConstantValue(Constant) << OtherT
  9485. << OtherIsBooleanDespiteType << *Result
  9486. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9487. } else {
  9488. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9489. ? (HasEnumType(OriginalOther)
  9490. ? diag::warn_unsigned_enum_always_true_comparison
  9491. : diag::warn_unsigned_always_true_comparison)
  9492. : diag::warn_tautological_constant_compare;
  9493. S.Diag(E->getOperatorLoc(), Diag)
  9494. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9495. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9496. }
  9497. return true;
  9498. }
  9499. /// Analyze the operands of the given comparison. Implements the
  9500. /// fallback case from AnalyzeComparison.
  9501. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9502. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9503. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9504. }
  9505. /// Implements -Wsign-compare.
  9506. ///
  9507. /// \param E the binary operator to check for warnings
  9508. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9509. // The type the comparison is being performed in.
  9510. QualType T = E->getLHS()->getType();
  9511. // Only analyze comparison operators where both sides have been converted to
  9512. // the same type.
  9513. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9514. return AnalyzeImpConvsInComparison(S, E);
  9515. // Don't analyze value-dependent comparisons directly.
  9516. if (E->isValueDependent())
  9517. return AnalyzeImpConvsInComparison(S, E);
  9518. Expr *LHS = E->getLHS();
  9519. Expr *RHS = E->getRHS();
  9520. if (T->isIntegralType(S.Context)) {
  9521. llvm::APSInt RHSValue;
  9522. llvm::APSInt LHSValue;
  9523. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9524. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9525. // We don't care about expressions whose result is a constant.
  9526. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9527. return AnalyzeImpConvsInComparison(S, E);
  9528. // We only care about expressions where just one side is literal
  9529. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9530. // Is the constant on the RHS or LHS?
  9531. const bool RhsConstant = IsRHSIntegralLiteral;
  9532. Expr *Const = RhsConstant ? RHS : LHS;
  9533. Expr *Other = RhsConstant ? LHS : RHS;
  9534. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9535. // Check whether an integer constant comparison results in a value
  9536. // of 'true' or 'false'.
  9537. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9538. return AnalyzeImpConvsInComparison(S, E);
  9539. }
  9540. }
  9541. if (!T->hasUnsignedIntegerRepresentation()) {
  9542. // We don't do anything special if this isn't an unsigned integral
  9543. // comparison: we're only interested in integral comparisons, and
  9544. // signed comparisons only happen in cases we don't care to warn about.
  9545. return AnalyzeImpConvsInComparison(S, E);
  9546. }
  9547. LHS = LHS->IgnoreParenImpCasts();
  9548. RHS = RHS->IgnoreParenImpCasts();
  9549. if (!S.getLangOpts().CPlusPlus) {
  9550. // Avoid warning about comparison of integers with different signs when
  9551. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9552. // the type of `E`.
  9553. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9554. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9555. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9556. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9557. }
  9558. // Check to see if one of the (unmodified) operands is of different
  9559. // signedness.
  9560. Expr *signedOperand, *unsignedOperand;
  9561. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9562. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9563. "unsigned comparison between two signed integer expressions?");
  9564. signedOperand = LHS;
  9565. unsignedOperand = RHS;
  9566. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9567. signedOperand = RHS;
  9568. unsignedOperand = LHS;
  9569. } else {
  9570. return AnalyzeImpConvsInComparison(S, E);
  9571. }
  9572. // Otherwise, calculate the effective range of the signed operand.
  9573. IntRange signedRange =
  9574. GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
  9575. // Go ahead and analyze implicit conversions in the operands. Note
  9576. // that we skip the implicit conversions on both sides.
  9577. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9578. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9579. // If the signed range is non-negative, -Wsign-compare won't fire.
  9580. if (signedRange.NonNegative)
  9581. return;
  9582. // For (in)equality comparisons, if the unsigned operand is a
  9583. // constant which cannot collide with a overflowed signed operand,
  9584. // then reinterpreting the signed operand as unsigned will not
  9585. // change the result of the comparison.
  9586. if (E->isEqualityOp()) {
  9587. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9588. IntRange unsignedRange =
  9589. GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
  9590. // We should never be unable to prove that the unsigned operand is
  9591. // non-negative.
  9592. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9593. if (unsignedRange.Width < comparisonWidth)
  9594. return;
  9595. }
  9596. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9597. S.PDiag(diag::warn_mixed_sign_comparison)
  9598. << LHS->getType() << RHS->getType()
  9599. << LHS->getSourceRange() << RHS->getSourceRange());
  9600. }
  9601. /// Analyzes an attempt to assign the given value to a bitfield.
  9602. ///
  9603. /// Returns true if there was something fishy about the attempt.
  9604. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9605. SourceLocation InitLoc) {
  9606. assert(Bitfield->isBitField());
  9607. if (Bitfield->isInvalidDecl())
  9608. return false;
  9609. // White-list bool bitfields.
  9610. QualType BitfieldType = Bitfield->getType();
  9611. if (BitfieldType->isBooleanType())
  9612. return false;
  9613. if (BitfieldType->isEnumeralType()) {
  9614. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9615. // If the underlying enum type was not explicitly specified as an unsigned
  9616. // type and the enum contain only positive values, MSVC++ will cause an
  9617. // inconsistency by storing this as a signed type.
  9618. if (S.getLangOpts().CPlusPlus11 &&
  9619. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9620. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9621. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9622. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9623. << BitfieldEnumDecl->getNameAsString();
  9624. }
  9625. }
  9626. if (Bitfield->getType()->isBooleanType())
  9627. return false;
  9628. // Ignore value- or type-dependent expressions.
  9629. if (Bitfield->getBitWidth()->isValueDependent() ||
  9630. Bitfield->getBitWidth()->isTypeDependent() ||
  9631. Init->isValueDependent() ||
  9632. Init->isTypeDependent())
  9633. return false;
  9634. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9635. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9636. Expr::EvalResult Result;
  9637. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  9638. Expr::SE_AllowSideEffects)) {
  9639. // The RHS is not constant. If the RHS has an enum type, make sure the
  9640. // bitfield is wide enough to hold all the values of the enum without
  9641. // truncation.
  9642. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9643. EnumDecl *ED = EnumTy->getDecl();
  9644. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9645. // Enum types are implicitly signed on Windows, so check if there are any
  9646. // negative enumerators to see if the enum was intended to be signed or
  9647. // not.
  9648. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9649. // Check for surprising sign changes when assigning enum values to a
  9650. // bitfield of different signedness. If the bitfield is signed and we
  9651. // have exactly the right number of bits to store this unsigned enum,
  9652. // suggest changing the enum to an unsigned type. This typically happens
  9653. // on Windows where unfixed enums always use an underlying type of 'int'.
  9654. unsigned DiagID = 0;
  9655. if (SignedEnum && !SignedBitfield) {
  9656. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9657. } else if (SignedBitfield && !SignedEnum &&
  9658. ED->getNumPositiveBits() == FieldWidth) {
  9659. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9660. }
  9661. if (DiagID) {
  9662. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9663. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9664. SourceRange TypeRange =
  9665. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9666. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9667. << SignedEnum << TypeRange;
  9668. }
  9669. // Compute the required bitwidth. If the enum has negative values, we need
  9670. // one more bit than the normal number of positive bits to represent the
  9671. // sign bit.
  9672. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9673. ED->getNumNegativeBits())
  9674. : ED->getNumPositiveBits();
  9675. // Check the bitwidth.
  9676. if (BitsNeeded > FieldWidth) {
  9677. Expr *WidthExpr = Bitfield->getBitWidth();
  9678. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9679. << Bitfield << ED;
  9680. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9681. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9682. }
  9683. }
  9684. return false;
  9685. }
  9686. llvm::APSInt Value = Result.Val.getInt();
  9687. unsigned OriginalWidth = Value.getBitWidth();
  9688. if (!Value.isSigned() || Value.isNegative())
  9689. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9690. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9691. OriginalWidth = Value.getMinSignedBits();
  9692. if (OriginalWidth <= FieldWidth)
  9693. return false;
  9694. // Compute the value which the bitfield will contain.
  9695. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9696. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9697. // Check whether the stored value is equal to the original value.
  9698. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9699. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9700. return false;
  9701. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9702. // therefore don't strictly fit into a signed bitfield of width 1.
  9703. if (FieldWidth == 1 && Value == 1)
  9704. return false;
  9705. std::string PrettyValue = Value.toString(10);
  9706. std::string PrettyTrunc = TruncatedValue.toString(10);
  9707. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9708. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9709. << Init->getSourceRange();
  9710. return true;
  9711. }
  9712. /// Analyze the given simple or compound assignment for warning-worthy
  9713. /// operations.
  9714. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9715. // Just recurse on the LHS.
  9716. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9717. // We want to recurse on the RHS as normal unless we're assigning to
  9718. // a bitfield.
  9719. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9720. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9721. E->getOperatorLoc())) {
  9722. // Recurse, ignoring any implicit conversions on the RHS.
  9723. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9724. E->getOperatorLoc());
  9725. }
  9726. }
  9727. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9728. // Diagnose implicitly sequentially-consistent atomic assignment.
  9729. if (E->getLHS()->getType()->isAtomicType())
  9730. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9731. }
  9732. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9733. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9734. SourceLocation CContext, unsigned diag,
  9735. bool pruneControlFlow = false) {
  9736. if (pruneControlFlow) {
  9737. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9738. S.PDiag(diag)
  9739. << SourceType << T << E->getSourceRange()
  9740. << SourceRange(CContext));
  9741. return;
  9742. }
  9743. S.Diag(E->getExprLoc(), diag)
  9744. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9745. }
  9746. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9747. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9748. SourceLocation CContext,
  9749. unsigned diag, bool pruneControlFlow = false) {
  9750. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9751. }
  9752. static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
  9753. return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
  9754. S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
  9755. }
  9756. static void adornObjCBoolConversionDiagWithTernaryFixit(
  9757. Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
  9758. Expr *Ignored = SourceExpr->IgnoreImplicit();
  9759. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
  9760. Ignored = OVE->getSourceExpr();
  9761. bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
  9762. isa<BinaryOperator>(Ignored) ||
  9763. isa<CXXOperatorCallExpr>(Ignored);
  9764. SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
  9765. if (NeedsParens)
  9766. Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
  9767. << FixItHint::CreateInsertion(EndLoc, ")");
  9768. Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
  9769. }
  9770. /// Diagnose an implicit cast from a floating point value to an integer value.
  9771. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9772. SourceLocation CContext) {
  9773. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9774. const bool PruneWarnings = S.inTemplateInstantiation();
  9775. Expr *InnerE = E->IgnoreParenImpCasts();
  9776. // We also want to warn on, e.g., "int i = -1.234"
  9777. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9778. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9779. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9780. const bool IsLiteral =
  9781. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9782. llvm::APFloat Value(0.0);
  9783. bool IsConstant =
  9784. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9785. if (!IsConstant) {
  9786. if (isObjCSignedCharBool(S, T)) {
  9787. return adornObjCBoolConversionDiagWithTernaryFixit(
  9788. S, E,
  9789. S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
  9790. << E->getType());
  9791. }
  9792. return DiagnoseImpCast(S, E, T, CContext,
  9793. diag::warn_impcast_float_integer, PruneWarnings);
  9794. }
  9795. bool isExact = false;
  9796. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9797. T->hasUnsignedIntegerRepresentation());
  9798. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9799. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9800. // FIXME: Force the precision of the source value down so we don't print
  9801. // digits which are usually useless (we don't really care here if we
  9802. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9803. // would automatically print the shortest representation, but it's a bit
  9804. // tricky to implement.
  9805. SmallString<16> PrettySourceValue;
  9806. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9807. precision = (precision * 59 + 195) / 196;
  9808. Value.toString(PrettySourceValue, precision);
  9809. if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
  9810. return adornObjCBoolConversionDiagWithTernaryFixit(
  9811. S, E,
  9812. S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
  9813. << PrettySourceValue);
  9814. }
  9815. if (Result == llvm::APFloat::opOK && isExact) {
  9816. if (IsLiteral) return;
  9817. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9818. PruneWarnings);
  9819. }
  9820. // Conversion of a floating-point value to a non-bool integer where the
  9821. // integral part cannot be represented by the integer type is undefined.
  9822. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9823. return DiagnoseImpCast(
  9824. S, E, T, CContext,
  9825. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9826. : diag::warn_impcast_float_to_integer_out_of_range,
  9827. PruneWarnings);
  9828. unsigned DiagID = 0;
  9829. if (IsLiteral) {
  9830. // Warn on floating point literal to integer.
  9831. DiagID = diag::warn_impcast_literal_float_to_integer;
  9832. } else if (IntegerValue == 0) {
  9833. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9834. return DiagnoseImpCast(S, E, T, CContext,
  9835. diag::warn_impcast_float_integer, PruneWarnings);
  9836. }
  9837. // Warn on non-zero to zero conversion.
  9838. DiagID = diag::warn_impcast_float_to_integer_zero;
  9839. } else {
  9840. if (IntegerValue.isUnsigned()) {
  9841. if (!IntegerValue.isMaxValue()) {
  9842. return DiagnoseImpCast(S, E, T, CContext,
  9843. diag::warn_impcast_float_integer, PruneWarnings);
  9844. }
  9845. } else { // IntegerValue.isSigned()
  9846. if (!IntegerValue.isMaxSignedValue() &&
  9847. !IntegerValue.isMinSignedValue()) {
  9848. return DiagnoseImpCast(S, E, T, CContext,
  9849. diag::warn_impcast_float_integer, PruneWarnings);
  9850. }
  9851. }
  9852. // Warn on evaluatable floating point expression to integer conversion.
  9853. DiagID = diag::warn_impcast_float_to_integer;
  9854. }
  9855. SmallString<16> PrettyTargetValue;
  9856. if (IsBool)
  9857. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9858. else
  9859. IntegerValue.toString(PrettyTargetValue);
  9860. if (PruneWarnings) {
  9861. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9862. S.PDiag(DiagID)
  9863. << E->getType() << T.getUnqualifiedType()
  9864. << PrettySourceValue << PrettyTargetValue
  9865. << E->getSourceRange() << SourceRange(CContext));
  9866. } else {
  9867. S.Diag(E->getExprLoc(), DiagID)
  9868. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9869. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9870. }
  9871. }
  9872. /// Analyze the given compound assignment for the possible losing of
  9873. /// floating-point precision.
  9874. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9875. assert(isa<CompoundAssignOperator>(E) &&
  9876. "Must be compound assignment operation");
  9877. // Recurse on the LHS and RHS in here
  9878. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9879. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9880. if (E->getLHS()->getType()->isAtomicType())
  9881. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9882. // Now check the outermost expression
  9883. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9884. const auto *RBT = cast<CompoundAssignOperator>(E)
  9885. ->getComputationResultType()
  9886. ->getAs<BuiltinType>();
  9887. // The below checks assume source is floating point.
  9888. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9889. // If source is floating point but target is an integer.
  9890. if (ResultBT->isInteger())
  9891. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  9892. E->getExprLoc(), diag::warn_impcast_float_integer);
  9893. if (!ResultBT->isFloatingPoint())
  9894. return;
  9895. // If both source and target are floating points, warn about losing precision.
  9896. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9897. QualType(ResultBT, 0), QualType(RBT, 0));
  9898. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9899. // warn about dropping FP rank.
  9900. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9901. diag::warn_impcast_float_result_precision);
  9902. }
  9903. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9904. IntRange Range) {
  9905. if (!Range.Width) return "0";
  9906. llvm::APSInt ValueInRange = Value;
  9907. ValueInRange.setIsSigned(!Range.NonNegative);
  9908. ValueInRange = ValueInRange.trunc(Range.Width);
  9909. return ValueInRange.toString(10);
  9910. }
  9911. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9912. if (!isa<ImplicitCastExpr>(Ex))
  9913. return false;
  9914. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9915. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9916. const Type *Source =
  9917. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9918. if (Target->isDependentType())
  9919. return false;
  9920. const BuiltinType *FloatCandidateBT =
  9921. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9922. const Type *BoolCandidateType = ToBool ? Target : Source;
  9923. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9924. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9925. }
  9926. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9927. SourceLocation CC) {
  9928. unsigned NumArgs = TheCall->getNumArgs();
  9929. for (unsigned i = 0; i < NumArgs; ++i) {
  9930. Expr *CurrA = TheCall->getArg(i);
  9931. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9932. continue;
  9933. bool IsSwapped = ((i > 0) &&
  9934. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9935. IsSwapped |= ((i < (NumArgs - 1)) &&
  9936. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9937. if (IsSwapped) {
  9938. // Warn on this floating-point to bool conversion.
  9939. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9940. CurrA->getType(), CC,
  9941. diag::warn_impcast_floating_point_to_bool);
  9942. }
  9943. }
  9944. }
  9945. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9946. SourceLocation CC) {
  9947. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9948. E->getExprLoc()))
  9949. return;
  9950. // Don't warn on functions which have return type nullptr_t.
  9951. if (isa<CallExpr>(E))
  9952. return;
  9953. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9954. const Expr::NullPointerConstantKind NullKind =
  9955. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9956. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9957. return;
  9958. // Return if target type is a safe conversion.
  9959. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9960. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9961. return;
  9962. SourceLocation Loc = E->getSourceRange().getBegin();
  9963. // Venture through the macro stacks to get to the source of macro arguments.
  9964. // The new location is a better location than the complete location that was
  9965. // passed in.
  9966. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9967. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9968. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9969. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9970. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9971. Loc, S.SourceMgr, S.getLangOpts());
  9972. if (MacroName == "NULL")
  9973. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9974. }
  9975. // Only warn if the null and context location are in the same macro expansion.
  9976. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9977. return;
  9978. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9979. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9980. << FixItHint::CreateReplacement(Loc,
  9981. S.getFixItZeroLiteralForType(T, Loc));
  9982. }
  9983. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9984. ObjCArrayLiteral *ArrayLiteral);
  9985. static void
  9986. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9987. ObjCDictionaryLiteral *DictionaryLiteral);
  9988. /// Check a single element within a collection literal against the
  9989. /// target element type.
  9990. static void checkObjCCollectionLiteralElement(Sema &S,
  9991. QualType TargetElementType,
  9992. Expr *Element,
  9993. unsigned ElementKind) {
  9994. // Skip a bitcast to 'id' or qualified 'id'.
  9995. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9996. if (ICE->getCastKind() == CK_BitCast &&
  9997. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9998. Element = ICE->getSubExpr();
  9999. }
  10000. QualType ElementType = Element->getType();
  10001. ExprResult ElementResult(Element);
  10002. if (ElementType->getAs<ObjCObjectPointerType>() &&
  10003. S.CheckSingleAssignmentConstraints(TargetElementType,
  10004. ElementResult,
  10005. false, false)
  10006. != Sema::Compatible) {
  10007. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  10008. << ElementType << ElementKind << TargetElementType
  10009. << Element->getSourceRange();
  10010. }
  10011. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  10012. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  10013. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  10014. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  10015. }
  10016. /// Check an Objective-C array literal being converted to the given
  10017. /// target type.
  10018. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  10019. ObjCArrayLiteral *ArrayLiteral) {
  10020. if (!S.NSArrayDecl)
  10021. return;
  10022. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  10023. if (!TargetObjCPtr)
  10024. return;
  10025. if (TargetObjCPtr->isUnspecialized() ||
  10026. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  10027. != S.NSArrayDecl->getCanonicalDecl())
  10028. return;
  10029. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  10030. if (TypeArgs.size() != 1)
  10031. return;
  10032. QualType TargetElementType = TypeArgs[0];
  10033. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  10034. checkObjCCollectionLiteralElement(S, TargetElementType,
  10035. ArrayLiteral->getElement(I),
  10036. 0);
  10037. }
  10038. }
  10039. /// Check an Objective-C dictionary literal being converted to the given
  10040. /// target type.
  10041. static void
  10042. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  10043. ObjCDictionaryLiteral *DictionaryLiteral) {
  10044. if (!S.NSDictionaryDecl)
  10045. return;
  10046. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  10047. if (!TargetObjCPtr)
  10048. return;
  10049. if (TargetObjCPtr->isUnspecialized() ||
  10050. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  10051. != S.NSDictionaryDecl->getCanonicalDecl())
  10052. return;
  10053. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  10054. if (TypeArgs.size() != 2)
  10055. return;
  10056. QualType TargetKeyType = TypeArgs[0];
  10057. QualType TargetObjectType = TypeArgs[1];
  10058. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  10059. auto Element = DictionaryLiteral->getKeyValueElement(I);
  10060. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  10061. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  10062. }
  10063. }
  10064. // Helper function to filter out cases for constant width constant conversion.
  10065. // Don't warn on char array initialization or for non-decimal values.
  10066. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  10067. SourceLocation CC) {
  10068. // If initializing from a constant, and the constant starts with '0',
  10069. // then it is a binary, octal, or hexadecimal. Allow these constants
  10070. // to fill all the bits, even if there is a sign change.
  10071. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  10072. const char FirstLiteralCharacter =
  10073. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  10074. if (FirstLiteralCharacter == '0')
  10075. return false;
  10076. }
  10077. // If the CC location points to a '{', and the type is char, then assume
  10078. // assume it is an array initialization.
  10079. if (CC.isValid() && T->isCharType()) {
  10080. const char FirstContextCharacter =
  10081. S.getSourceManager().getCharacterData(CC)[0];
  10082. if (FirstContextCharacter == '{')
  10083. return false;
  10084. }
  10085. return true;
  10086. }
  10087. static const IntegerLiteral *getIntegerLiteral(Expr *E) {
  10088. const auto *IL = dyn_cast<IntegerLiteral>(E);
  10089. if (!IL) {
  10090. if (auto *UO = dyn_cast<UnaryOperator>(E)) {
  10091. if (UO->getOpcode() == UO_Minus)
  10092. return dyn_cast<IntegerLiteral>(UO->getSubExpr());
  10093. }
  10094. }
  10095. return IL;
  10096. }
  10097. static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
  10098. Expr *LHS, Expr *RHS) {
  10099. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  10100. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  10101. const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  10102. if (!LHSEnumType)
  10103. return;
  10104. const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  10105. if (!RHSEnumType)
  10106. return;
  10107. // Ignore anonymous enums.
  10108. if (!LHSEnumType->getDecl()->hasNameForLinkage())
  10109. return;
  10110. if (!RHSEnumType->getDecl()->hasNameForLinkage())
  10111. return;
  10112. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  10113. return;
  10114. S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
  10115. << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
  10116. << RHS->getSourceRange();
  10117. }
  10118. static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
  10119. E = E->IgnoreParenImpCasts();
  10120. SourceLocation ExprLoc = E->getExprLoc();
  10121. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  10122. BinaryOperator::Opcode Opc = BO->getOpcode();
  10123. Expr::EvalResult Result;
  10124. // Do not diagnose unsigned shifts.
  10125. if (Opc == BO_Shl) {
  10126. const auto *LHS = getIntegerLiteral(BO->getLHS());
  10127. const auto *RHS = getIntegerLiteral(BO->getRHS());
  10128. if (LHS && LHS->getValue() == 0)
  10129. S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
  10130. else if (!E->isValueDependent() && LHS && RHS &&
  10131. RHS->getValue().isNonNegative() &&
  10132. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
  10133. S.Diag(ExprLoc, diag::warn_left_shift_always)
  10134. << (Result.Val.getInt() != 0);
  10135. else if (E->getType()->isSignedIntegerType())
  10136. S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
  10137. }
  10138. }
  10139. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  10140. const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
  10141. const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
  10142. if (!LHS || !RHS)
  10143. return;
  10144. if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
  10145. (RHS->getValue() == 0 || RHS->getValue() == 1))
  10146. // Do not diagnose common idioms.
  10147. return;
  10148. if (LHS->getValue() != 0 && LHS->getValue() != 0)
  10149. S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
  10150. }
  10151. }
  10152. static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  10153. SourceLocation CC,
  10154. bool *ICContext = nullptr,
  10155. bool IsListInit = false) {
  10156. if (E->isTypeDependent() || E->isValueDependent()) return;
  10157. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  10158. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  10159. if (Source == Target) return;
  10160. if (Target->isDependentType()) return;
  10161. // If the conversion context location is invalid don't complain. We also
  10162. // don't want to emit a warning if the issue occurs from the expansion of
  10163. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  10164. // delay this check as long as possible. Once we detect we are in that
  10165. // scenario, we just return.
  10166. if (CC.isInvalid())
  10167. return;
  10168. if (Source->isAtomicType())
  10169. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  10170. // Diagnose implicit casts to bool.
  10171. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  10172. if (isa<StringLiteral>(E))
  10173. // Warn on string literal to bool. Checks for string literals in logical
  10174. // and expressions, for instance, assert(0 && "error here"), are
  10175. // prevented by a check in AnalyzeImplicitConversions().
  10176. return DiagnoseImpCast(S, E, T, CC,
  10177. diag::warn_impcast_string_literal_to_bool);
  10178. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  10179. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  10180. // This covers the literal expressions that evaluate to Objective-C
  10181. // objects.
  10182. return DiagnoseImpCast(S, E, T, CC,
  10183. diag::warn_impcast_objective_c_literal_to_bool);
  10184. }
  10185. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  10186. // Warn on pointer to bool conversion that is always true.
  10187. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  10188. SourceRange(CC));
  10189. }
  10190. }
  10191. // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
  10192. // is a typedef for signed char (macOS), then that constant value has to be 1
  10193. // or 0.
  10194. if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
  10195. Expr::EvalResult Result;
  10196. if (E->EvaluateAsInt(Result, S.getASTContext(),
  10197. Expr::SE_AllowSideEffects)) {
  10198. if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
  10199. adornObjCBoolConversionDiagWithTernaryFixit(
  10200. S, E,
  10201. S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
  10202. << Result.Val.getInt().toString(10));
  10203. }
  10204. return;
  10205. }
  10206. }
  10207. // Check implicit casts from Objective-C collection literals to specialized
  10208. // collection types, e.g., NSArray<NSString *> *.
  10209. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  10210. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  10211. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  10212. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  10213. // Strip vector types.
  10214. if (isa<VectorType>(Source)) {
  10215. if (!isa<VectorType>(Target)) {
  10216. if (S.SourceMgr.isInSystemMacro(CC))
  10217. return;
  10218. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  10219. }
  10220. // If the vector cast is cast between two vectors of the same size, it is
  10221. // a bitcast, not a conversion.
  10222. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  10223. return;
  10224. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  10225. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  10226. }
  10227. if (auto VecTy = dyn_cast<VectorType>(Target))
  10228. Target = VecTy->getElementType().getTypePtr();
  10229. // Strip complex types.
  10230. if (isa<ComplexType>(Source)) {
  10231. if (!isa<ComplexType>(Target)) {
  10232. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  10233. return;
  10234. return DiagnoseImpCast(S, E, T, CC,
  10235. S.getLangOpts().CPlusPlus
  10236. ? diag::err_impcast_complex_scalar
  10237. : diag::warn_impcast_complex_scalar);
  10238. }
  10239. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  10240. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  10241. }
  10242. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  10243. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  10244. // If the source is floating point...
  10245. if (SourceBT && SourceBT->isFloatingPoint()) {
  10246. // ...and the target is floating point...
  10247. if (TargetBT && TargetBT->isFloatingPoint()) {
  10248. // ...then warn if we're dropping FP rank.
  10249. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  10250. QualType(SourceBT, 0), QualType(TargetBT, 0));
  10251. if (Order > 0) {
  10252. // Don't warn about float constants that are precisely
  10253. // representable in the target type.
  10254. Expr::EvalResult result;
  10255. if (E->EvaluateAsRValue(result, S.Context)) {
  10256. // Value might be a float, a float vector, or a float complex.
  10257. if (IsSameFloatAfterCast(result.Val,
  10258. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  10259. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  10260. return;
  10261. }
  10262. if (S.SourceMgr.isInSystemMacro(CC))
  10263. return;
  10264. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  10265. }
  10266. // ... or possibly if we're increasing rank, too
  10267. else if (Order < 0) {
  10268. if (S.SourceMgr.isInSystemMacro(CC))
  10269. return;
  10270. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  10271. }
  10272. return;
  10273. }
  10274. // If the target is integral, always warn.
  10275. if (TargetBT && TargetBT->isInteger()) {
  10276. if (S.SourceMgr.isInSystemMacro(CC))
  10277. return;
  10278. DiagnoseFloatingImpCast(S, E, T, CC);
  10279. }
  10280. // Detect the case where a call result is converted from floating-point to
  10281. // to bool, and the final argument to the call is converted from bool, to
  10282. // discover this typo:
  10283. //
  10284. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  10285. //
  10286. // FIXME: This is an incredibly special case; is there some more general
  10287. // way to detect this class of misplaced-parentheses bug?
  10288. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  10289. // Check last argument of function call to see if it is an
  10290. // implicit cast from a type matching the type the result
  10291. // is being cast to.
  10292. CallExpr *CEx = cast<CallExpr>(E);
  10293. if (unsigned NumArgs = CEx->getNumArgs()) {
  10294. Expr *LastA = CEx->getArg(NumArgs - 1);
  10295. Expr *InnerE = LastA->IgnoreParenImpCasts();
  10296. if (isa<ImplicitCastExpr>(LastA) &&
  10297. InnerE->getType()->isBooleanType()) {
  10298. // Warn on this floating-point to bool conversion
  10299. DiagnoseImpCast(S, E, T, CC,
  10300. diag::warn_impcast_floating_point_to_bool);
  10301. }
  10302. }
  10303. }
  10304. return;
  10305. }
  10306. // Valid casts involving fixed point types should be accounted for here.
  10307. if (Source->isFixedPointType()) {
  10308. if (Target->isUnsaturatedFixedPointType()) {
  10309. Expr::EvalResult Result;
  10310. if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
  10311. S.isConstantEvaluated())) {
  10312. APFixedPoint Value = Result.Val.getFixedPoint();
  10313. APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  10314. APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  10315. if (Value > MaxVal || Value < MinVal) {
  10316. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10317. S.PDiag(diag::warn_impcast_fixed_point_range)
  10318. << Value.toString() << T
  10319. << E->getSourceRange()
  10320. << clang::SourceRange(CC));
  10321. return;
  10322. }
  10323. }
  10324. } else if (Target->isIntegerType()) {
  10325. Expr::EvalResult Result;
  10326. if (!S.isConstantEvaluated() &&
  10327. E->EvaluateAsFixedPoint(Result, S.Context,
  10328. Expr::SE_AllowSideEffects)) {
  10329. APFixedPoint FXResult = Result.Val.getFixedPoint();
  10330. bool Overflowed;
  10331. llvm::APSInt IntResult = FXResult.convertToInt(
  10332. S.Context.getIntWidth(T),
  10333. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  10334. if (Overflowed) {
  10335. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10336. S.PDiag(diag::warn_impcast_fixed_point_range)
  10337. << FXResult.toString() << T
  10338. << E->getSourceRange()
  10339. << clang::SourceRange(CC));
  10340. return;
  10341. }
  10342. }
  10343. }
  10344. } else if (Target->isUnsaturatedFixedPointType()) {
  10345. if (Source->isIntegerType()) {
  10346. Expr::EvalResult Result;
  10347. if (!S.isConstantEvaluated() &&
  10348. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10349. llvm::APSInt Value = Result.Val.getInt();
  10350. bool Overflowed;
  10351. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10352. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  10353. if (Overflowed) {
  10354. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10355. S.PDiag(diag::warn_impcast_fixed_point_range)
  10356. << Value.toString(/*Radix=*/10) << T
  10357. << E->getSourceRange()
  10358. << clang::SourceRange(CC));
  10359. return;
  10360. }
  10361. }
  10362. }
  10363. }
  10364. // If we are casting an integer type to a floating point type without
  10365. // initialization-list syntax, we might lose accuracy if the floating
  10366. // point type has a narrower significand than the integer type.
  10367. if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
  10368. TargetBT->isFloatingType() && !IsListInit) {
  10369. // Determine the number of precision bits in the source integer type.
  10370. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
  10371. unsigned int SourcePrecision = SourceRange.Width;
  10372. // Determine the number of precision bits in the
  10373. // target floating point type.
  10374. unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
  10375. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  10376. if (SourcePrecision > 0 && TargetPrecision > 0 &&
  10377. SourcePrecision > TargetPrecision) {
  10378. llvm::APSInt SourceInt;
  10379. if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
  10380. // If the source integer is a constant, convert it to the target
  10381. // floating point type. Issue a warning if the value changes
  10382. // during the whole conversion.
  10383. llvm::APFloat TargetFloatValue(
  10384. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  10385. llvm::APFloat::opStatus ConversionStatus =
  10386. TargetFloatValue.convertFromAPInt(
  10387. SourceInt, SourceBT->isSignedInteger(),
  10388. llvm::APFloat::rmNearestTiesToEven);
  10389. if (ConversionStatus != llvm::APFloat::opOK) {
  10390. std::string PrettySourceValue = SourceInt.toString(10);
  10391. SmallString<32> PrettyTargetValue;
  10392. TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
  10393. S.DiagRuntimeBehavior(
  10394. E->getExprLoc(), E,
  10395. S.PDiag(diag::warn_impcast_integer_float_precision_constant)
  10396. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10397. << E->getSourceRange() << clang::SourceRange(CC));
  10398. }
  10399. } else {
  10400. // Otherwise, the implicit conversion may lose precision.
  10401. DiagnoseImpCast(S, E, T, CC,
  10402. diag::warn_impcast_integer_float_precision);
  10403. }
  10404. }
  10405. }
  10406. DiagnoseNullConversion(S, E, T, CC);
  10407. S.DiscardMisalignedMemberAddress(Target, E);
  10408. if (Target->isBooleanType())
  10409. DiagnoseIntInBoolContext(S, E);
  10410. if (!Source->isIntegerType() || !Target->isIntegerType())
  10411. return;
  10412. // TODO: remove this early return once the false positives for constant->bool
  10413. // in templates, macros, etc, are reduced or removed.
  10414. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  10415. return;
  10416. if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
  10417. !E->isKnownToHaveBooleanValue()) {
  10418. return adornObjCBoolConversionDiagWithTernaryFixit(
  10419. S, E,
  10420. S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
  10421. << E->getType());
  10422. }
  10423. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
  10424. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  10425. if (SourceRange.Width > TargetRange.Width) {
  10426. // If the source is a constant, use a default-on diagnostic.
  10427. // TODO: this should happen for bitfield stores, too.
  10428. Expr::EvalResult Result;
  10429. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
  10430. S.isConstantEvaluated())) {
  10431. llvm::APSInt Value(32);
  10432. Value = Result.Val.getInt();
  10433. if (S.SourceMgr.isInSystemMacro(CC))
  10434. return;
  10435. std::string PrettySourceValue = Value.toString(10);
  10436. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10437. S.DiagRuntimeBehavior(
  10438. E->getExprLoc(), E,
  10439. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10440. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10441. << E->getSourceRange() << clang::SourceRange(CC));
  10442. return;
  10443. }
  10444. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  10445. if (S.SourceMgr.isInSystemMacro(CC))
  10446. return;
  10447. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  10448. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  10449. /* pruneControlFlow */ true);
  10450. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  10451. }
  10452. if (TargetRange.Width > SourceRange.Width) {
  10453. if (auto *UO = dyn_cast<UnaryOperator>(E))
  10454. if (UO->getOpcode() == UO_Minus)
  10455. if (Source->isUnsignedIntegerType()) {
  10456. if (Target->isUnsignedIntegerType())
  10457. return DiagnoseImpCast(S, E, T, CC,
  10458. diag::warn_impcast_high_order_zero_bits);
  10459. if (Target->isSignedIntegerType())
  10460. return DiagnoseImpCast(S, E, T, CC,
  10461. diag::warn_impcast_nonnegative_result);
  10462. }
  10463. }
  10464. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  10465. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  10466. // Warn when doing a signed to signed conversion, warn if the positive
  10467. // source value is exactly the width of the target type, which will
  10468. // cause a negative value to be stored.
  10469. Expr::EvalResult Result;
  10470. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  10471. !S.SourceMgr.isInSystemMacro(CC)) {
  10472. llvm::APSInt Value = Result.Val.getInt();
  10473. if (isSameWidthConstantConversion(S, E, T, CC)) {
  10474. std::string PrettySourceValue = Value.toString(10);
  10475. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10476. S.DiagRuntimeBehavior(
  10477. E->getExprLoc(), E,
  10478. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10479. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10480. << E->getSourceRange() << clang::SourceRange(CC));
  10481. return;
  10482. }
  10483. }
  10484. // Fall through for non-constants to give a sign conversion warning.
  10485. }
  10486. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  10487. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  10488. SourceRange.Width == TargetRange.Width)) {
  10489. if (S.SourceMgr.isInSystemMacro(CC))
  10490. return;
  10491. unsigned DiagID = diag::warn_impcast_integer_sign;
  10492. // Traditionally, gcc has warned about this under -Wsign-compare.
  10493. // We also want to warn about it in -Wconversion.
  10494. // So if -Wconversion is off, use a completely identical diagnostic
  10495. // in the sign-compare group.
  10496. // The conditional-checking code will
  10497. if (ICContext) {
  10498. DiagID = diag::warn_impcast_integer_sign_conditional;
  10499. *ICContext = true;
  10500. }
  10501. return DiagnoseImpCast(S, E, T, CC, DiagID);
  10502. }
  10503. // Diagnose conversions between different enumeration types.
  10504. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  10505. // type, to give us better diagnostics.
  10506. QualType SourceType = E->getType();
  10507. if (!S.getLangOpts().CPlusPlus) {
  10508. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10509. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  10510. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  10511. SourceType = S.Context.getTypeDeclType(Enum);
  10512. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  10513. }
  10514. }
  10515. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  10516. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  10517. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  10518. TargetEnum->getDecl()->hasNameForLinkage() &&
  10519. SourceEnum != TargetEnum) {
  10520. if (S.SourceMgr.isInSystemMacro(CC))
  10521. return;
  10522. return DiagnoseImpCast(S, E, SourceType, T, CC,
  10523. diag::warn_impcast_different_enum_types);
  10524. }
  10525. }
  10526. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10527. SourceLocation CC, QualType T);
  10528. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  10529. SourceLocation CC, bool &ICContext) {
  10530. E = E->IgnoreParenImpCasts();
  10531. if (isa<ConditionalOperator>(E))
  10532. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  10533. AnalyzeImplicitConversions(S, E, CC);
  10534. if (E->getType() != T)
  10535. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  10536. }
  10537. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10538. SourceLocation CC, QualType T) {
  10539. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  10540. bool Suspicious = false;
  10541. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  10542. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  10543. CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
  10544. E->getFalseExpr());
  10545. if (T->isBooleanType())
  10546. DiagnoseIntInBoolContext(S, E);
  10547. // If -Wconversion would have warned about either of the candidates
  10548. // for a signedness conversion to the context type...
  10549. if (!Suspicious) return;
  10550. // ...but it's currently ignored...
  10551. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  10552. return;
  10553. // ...then check whether it would have warned about either of the
  10554. // candidates for a signedness conversion to the condition type.
  10555. if (E->getType() == T) return;
  10556. Suspicious = false;
  10557. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  10558. E->getType(), CC, &Suspicious);
  10559. if (!Suspicious)
  10560. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  10561. E->getType(), CC, &Suspicious);
  10562. }
  10563. /// Check conversion of given expression to boolean.
  10564. /// Input argument E is a logical expression.
  10565. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  10566. if (S.getLangOpts().Bool)
  10567. return;
  10568. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  10569. return;
  10570. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  10571. }
  10572. /// AnalyzeImplicitConversions - Find and report any interesting
  10573. /// implicit conversions in the given expression. There are a couple
  10574. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  10575. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
  10576. bool IsListInit/*= false*/) {
  10577. QualType T = OrigE->getType();
  10578. Expr *E = OrigE->IgnoreParenImpCasts();
  10579. // Propagate whether we are in a C++ list initialization expression.
  10580. // If so, we do not issue warnings for implicit int-float conversion
  10581. // precision loss, because C++11 narrowing already handles it.
  10582. IsListInit =
  10583. IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
  10584. if (E->isTypeDependent() || E->isValueDependent())
  10585. return;
  10586. // For conditional operators, we analyze the arguments as if they
  10587. // were being fed directly into the output.
  10588. if (isa<ConditionalOperator>(E)) {
  10589. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  10590. CheckConditionalOperator(S, CO, CC, T);
  10591. return;
  10592. }
  10593. // Check implicit argument conversions for function calls.
  10594. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  10595. CheckImplicitArgumentConversions(S, Call, CC);
  10596. // Go ahead and check any implicit conversions we might have skipped.
  10597. // The non-canonical typecheck is just an optimization;
  10598. // CheckImplicitConversion will filter out dead implicit conversions.
  10599. if (E->getType() != T)
  10600. CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
  10601. // Now continue drilling into this expression.
  10602. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  10603. // The bound subexpressions in a PseudoObjectExpr are not reachable
  10604. // as transitive children.
  10605. // FIXME: Use a more uniform representation for this.
  10606. for (auto *SE : POE->semantics())
  10607. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  10608. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
  10609. }
  10610. // Skip past explicit casts.
  10611. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  10612. E = CE->getSubExpr()->IgnoreParenImpCasts();
  10613. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  10614. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  10615. return AnalyzeImplicitConversions(S, E, CC, IsListInit);
  10616. }
  10617. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10618. // Do a somewhat different check with comparison operators.
  10619. if (BO->isComparisonOp())
  10620. return AnalyzeComparison(S, BO);
  10621. // And with simple assignments.
  10622. if (BO->getOpcode() == BO_Assign)
  10623. return AnalyzeAssignment(S, BO);
  10624. // And with compound assignments.
  10625. if (BO->isAssignmentOp())
  10626. return AnalyzeCompoundAssignment(S, BO);
  10627. }
  10628. // These break the otherwise-useful invariant below. Fortunately,
  10629. // we don't really need to recurse into them, because any internal
  10630. // expressions should have been analyzed already when they were
  10631. // built into statements.
  10632. if (isa<StmtExpr>(E)) return;
  10633. // Don't descend into unevaluated contexts.
  10634. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  10635. // Now just recurse over the expression's children.
  10636. CC = E->getExprLoc();
  10637. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  10638. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  10639. for (Stmt *SubStmt : E->children()) {
  10640. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  10641. if (!ChildExpr)
  10642. continue;
  10643. if (IsLogicalAndOperator &&
  10644. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  10645. // Ignore checking string literals that are in logical and operators.
  10646. // This is a common pattern for asserts.
  10647. continue;
  10648. AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
  10649. }
  10650. if (BO && BO->isLogicalOp()) {
  10651. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  10652. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10653. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10654. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  10655. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10656. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10657. }
  10658. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  10659. if (U->getOpcode() == UO_LNot) {
  10660. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  10661. } else if (U->getOpcode() != UO_AddrOf) {
  10662. if (U->getSubExpr()->getType()->isAtomicType())
  10663. S.Diag(U->getSubExpr()->getBeginLoc(),
  10664. diag::warn_atomic_implicit_seq_cst);
  10665. }
  10666. }
  10667. }
  10668. /// Diagnose integer type and any valid implicit conversion to it.
  10669. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  10670. // Taking into account implicit conversions,
  10671. // allow any integer.
  10672. if (!E->getType()->isIntegerType()) {
  10673. S.Diag(E->getBeginLoc(),
  10674. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  10675. return true;
  10676. }
  10677. // Potentially emit standard warnings for implicit conversions if enabled
  10678. // using -Wconversion.
  10679. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  10680. return false;
  10681. }
  10682. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  10683. // Returns true when emitting a warning about taking the address of a reference.
  10684. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  10685. const PartialDiagnostic &PD) {
  10686. E = E->IgnoreParenImpCasts();
  10687. const FunctionDecl *FD = nullptr;
  10688. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10689. if (!DRE->getDecl()->getType()->isReferenceType())
  10690. return false;
  10691. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10692. if (!M->getMemberDecl()->getType()->isReferenceType())
  10693. return false;
  10694. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10695. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10696. return false;
  10697. FD = Call->getDirectCallee();
  10698. } else {
  10699. return false;
  10700. }
  10701. SemaRef.Diag(E->getExprLoc(), PD);
  10702. // If possible, point to location of function.
  10703. if (FD) {
  10704. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10705. }
  10706. return true;
  10707. }
  10708. // Returns true if the SourceLocation is expanded from any macro body.
  10709. // Returns false if the SourceLocation is invalid, is from not in a macro
  10710. // expansion, or is from expanded from a top-level macro argument.
  10711. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10712. if (Loc.isInvalid())
  10713. return false;
  10714. while (Loc.isMacroID()) {
  10715. if (SM.isMacroBodyExpansion(Loc))
  10716. return true;
  10717. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10718. }
  10719. return false;
  10720. }
  10721. /// Diagnose pointers that are always non-null.
  10722. /// \param E the expression containing the pointer
  10723. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10724. /// compared to a null pointer
  10725. /// \param IsEqual True when the comparison is equal to a null pointer
  10726. /// \param Range Extra SourceRange to highlight in the diagnostic
  10727. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10728. Expr::NullPointerConstantKind NullKind,
  10729. bool IsEqual, SourceRange Range) {
  10730. if (!E)
  10731. return;
  10732. // Don't warn inside macros.
  10733. if (E->getExprLoc().isMacroID()) {
  10734. const SourceManager &SM = getSourceManager();
  10735. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10736. IsInAnyMacroBody(SM, Range.getBegin()))
  10737. return;
  10738. }
  10739. E = E->IgnoreImpCasts();
  10740. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10741. if (isa<CXXThisExpr>(E)) {
  10742. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10743. : diag::warn_this_bool_conversion;
  10744. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10745. return;
  10746. }
  10747. bool IsAddressOf = false;
  10748. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10749. if (UO->getOpcode() != UO_AddrOf)
  10750. return;
  10751. IsAddressOf = true;
  10752. E = UO->getSubExpr();
  10753. }
  10754. if (IsAddressOf) {
  10755. unsigned DiagID = IsCompare
  10756. ? diag::warn_address_of_reference_null_compare
  10757. : diag::warn_address_of_reference_bool_conversion;
  10758. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10759. << IsEqual;
  10760. if (CheckForReference(*this, E, PD)) {
  10761. return;
  10762. }
  10763. }
  10764. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10765. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10766. std::string Str;
  10767. llvm::raw_string_ostream S(Str);
  10768. E->printPretty(S, nullptr, getPrintingPolicy());
  10769. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10770. : diag::warn_cast_nonnull_to_bool;
  10771. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10772. << E->getSourceRange() << Range << IsEqual;
  10773. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10774. };
  10775. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10776. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10777. if (auto *Callee = Call->getDirectCallee()) {
  10778. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10779. ComplainAboutNonnullParamOrCall(A);
  10780. return;
  10781. }
  10782. }
  10783. }
  10784. // Expect to find a single Decl. Skip anything more complicated.
  10785. ValueDecl *D = nullptr;
  10786. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10787. D = R->getDecl();
  10788. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10789. D = M->getMemberDecl();
  10790. }
  10791. // Weak Decls can be null.
  10792. if (!D || D->isWeak())
  10793. return;
  10794. // Check for parameter decl with nonnull attribute
  10795. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10796. if (getCurFunction() &&
  10797. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10798. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10799. ComplainAboutNonnullParamOrCall(A);
  10800. return;
  10801. }
  10802. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10803. // Skip function template not specialized yet.
  10804. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10805. return;
  10806. auto ParamIter = llvm::find(FD->parameters(), PV);
  10807. assert(ParamIter != FD->param_end());
  10808. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10809. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10810. if (!NonNull->args_size()) {
  10811. ComplainAboutNonnullParamOrCall(NonNull);
  10812. return;
  10813. }
  10814. for (const ParamIdx &ArgNo : NonNull->args()) {
  10815. if (ArgNo.getASTIndex() == ParamNo) {
  10816. ComplainAboutNonnullParamOrCall(NonNull);
  10817. return;
  10818. }
  10819. }
  10820. }
  10821. }
  10822. }
  10823. }
  10824. QualType T = D->getType();
  10825. const bool IsArray = T->isArrayType();
  10826. const bool IsFunction = T->isFunctionType();
  10827. // Address of function is used to silence the function warning.
  10828. if (IsAddressOf && IsFunction) {
  10829. return;
  10830. }
  10831. // Found nothing.
  10832. if (!IsAddressOf && !IsFunction && !IsArray)
  10833. return;
  10834. // Pretty print the expression for the diagnostic.
  10835. std::string Str;
  10836. llvm::raw_string_ostream S(Str);
  10837. E->printPretty(S, nullptr, getPrintingPolicy());
  10838. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10839. : diag::warn_impcast_pointer_to_bool;
  10840. enum {
  10841. AddressOf,
  10842. FunctionPointer,
  10843. ArrayPointer
  10844. } DiagType;
  10845. if (IsAddressOf)
  10846. DiagType = AddressOf;
  10847. else if (IsFunction)
  10848. DiagType = FunctionPointer;
  10849. else if (IsArray)
  10850. DiagType = ArrayPointer;
  10851. else
  10852. llvm_unreachable("Could not determine diagnostic.");
  10853. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10854. << Range << IsEqual;
  10855. if (!IsFunction)
  10856. return;
  10857. // Suggest '&' to silence the function warning.
  10858. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10859. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10860. // Check to see if '()' fixit should be emitted.
  10861. QualType ReturnType;
  10862. UnresolvedSet<4> NonTemplateOverloads;
  10863. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10864. if (ReturnType.isNull())
  10865. return;
  10866. if (IsCompare) {
  10867. // There are two cases here. If there is null constant, the only suggest
  10868. // for a pointer return type. If the null is 0, then suggest if the return
  10869. // type is a pointer or an integer type.
  10870. if (!ReturnType->isPointerType()) {
  10871. if (NullKind == Expr::NPCK_ZeroExpression ||
  10872. NullKind == Expr::NPCK_ZeroLiteral) {
  10873. if (!ReturnType->isIntegerType())
  10874. return;
  10875. } else {
  10876. return;
  10877. }
  10878. }
  10879. } else { // !IsCompare
  10880. // For function to bool, only suggest if the function pointer has bool
  10881. // return type.
  10882. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10883. return;
  10884. }
  10885. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10886. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10887. }
  10888. /// Diagnoses "dangerous" implicit conversions within the given
  10889. /// expression (which is a full expression). Implements -Wconversion
  10890. /// and -Wsign-compare.
  10891. ///
  10892. /// \param CC the "context" location of the implicit conversion, i.e.
  10893. /// the most location of the syntactic entity requiring the implicit
  10894. /// conversion
  10895. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10896. // Don't diagnose in unevaluated contexts.
  10897. if (isUnevaluatedContext())
  10898. return;
  10899. // Don't diagnose for value- or type-dependent expressions.
  10900. if (E->isTypeDependent() || E->isValueDependent())
  10901. return;
  10902. // Check for array bounds violations in cases where the check isn't triggered
  10903. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10904. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10905. CheckArrayAccess(E);
  10906. // This is not the right CC for (e.g.) a variable initialization.
  10907. AnalyzeImplicitConversions(*this, E, CC);
  10908. }
  10909. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10910. /// Input argument E is a logical expression.
  10911. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10912. ::CheckBoolLikeConversion(*this, E, CC);
  10913. }
  10914. /// Diagnose when expression is an integer constant expression and its evaluation
  10915. /// results in integer overflow
  10916. void Sema::CheckForIntOverflow (Expr *E) {
  10917. // Use a work list to deal with nested struct initializers.
  10918. SmallVector<Expr *, 2> Exprs(1, E);
  10919. do {
  10920. Expr *OriginalE = Exprs.pop_back_val();
  10921. Expr *E = OriginalE->IgnoreParenCasts();
  10922. if (isa<BinaryOperator>(E)) {
  10923. E->EvaluateForOverflow(Context);
  10924. continue;
  10925. }
  10926. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10927. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10928. else if (isa<ObjCBoxedExpr>(OriginalE))
  10929. E->EvaluateForOverflow(Context);
  10930. else if (auto Call = dyn_cast<CallExpr>(E))
  10931. Exprs.append(Call->arg_begin(), Call->arg_end());
  10932. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10933. Exprs.append(Message->arg_begin(), Message->arg_end());
  10934. } while (!Exprs.empty());
  10935. }
  10936. namespace {
  10937. /// Visitor for expressions which looks for unsequenced operations on the
  10938. /// same object.
  10939. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10940. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10941. /// A tree of sequenced regions within an expression. Two regions are
  10942. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10943. /// finish processing an expression with sequencing, such as a comma
  10944. /// expression, we fold its tree nodes into its parent, since they are
  10945. /// unsequenced with respect to nodes we will visit later.
  10946. class SequenceTree {
  10947. struct Value {
  10948. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10949. unsigned Parent : 31;
  10950. unsigned Merged : 1;
  10951. };
  10952. SmallVector<Value, 8> Values;
  10953. public:
  10954. /// A region within an expression which may be sequenced with respect
  10955. /// to some other region.
  10956. class Seq {
  10957. friend class SequenceTree;
  10958. unsigned Index;
  10959. explicit Seq(unsigned N) : Index(N) {}
  10960. public:
  10961. Seq() : Index(0) {}
  10962. };
  10963. SequenceTree() { Values.push_back(Value(0)); }
  10964. Seq root() const { return Seq(0); }
  10965. /// Create a new sequence of operations, which is an unsequenced
  10966. /// subset of \p Parent. This sequence of operations is sequenced with
  10967. /// respect to other children of \p Parent.
  10968. Seq allocate(Seq Parent) {
  10969. Values.push_back(Value(Parent.Index));
  10970. return Seq(Values.size() - 1);
  10971. }
  10972. /// Merge a sequence of operations into its parent.
  10973. void merge(Seq S) {
  10974. Values[S.Index].Merged = true;
  10975. }
  10976. /// Determine whether two operations are unsequenced. This operation
  10977. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10978. /// should have been merged into its parent as appropriate.
  10979. bool isUnsequenced(Seq Cur, Seq Old) {
  10980. unsigned C = representative(Cur.Index);
  10981. unsigned Target = representative(Old.Index);
  10982. while (C >= Target) {
  10983. if (C == Target)
  10984. return true;
  10985. C = Values[C].Parent;
  10986. }
  10987. return false;
  10988. }
  10989. private:
  10990. /// Pick a representative for a sequence.
  10991. unsigned representative(unsigned K) {
  10992. if (Values[K].Merged)
  10993. // Perform path compression as we go.
  10994. return Values[K].Parent = representative(Values[K].Parent);
  10995. return K;
  10996. }
  10997. };
  10998. /// An object for which we can track unsequenced uses.
  10999. using Object = NamedDecl *;
  11000. /// Different flavors of object usage which we track. We only track the
  11001. /// least-sequenced usage of each kind.
  11002. enum UsageKind {
  11003. /// A read of an object. Multiple unsequenced reads are OK.
  11004. UK_Use,
  11005. /// A modification of an object which is sequenced before the value
  11006. /// computation of the expression, such as ++n in C++.
  11007. UK_ModAsValue,
  11008. /// A modification of an object which is not sequenced before the value
  11009. /// computation of the expression, such as n++.
  11010. UK_ModAsSideEffect,
  11011. UK_Count = UK_ModAsSideEffect + 1
  11012. };
  11013. struct Usage {
  11014. Expr *Use;
  11015. SequenceTree::Seq Seq;
  11016. Usage() : Use(nullptr), Seq() {}
  11017. };
  11018. struct UsageInfo {
  11019. Usage Uses[UK_Count];
  11020. /// Have we issued a diagnostic for this variable already?
  11021. bool Diagnosed;
  11022. UsageInfo() : Uses(), Diagnosed(false) {}
  11023. };
  11024. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  11025. Sema &SemaRef;
  11026. /// Sequenced regions within the expression.
  11027. SequenceTree Tree;
  11028. /// Declaration modifications and references which we have seen.
  11029. UsageInfoMap UsageMap;
  11030. /// The region we are currently within.
  11031. SequenceTree::Seq Region;
  11032. /// Filled in with declarations which were modified as a side-effect
  11033. /// (that is, post-increment operations).
  11034. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  11035. /// Expressions to check later. We defer checking these to reduce
  11036. /// stack usage.
  11037. SmallVectorImpl<Expr *> &WorkList;
  11038. /// RAII object wrapping the visitation of a sequenced subexpression of an
  11039. /// expression. At the end of this process, the side-effects of the evaluation
  11040. /// become sequenced with respect to the value computation of the result, so
  11041. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  11042. /// UK_ModAsValue.
  11043. struct SequencedSubexpression {
  11044. SequencedSubexpression(SequenceChecker &Self)
  11045. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  11046. Self.ModAsSideEffect = &ModAsSideEffect;
  11047. }
  11048. ~SequencedSubexpression() {
  11049. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  11050. UsageInfo &U = Self.UsageMap[M.first];
  11051. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  11052. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  11053. SideEffectUsage = M.second;
  11054. }
  11055. Self.ModAsSideEffect = OldModAsSideEffect;
  11056. }
  11057. SequenceChecker &Self;
  11058. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  11059. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  11060. };
  11061. /// RAII object wrapping the visitation of a subexpression which we might
  11062. /// choose to evaluate as a constant. If any subexpression is evaluated and
  11063. /// found to be non-constant, this allows us to suppress the evaluation of
  11064. /// the outer expression.
  11065. class EvaluationTracker {
  11066. public:
  11067. EvaluationTracker(SequenceChecker &Self)
  11068. : Self(Self), Prev(Self.EvalTracker) {
  11069. Self.EvalTracker = this;
  11070. }
  11071. ~EvaluationTracker() {
  11072. Self.EvalTracker = Prev;
  11073. if (Prev)
  11074. Prev->EvalOK &= EvalOK;
  11075. }
  11076. bool evaluate(const Expr *E, bool &Result) {
  11077. if (!EvalOK || E->isValueDependent())
  11078. return false;
  11079. EvalOK = E->EvaluateAsBooleanCondition(
  11080. Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
  11081. return EvalOK;
  11082. }
  11083. private:
  11084. SequenceChecker &Self;
  11085. EvaluationTracker *Prev;
  11086. bool EvalOK = true;
  11087. } *EvalTracker = nullptr;
  11088. /// Find the object which is produced by the specified expression,
  11089. /// if any.
  11090. Object getObject(Expr *E, bool Mod) const {
  11091. E = E->IgnoreParenCasts();
  11092. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  11093. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  11094. return getObject(UO->getSubExpr(), Mod);
  11095. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  11096. if (BO->getOpcode() == BO_Comma)
  11097. return getObject(BO->getRHS(), Mod);
  11098. if (Mod && BO->isAssignmentOp())
  11099. return getObject(BO->getLHS(), Mod);
  11100. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  11101. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  11102. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  11103. return ME->getMemberDecl();
  11104. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  11105. // FIXME: If this is a reference, map through to its value.
  11106. return DRE->getDecl();
  11107. return nullptr;
  11108. }
  11109. /// Note that an object was modified or used by an expression.
  11110. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  11111. Usage &U = UI.Uses[UK];
  11112. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  11113. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  11114. ModAsSideEffect->push_back(std::make_pair(O, U));
  11115. U.Use = Ref;
  11116. U.Seq = Region;
  11117. }
  11118. }
  11119. /// Check whether a modification or use conflicts with a prior usage.
  11120. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  11121. bool IsModMod) {
  11122. if (UI.Diagnosed)
  11123. return;
  11124. const Usage &U = UI.Uses[OtherKind];
  11125. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  11126. return;
  11127. Expr *Mod = U.Use;
  11128. Expr *ModOrUse = Ref;
  11129. if (OtherKind == UK_Use)
  11130. std::swap(Mod, ModOrUse);
  11131. SemaRef.DiagRuntimeBehavior(
  11132. Mod->getExprLoc(), {Mod, ModOrUse},
  11133. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  11134. : diag::warn_unsequenced_mod_use)
  11135. << O << SourceRange(ModOrUse->getExprLoc()));
  11136. UI.Diagnosed = true;
  11137. }
  11138. void notePreUse(Object O, Expr *Use) {
  11139. UsageInfo &U = UsageMap[O];
  11140. // Uses conflict with other modifications.
  11141. checkUsage(O, U, Use, UK_ModAsValue, false);
  11142. }
  11143. void notePostUse(Object O, Expr *Use) {
  11144. UsageInfo &U = UsageMap[O];
  11145. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  11146. addUsage(U, O, Use, UK_Use);
  11147. }
  11148. void notePreMod(Object O, Expr *Mod) {
  11149. UsageInfo &U = UsageMap[O];
  11150. // Modifications conflict with other modifications and with uses.
  11151. checkUsage(O, U, Mod, UK_ModAsValue, true);
  11152. checkUsage(O, U, Mod, UK_Use, false);
  11153. }
  11154. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  11155. UsageInfo &U = UsageMap[O];
  11156. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  11157. addUsage(U, O, Use, UK);
  11158. }
  11159. public:
  11160. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  11161. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  11162. Visit(E);
  11163. }
  11164. void VisitStmt(Stmt *S) {
  11165. // Skip all statements which aren't expressions for now.
  11166. }
  11167. void VisitExpr(Expr *E) {
  11168. // By default, just recurse to evaluated subexpressions.
  11169. Base::VisitStmt(E);
  11170. }
  11171. void VisitCastExpr(CastExpr *E) {
  11172. Object O = Object();
  11173. if (E->getCastKind() == CK_LValueToRValue)
  11174. O = getObject(E->getSubExpr(), false);
  11175. if (O)
  11176. notePreUse(O, E);
  11177. VisitExpr(E);
  11178. if (O)
  11179. notePostUse(O, E);
  11180. }
  11181. void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
  11182. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  11183. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  11184. SequenceTree::Seq OldRegion = Region;
  11185. {
  11186. SequencedSubexpression SeqBefore(*this);
  11187. Region = BeforeRegion;
  11188. Visit(SequencedBefore);
  11189. }
  11190. Region = AfterRegion;
  11191. Visit(SequencedAfter);
  11192. Region = OldRegion;
  11193. Tree.merge(BeforeRegion);
  11194. Tree.merge(AfterRegion);
  11195. }
  11196. void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
  11197. // C++17 [expr.sub]p1:
  11198. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  11199. // expression E1 is sequenced before the expression E2.
  11200. if (SemaRef.getLangOpts().CPlusPlus17)
  11201. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  11202. else
  11203. Base::VisitStmt(ASE);
  11204. }
  11205. void VisitBinComma(BinaryOperator *BO) {
  11206. // C++11 [expr.comma]p1:
  11207. // Every value computation and side effect associated with the left
  11208. // expression is sequenced before every value computation and side
  11209. // effect associated with the right expression.
  11210. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  11211. }
  11212. void VisitBinAssign(BinaryOperator *BO) {
  11213. // The modification is sequenced after the value computation of the LHS
  11214. // and RHS, so check it before inspecting the operands and update the
  11215. // map afterwards.
  11216. Object O = getObject(BO->getLHS(), true);
  11217. if (!O)
  11218. return VisitExpr(BO);
  11219. notePreMod(O, BO);
  11220. // C++11 [expr.ass]p7:
  11221. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  11222. // only once.
  11223. //
  11224. // Therefore, for a compound assignment operator, O is considered used
  11225. // everywhere except within the evaluation of E1 itself.
  11226. if (isa<CompoundAssignOperator>(BO))
  11227. notePreUse(O, BO);
  11228. Visit(BO->getLHS());
  11229. if (isa<CompoundAssignOperator>(BO))
  11230. notePostUse(O, BO);
  11231. Visit(BO->getRHS());
  11232. // C++11 [expr.ass]p1:
  11233. // the assignment is sequenced [...] before the value computation of the
  11234. // assignment expression.
  11235. // C11 6.5.16/3 has no such rule.
  11236. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  11237. : UK_ModAsSideEffect);
  11238. }
  11239. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  11240. VisitBinAssign(CAO);
  11241. }
  11242. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  11243. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  11244. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  11245. Object O = getObject(UO->getSubExpr(), true);
  11246. if (!O)
  11247. return VisitExpr(UO);
  11248. notePreMod(O, UO);
  11249. Visit(UO->getSubExpr());
  11250. // C++11 [expr.pre.incr]p1:
  11251. // the expression ++x is equivalent to x+=1
  11252. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  11253. : UK_ModAsSideEffect);
  11254. }
  11255. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  11256. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  11257. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  11258. Object O = getObject(UO->getSubExpr(), true);
  11259. if (!O)
  11260. return VisitExpr(UO);
  11261. notePreMod(O, UO);
  11262. Visit(UO->getSubExpr());
  11263. notePostMod(O, UO, UK_ModAsSideEffect);
  11264. }
  11265. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  11266. void VisitBinLOr(BinaryOperator *BO) {
  11267. // The side-effects of the LHS of an '&&' are sequenced before the
  11268. // value computation of the RHS, and hence before the value computation
  11269. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  11270. // as if they were unconditionally sequenced.
  11271. EvaluationTracker Eval(*this);
  11272. {
  11273. SequencedSubexpression Sequenced(*this);
  11274. Visit(BO->getLHS());
  11275. }
  11276. bool Result;
  11277. if (Eval.evaluate(BO->getLHS(), Result)) {
  11278. if (!Result)
  11279. Visit(BO->getRHS());
  11280. } else {
  11281. // Check for unsequenced operations in the RHS, treating it as an
  11282. // entirely separate evaluation.
  11283. //
  11284. // FIXME: If there are operations in the RHS which are unsequenced
  11285. // with respect to operations outside the RHS, and those operations
  11286. // are unconditionally evaluated, diagnose them.
  11287. WorkList.push_back(BO->getRHS());
  11288. }
  11289. }
  11290. void VisitBinLAnd(BinaryOperator *BO) {
  11291. EvaluationTracker Eval(*this);
  11292. {
  11293. SequencedSubexpression Sequenced(*this);
  11294. Visit(BO->getLHS());
  11295. }
  11296. bool Result;
  11297. if (Eval.evaluate(BO->getLHS(), Result)) {
  11298. if (Result)
  11299. Visit(BO->getRHS());
  11300. } else {
  11301. WorkList.push_back(BO->getRHS());
  11302. }
  11303. }
  11304. // Only visit the condition, unless we can be sure which subexpression will
  11305. // be chosen.
  11306. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  11307. EvaluationTracker Eval(*this);
  11308. {
  11309. SequencedSubexpression Sequenced(*this);
  11310. Visit(CO->getCond());
  11311. }
  11312. bool Result;
  11313. if (Eval.evaluate(CO->getCond(), Result))
  11314. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  11315. else {
  11316. WorkList.push_back(CO->getTrueExpr());
  11317. WorkList.push_back(CO->getFalseExpr());
  11318. }
  11319. }
  11320. void VisitCallExpr(CallExpr *CE) {
  11321. // C++11 [intro.execution]p15:
  11322. // When calling a function [...], every value computation and side effect
  11323. // associated with any argument expression, or with the postfix expression
  11324. // designating the called function, is sequenced before execution of every
  11325. // expression or statement in the body of the function [and thus before
  11326. // the value computation of its result].
  11327. SequencedSubexpression Sequenced(*this);
  11328. Base::VisitCallExpr(CE);
  11329. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  11330. }
  11331. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  11332. // This is a call, so all subexpressions are sequenced before the result.
  11333. SequencedSubexpression Sequenced(*this);
  11334. if (!CCE->isListInitialization())
  11335. return VisitExpr(CCE);
  11336. // In C++11, list initializations are sequenced.
  11337. SmallVector<SequenceTree::Seq, 32> Elts;
  11338. SequenceTree::Seq Parent = Region;
  11339. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  11340. E = CCE->arg_end();
  11341. I != E; ++I) {
  11342. Region = Tree.allocate(Parent);
  11343. Elts.push_back(Region);
  11344. Visit(*I);
  11345. }
  11346. // Forget that the initializers are sequenced.
  11347. Region = Parent;
  11348. for (unsigned I = 0; I < Elts.size(); ++I)
  11349. Tree.merge(Elts[I]);
  11350. }
  11351. void VisitInitListExpr(InitListExpr *ILE) {
  11352. if (!SemaRef.getLangOpts().CPlusPlus11)
  11353. return VisitExpr(ILE);
  11354. // In C++11, list initializations are sequenced.
  11355. SmallVector<SequenceTree::Seq, 32> Elts;
  11356. SequenceTree::Seq Parent = Region;
  11357. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  11358. Expr *E = ILE->getInit(I);
  11359. if (!E) continue;
  11360. Region = Tree.allocate(Parent);
  11361. Elts.push_back(Region);
  11362. Visit(E);
  11363. }
  11364. // Forget that the initializers are sequenced.
  11365. Region = Parent;
  11366. for (unsigned I = 0; I < Elts.size(); ++I)
  11367. Tree.merge(Elts[I]);
  11368. }
  11369. };
  11370. } // namespace
  11371. void Sema::CheckUnsequencedOperations(Expr *E) {
  11372. SmallVector<Expr *, 8> WorkList;
  11373. WorkList.push_back(E);
  11374. while (!WorkList.empty()) {
  11375. Expr *Item = WorkList.pop_back_val();
  11376. SequenceChecker(*this, Item, WorkList);
  11377. }
  11378. }
  11379. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  11380. bool IsConstexpr) {
  11381. llvm::SaveAndRestore<bool> ConstantContext(
  11382. isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
  11383. CheckImplicitConversions(E, CheckLoc);
  11384. if (!E->isInstantiationDependent())
  11385. CheckUnsequencedOperations(E);
  11386. if (!IsConstexpr && !E->isValueDependent())
  11387. CheckForIntOverflow(E);
  11388. DiagnoseMisalignedMembers();
  11389. }
  11390. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  11391. FieldDecl *BitField,
  11392. Expr *Init) {
  11393. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  11394. }
  11395. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  11396. SourceLocation Loc) {
  11397. if (!PType->isVariablyModifiedType())
  11398. return;
  11399. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  11400. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  11401. return;
  11402. }
  11403. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  11404. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  11405. return;
  11406. }
  11407. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  11408. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  11409. return;
  11410. }
  11411. const ArrayType *AT = S.Context.getAsArrayType(PType);
  11412. if (!AT)
  11413. return;
  11414. if (AT->getSizeModifier() != ArrayType::Star) {
  11415. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  11416. return;
  11417. }
  11418. S.Diag(Loc, diag::err_array_star_in_function_definition);
  11419. }
  11420. /// CheckParmsForFunctionDef - Check that the parameters of the given
  11421. /// function are appropriate for the definition of a function. This
  11422. /// takes care of any checks that cannot be performed on the
  11423. /// declaration itself, e.g., that the types of each of the function
  11424. /// parameters are complete.
  11425. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  11426. bool CheckParameterNames) {
  11427. bool HasInvalidParm = false;
  11428. for (ParmVarDecl *Param : Parameters) {
  11429. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  11430. // function declarator that is part of a function definition of
  11431. // that function shall not have incomplete type.
  11432. //
  11433. // This is also C++ [dcl.fct]p6.
  11434. if (!Param->isInvalidDecl() &&
  11435. RequireCompleteType(Param->getLocation(), Param->getType(),
  11436. diag::err_typecheck_decl_incomplete_type)) {
  11437. Param->setInvalidDecl();
  11438. HasInvalidParm = true;
  11439. }
  11440. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  11441. // declaration of each parameter shall include an identifier.
  11442. if (CheckParameterNames &&
  11443. Param->getIdentifier() == nullptr &&
  11444. !Param->isImplicit() &&
  11445. !getLangOpts().CPlusPlus)
  11446. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11447. // C99 6.7.5.3p12:
  11448. // If the function declarator is not part of a definition of that
  11449. // function, parameters may have incomplete type and may use the [*]
  11450. // notation in their sequences of declarator specifiers to specify
  11451. // variable length array types.
  11452. QualType PType = Param->getOriginalType();
  11453. // FIXME: This diagnostic should point the '[*]' if source-location
  11454. // information is added for it.
  11455. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  11456. // If the parameter is a c++ class type and it has to be destructed in the
  11457. // callee function, declare the destructor so that it can be called by the
  11458. // callee function. Do not perform any direct access check on the dtor here.
  11459. if (!Param->isInvalidDecl()) {
  11460. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  11461. if (!ClassDecl->isInvalidDecl() &&
  11462. !ClassDecl->hasIrrelevantDestructor() &&
  11463. !ClassDecl->isDependentContext() &&
  11464. ClassDecl->isParamDestroyedInCallee()) {
  11465. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11466. MarkFunctionReferenced(Param->getLocation(), Destructor);
  11467. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  11468. }
  11469. }
  11470. }
  11471. // Parameters with the pass_object_size attribute only need to be marked
  11472. // constant at function definitions. Because we lack information about
  11473. // whether we're on a declaration or definition when we're instantiating the
  11474. // attribute, we need to check for constness here.
  11475. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  11476. if (!Param->getType().isConstQualified())
  11477. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  11478. << Attr->getSpelling() << 1;
  11479. // Check for parameter names shadowing fields from the class.
  11480. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  11481. // The owning context for the parameter should be the function, but we
  11482. // want to see if this function's declaration context is a record.
  11483. DeclContext *DC = Param->getDeclContext();
  11484. if (DC && DC->isFunctionOrMethod()) {
  11485. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  11486. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  11487. RD, /*DeclIsField*/ false);
  11488. }
  11489. }
  11490. }
  11491. return HasInvalidParm;
  11492. }
  11493. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  11494. /// or MemberExpr.
  11495. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  11496. ASTContext &Context) {
  11497. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  11498. return Context.getDeclAlign(DRE->getDecl());
  11499. if (const auto *ME = dyn_cast<MemberExpr>(E))
  11500. return Context.getDeclAlign(ME->getMemberDecl());
  11501. return TypeAlign;
  11502. }
  11503. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  11504. /// pointer cast increases the alignment requirements.
  11505. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  11506. // This is actually a lot of work to potentially be doing on every
  11507. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  11508. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  11509. return;
  11510. // Ignore dependent types.
  11511. if (T->isDependentType() || Op->getType()->isDependentType())
  11512. return;
  11513. // Require that the destination be a pointer type.
  11514. const PointerType *DestPtr = T->getAs<PointerType>();
  11515. if (!DestPtr) return;
  11516. // If the destination has alignment 1, we're done.
  11517. QualType DestPointee = DestPtr->getPointeeType();
  11518. if (DestPointee->isIncompleteType()) return;
  11519. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  11520. if (DestAlign.isOne()) return;
  11521. // Require that the source be a pointer type.
  11522. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  11523. if (!SrcPtr) return;
  11524. QualType SrcPointee = SrcPtr->getPointeeType();
  11525. // Whitelist casts from cv void*. We already implicitly
  11526. // whitelisted casts to cv void*, since they have alignment 1.
  11527. // Also whitelist casts involving incomplete types, which implicitly
  11528. // includes 'void'.
  11529. if (SrcPointee->isIncompleteType()) return;
  11530. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  11531. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  11532. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  11533. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  11534. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  11535. if (UO->getOpcode() == UO_AddrOf)
  11536. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  11537. }
  11538. if (SrcAlign >= DestAlign) return;
  11539. Diag(TRange.getBegin(), diag::warn_cast_align)
  11540. << Op->getType() << T
  11541. << static_cast<unsigned>(SrcAlign.getQuantity())
  11542. << static_cast<unsigned>(DestAlign.getQuantity())
  11543. << TRange << Op->getSourceRange();
  11544. }
  11545. /// Check whether this array fits the idiom of a size-one tail padded
  11546. /// array member of a struct.
  11547. ///
  11548. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  11549. /// commonly used to emulate flexible arrays in C89 code.
  11550. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  11551. const NamedDecl *ND) {
  11552. if (Size != 1 || !ND) return false;
  11553. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  11554. if (!FD) return false;
  11555. // Don't consider sizes resulting from macro expansions or template argument
  11556. // substitution to form C89 tail-padded arrays.
  11557. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  11558. while (TInfo) {
  11559. TypeLoc TL = TInfo->getTypeLoc();
  11560. // Look through typedefs.
  11561. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  11562. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  11563. TInfo = TDL->getTypeSourceInfo();
  11564. continue;
  11565. }
  11566. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  11567. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  11568. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  11569. return false;
  11570. }
  11571. break;
  11572. }
  11573. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  11574. if (!RD) return false;
  11575. if (RD->isUnion()) return false;
  11576. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11577. if (!CRD->isStandardLayout()) return false;
  11578. }
  11579. // See if this is the last field decl in the record.
  11580. const Decl *D = FD;
  11581. while ((D = D->getNextDeclInContext()))
  11582. if (isa<FieldDecl>(D))
  11583. return false;
  11584. return true;
  11585. }
  11586. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  11587. const ArraySubscriptExpr *ASE,
  11588. bool AllowOnePastEnd, bool IndexNegated) {
  11589. // Already diagnosed by the constant evaluator.
  11590. if (isConstantEvaluated())
  11591. return;
  11592. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  11593. if (IndexExpr->isValueDependent())
  11594. return;
  11595. const Type *EffectiveType =
  11596. BaseExpr->getType()->getPointeeOrArrayElementType();
  11597. BaseExpr = BaseExpr->IgnoreParenCasts();
  11598. const ConstantArrayType *ArrayTy =
  11599. Context.getAsConstantArrayType(BaseExpr->getType());
  11600. if (!ArrayTy)
  11601. return;
  11602. const Type *BaseType = ArrayTy->getElementType().getTypePtr();
  11603. if (EffectiveType->isDependentType() || BaseType->isDependentType())
  11604. return;
  11605. Expr::EvalResult Result;
  11606. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  11607. return;
  11608. llvm::APSInt index = Result.Val.getInt();
  11609. if (IndexNegated)
  11610. index = -index;
  11611. const NamedDecl *ND = nullptr;
  11612. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11613. ND = DRE->getDecl();
  11614. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11615. ND = ME->getMemberDecl();
  11616. if (index.isUnsigned() || !index.isNegative()) {
  11617. // It is possible that the type of the base expression after
  11618. // IgnoreParenCasts is incomplete, even though the type of the base
  11619. // expression before IgnoreParenCasts is complete (see PR39746 for an
  11620. // example). In this case we have no information about whether the array
  11621. // access exceeds the array bounds. However we can still diagnose an array
  11622. // access which precedes the array bounds.
  11623. if (BaseType->isIncompleteType())
  11624. return;
  11625. llvm::APInt size = ArrayTy->getSize();
  11626. if (!size.isStrictlyPositive())
  11627. return;
  11628. if (BaseType != EffectiveType) {
  11629. // Make sure we're comparing apples to apples when comparing index to size
  11630. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  11631. uint64_t array_typesize = Context.getTypeSize(BaseType);
  11632. // Handle ptrarith_typesize being zero, such as when casting to void*
  11633. if (!ptrarith_typesize) ptrarith_typesize = 1;
  11634. if (ptrarith_typesize != array_typesize) {
  11635. // There's a cast to a different size type involved
  11636. uint64_t ratio = array_typesize / ptrarith_typesize;
  11637. // TODO: Be smarter about handling cases where array_typesize is not a
  11638. // multiple of ptrarith_typesize
  11639. if (ptrarith_typesize * ratio == array_typesize)
  11640. size *= llvm::APInt(size.getBitWidth(), ratio);
  11641. }
  11642. }
  11643. if (size.getBitWidth() > index.getBitWidth())
  11644. index = index.zext(size.getBitWidth());
  11645. else if (size.getBitWidth() < index.getBitWidth())
  11646. size = size.zext(index.getBitWidth());
  11647. // For array subscripting the index must be less than size, but for pointer
  11648. // arithmetic also allow the index (offset) to be equal to size since
  11649. // computing the next address after the end of the array is legal and
  11650. // commonly done e.g. in C++ iterators and range-based for loops.
  11651. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  11652. return;
  11653. // Also don't warn for arrays of size 1 which are members of some
  11654. // structure. These are often used to approximate flexible arrays in C89
  11655. // code.
  11656. if (IsTailPaddedMemberArray(*this, size, ND))
  11657. return;
  11658. // Suppress the warning if the subscript expression (as identified by the
  11659. // ']' location) and the index expression are both from macro expansions
  11660. // within a system header.
  11661. if (ASE) {
  11662. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  11663. ASE->getRBracketLoc());
  11664. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  11665. SourceLocation IndexLoc =
  11666. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  11667. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  11668. return;
  11669. }
  11670. }
  11671. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  11672. if (ASE)
  11673. DiagID = diag::warn_array_index_exceeds_bounds;
  11674. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11675. PDiag(DiagID) << index.toString(10, true)
  11676. << size.toString(10, true)
  11677. << (unsigned)size.getLimitedValue(~0U)
  11678. << IndexExpr->getSourceRange());
  11679. } else {
  11680. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  11681. if (!ASE) {
  11682. DiagID = diag::warn_ptr_arith_precedes_bounds;
  11683. if (index.isNegative()) index = -index;
  11684. }
  11685. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11686. PDiag(DiagID) << index.toString(10, true)
  11687. << IndexExpr->getSourceRange());
  11688. }
  11689. if (!ND) {
  11690. // Try harder to find a NamedDecl to point at in the note.
  11691. while (const ArraySubscriptExpr *ASE =
  11692. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  11693. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  11694. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11695. ND = DRE->getDecl();
  11696. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11697. ND = ME->getMemberDecl();
  11698. }
  11699. if (ND)
  11700. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  11701. PDiag(diag::note_array_declared_here)
  11702. << ND->getDeclName());
  11703. }
  11704. void Sema::CheckArrayAccess(const Expr *expr) {
  11705. int AllowOnePastEnd = 0;
  11706. while (expr) {
  11707. expr = expr->IgnoreParenImpCasts();
  11708. switch (expr->getStmtClass()) {
  11709. case Stmt::ArraySubscriptExprClass: {
  11710. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  11711. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  11712. AllowOnePastEnd > 0);
  11713. expr = ASE->getBase();
  11714. break;
  11715. }
  11716. case Stmt::MemberExprClass: {
  11717. expr = cast<MemberExpr>(expr)->getBase();
  11718. break;
  11719. }
  11720. case Stmt::OMPArraySectionExprClass: {
  11721. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  11722. if (ASE->getLowerBound())
  11723. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  11724. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  11725. return;
  11726. }
  11727. case Stmt::UnaryOperatorClass: {
  11728. // Only unwrap the * and & unary operators
  11729. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  11730. expr = UO->getSubExpr();
  11731. switch (UO->getOpcode()) {
  11732. case UO_AddrOf:
  11733. AllowOnePastEnd++;
  11734. break;
  11735. case UO_Deref:
  11736. AllowOnePastEnd--;
  11737. break;
  11738. default:
  11739. return;
  11740. }
  11741. break;
  11742. }
  11743. case Stmt::ConditionalOperatorClass: {
  11744. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11745. if (const Expr *lhs = cond->getLHS())
  11746. CheckArrayAccess(lhs);
  11747. if (const Expr *rhs = cond->getRHS())
  11748. CheckArrayAccess(rhs);
  11749. return;
  11750. }
  11751. case Stmt::CXXOperatorCallExprClass: {
  11752. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11753. for (const auto *Arg : OCE->arguments())
  11754. CheckArrayAccess(Arg);
  11755. return;
  11756. }
  11757. default:
  11758. return;
  11759. }
  11760. }
  11761. }
  11762. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11763. namespace {
  11764. struct RetainCycleOwner {
  11765. VarDecl *Variable = nullptr;
  11766. SourceRange Range;
  11767. SourceLocation Loc;
  11768. bool Indirect = false;
  11769. RetainCycleOwner() = default;
  11770. void setLocsFrom(Expr *e) {
  11771. Loc = e->getExprLoc();
  11772. Range = e->getSourceRange();
  11773. }
  11774. };
  11775. } // namespace
  11776. /// Consider whether capturing the given variable can possibly lead to
  11777. /// a retain cycle.
  11778. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11779. // In ARC, it's captured strongly iff the variable has __strong
  11780. // lifetime. In MRR, it's captured strongly if the variable is
  11781. // __block and has an appropriate type.
  11782. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11783. return false;
  11784. owner.Variable = var;
  11785. if (ref)
  11786. owner.setLocsFrom(ref);
  11787. return true;
  11788. }
  11789. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11790. while (true) {
  11791. e = e->IgnoreParens();
  11792. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11793. switch (cast->getCastKind()) {
  11794. case CK_BitCast:
  11795. case CK_LValueBitCast:
  11796. case CK_LValueToRValue:
  11797. case CK_ARCReclaimReturnedObject:
  11798. e = cast->getSubExpr();
  11799. continue;
  11800. default:
  11801. return false;
  11802. }
  11803. }
  11804. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11805. ObjCIvarDecl *ivar = ref->getDecl();
  11806. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11807. return false;
  11808. // Try to find a retain cycle in the base.
  11809. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11810. return false;
  11811. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11812. owner.Indirect = true;
  11813. return true;
  11814. }
  11815. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11816. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11817. if (!var) return false;
  11818. return considerVariable(var, ref, owner);
  11819. }
  11820. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11821. if (member->isArrow()) return false;
  11822. // Don't count this as an indirect ownership.
  11823. e = member->getBase();
  11824. continue;
  11825. }
  11826. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11827. // Only pay attention to pseudo-objects on property references.
  11828. ObjCPropertyRefExpr *pre
  11829. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11830. ->IgnoreParens());
  11831. if (!pre) return false;
  11832. if (pre->isImplicitProperty()) return false;
  11833. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11834. if (!property->isRetaining() &&
  11835. !(property->getPropertyIvarDecl() &&
  11836. property->getPropertyIvarDecl()->getType()
  11837. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11838. return false;
  11839. owner.Indirect = true;
  11840. if (pre->isSuperReceiver()) {
  11841. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11842. if (!owner.Variable)
  11843. return false;
  11844. owner.Loc = pre->getLocation();
  11845. owner.Range = pre->getSourceRange();
  11846. return true;
  11847. }
  11848. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11849. ->getSourceExpr());
  11850. continue;
  11851. }
  11852. // Array ivars?
  11853. return false;
  11854. }
  11855. }
  11856. namespace {
  11857. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11858. ASTContext &Context;
  11859. VarDecl *Variable;
  11860. Expr *Capturer = nullptr;
  11861. bool VarWillBeReased = false;
  11862. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11863. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11864. Context(Context), Variable(variable) {}
  11865. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11866. if (ref->getDecl() == Variable && !Capturer)
  11867. Capturer = ref;
  11868. }
  11869. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11870. if (Capturer) return;
  11871. Visit(ref->getBase());
  11872. if (Capturer && ref->isFreeIvar())
  11873. Capturer = ref;
  11874. }
  11875. void VisitBlockExpr(BlockExpr *block) {
  11876. // Look inside nested blocks
  11877. if (block->getBlockDecl()->capturesVariable(Variable))
  11878. Visit(block->getBlockDecl()->getBody());
  11879. }
  11880. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11881. if (Capturer) return;
  11882. if (OVE->getSourceExpr())
  11883. Visit(OVE->getSourceExpr());
  11884. }
  11885. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11886. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11887. return;
  11888. Expr *LHS = BinOp->getLHS();
  11889. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11890. if (DRE->getDecl() != Variable)
  11891. return;
  11892. if (Expr *RHS = BinOp->getRHS()) {
  11893. RHS = RHS->IgnoreParenCasts();
  11894. llvm::APSInt Value;
  11895. VarWillBeReased =
  11896. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11897. }
  11898. }
  11899. }
  11900. };
  11901. } // namespace
  11902. /// Check whether the given argument is a block which captures a
  11903. /// variable.
  11904. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11905. assert(owner.Variable && owner.Loc.isValid());
  11906. e = e->IgnoreParenCasts();
  11907. // Look through [^{...} copy] and Block_copy(^{...}).
  11908. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11909. Selector Cmd = ME->getSelector();
  11910. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11911. e = ME->getInstanceReceiver();
  11912. if (!e)
  11913. return nullptr;
  11914. e = e->IgnoreParenCasts();
  11915. }
  11916. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11917. if (CE->getNumArgs() == 1) {
  11918. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11919. if (Fn) {
  11920. const IdentifierInfo *FnI = Fn->getIdentifier();
  11921. if (FnI && FnI->isStr("_Block_copy")) {
  11922. e = CE->getArg(0)->IgnoreParenCasts();
  11923. }
  11924. }
  11925. }
  11926. }
  11927. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11928. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11929. return nullptr;
  11930. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11931. visitor.Visit(block->getBlockDecl()->getBody());
  11932. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11933. }
  11934. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11935. RetainCycleOwner &owner) {
  11936. assert(capturer);
  11937. assert(owner.Variable && owner.Loc.isValid());
  11938. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11939. << owner.Variable << capturer->getSourceRange();
  11940. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11941. << owner.Indirect << owner.Range;
  11942. }
  11943. /// Check for a keyword selector that starts with the word 'add' or
  11944. /// 'set'.
  11945. static bool isSetterLikeSelector(Selector sel) {
  11946. if (sel.isUnarySelector()) return false;
  11947. StringRef str = sel.getNameForSlot(0);
  11948. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11949. if (str.startswith("set"))
  11950. str = str.substr(3);
  11951. else if (str.startswith("add")) {
  11952. // Specially whitelist 'addOperationWithBlock:'.
  11953. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11954. return false;
  11955. str = str.substr(3);
  11956. }
  11957. else
  11958. return false;
  11959. if (str.empty()) return true;
  11960. return !isLowercase(str.front());
  11961. }
  11962. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11963. ObjCMessageExpr *Message) {
  11964. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11965. Message->getReceiverInterface(),
  11966. NSAPI::ClassId_NSMutableArray);
  11967. if (!IsMutableArray) {
  11968. return None;
  11969. }
  11970. Selector Sel = Message->getSelector();
  11971. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11972. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11973. if (!MKOpt) {
  11974. return None;
  11975. }
  11976. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11977. switch (MK) {
  11978. case NSAPI::NSMutableArr_addObject:
  11979. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11980. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11981. return 0;
  11982. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11983. return 1;
  11984. default:
  11985. return None;
  11986. }
  11987. return None;
  11988. }
  11989. static
  11990. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11991. ObjCMessageExpr *Message) {
  11992. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11993. Message->getReceiverInterface(),
  11994. NSAPI::ClassId_NSMutableDictionary);
  11995. if (!IsMutableDictionary) {
  11996. return None;
  11997. }
  11998. Selector Sel = Message->getSelector();
  11999. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  12000. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  12001. if (!MKOpt) {
  12002. return None;
  12003. }
  12004. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  12005. switch (MK) {
  12006. case NSAPI::NSMutableDict_setObjectForKey:
  12007. case NSAPI::NSMutableDict_setValueForKey:
  12008. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  12009. return 0;
  12010. default:
  12011. return None;
  12012. }
  12013. return None;
  12014. }
  12015. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  12016. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  12017. Message->getReceiverInterface(),
  12018. NSAPI::ClassId_NSMutableSet);
  12019. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  12020. Message->getReceiverInterface(),
  12021. NSAPI::ClassId_NSMutableOrderedSet);
  12022. if (!IsMutableSet && !IsMutableOrderedSet) {
  12023. return None;
  12024. }
  12025. Selector Sel = Message->getSelector();
  12026. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  12027. if (!MKOpt) {
  12028. return None;
  12029. }
  12030. NSAPI::NSSetMethodKind MK = *MKOpt;
  12031. switch (MK) {
  12032. case NSAPI::NSMutableSet_addObject:
  12033. case NSAPI::NSOrderedSet_setObjectAtIndex:
  12034. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  12035. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  12036. return 0;
  12037. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  12038. return 1;
  12039. }
  12040. return None;
  12041. }
  12042. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  12043. if (!Message->isInstanceMessage()) {
  12044. return;
  12045. }
  12046. Optional<int> ArgOpt;
  12047. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  12048. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  12049. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  12050. return;
  12051. }
  12052. int ArgIndex = *ArgOpt;
  12053. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  12054. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  12055. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  12056. }
  12057. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  12058. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  12059. if (ArgRE->isObjCSelfExpr()) {
  12060. Diag(Message->getSourceRange().getBegin(),
  12061. diag::warn_objc_circular_container)
  12062. << ArgRE->getDecl() << StringRef("'super'");
  12063. }
  12064. }
  12065. } else {
  12066. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  12067. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  12068. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  12069. }
  12070. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  12071. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  12072. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  12073. ValueDecl *Decl = ReceiverRE->getDecl();
  12074. Diag(Message->getSourceRange().getBegin(),
  12075. diag::warn_objc_circular_container)
  12076. << Decl << Decl;
  12077. if (!ArgRE->isObjCSelfExpr()) {
  12078. Diag(Decl->getLocation(),
  12079. diag::note_objc_circular_container_declared_here)
  12080. << Decl;
  12081. }
  12082. }
  12083. }
  12084. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  12085. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  12086. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  12087. ObjCIvarDecl *Decl = IvarRE->getDecl();
  12088. Diag(Message->getSourceRange().getBegin(),
  12089. diag::warn_objc_circular_container)
  12090. << Decl << Decl;
  12091. Diag(Decl->getLocation(),
  12092. diag::note_objc_circular_container_declared_here)
  12093. << Decl;
  12094. }
  12095. }
  12096. }
  12097. }
  12098. }
  12099. /// Check a message send to see if it's likely to cause a retain cycle.
  12100. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  12101. // Only check instance methods whose selector looks like a setter.
  12102. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  12103. return;
  12104. // Try to find a variable that the receiver is strongly owned by.
  12105. RetainCycleOwner owner;
  12106. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  12107. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  12108. return;
  12109. } else {
  12110. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  12111. owner.Variable = getCurMethodDecl()->getSelfDecl();
  12112. owner.Loc = msg->getSuperLoc();
  12113. owner.Range = msg->getSuperLoc();
  12114. }
  12115. // Check whether the receiver is captured by any of the arguments.
  12116. const ObjCMethodDecl *MD = msg->getMethodDecl();
  12117. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  12118. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  12119. // noescape blocks should not be retained by the method.
  12120. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  12121. continue;
  12122. return diagnoseRetainCycle(*this, capturer, owner);
  12123. }
  12124. }
  12125. }
  12126. /// Check a property assign to see if it's likely to cause a retain cycle.
  12127. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  12128. RetainCycleOwner owner;
  12129. if (!findRetainCycleOwner(*this, receiver, owner))
  12130. return;
  12131. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  12132. diagnoseRetainCycle(*this, capturer, owner);
  12133. }
  12134. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  12135. RetainCycleOwner Owner;
  12136. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  12137. return;
  12138. // Because we don't have an expression for the variable, we have to set the
  12139. // location explicitly here.
  12140. Owner.Loc = Var->getLocation();
  12141. Owner.Range = Var->getSourceRange();
  12142. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  12143. diagnoseRetainCycle(*this, Capturer, Owner);
  12144. }
  12145. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  12146. Expr *RHS, bool isProperty) {
  12147. // Check if RHS is an Objective-C object literal, which also can get
  12148. // immediately zapped in a weak reference. Note that we explicitly
  12149. // allow ObjCStringLiterals, since those are designed to never really die.
  12150. RHS = RHS->IgnoreParenImpCasts();
  12151. // This enum needs to match with the 'select' in
  12152. // warn_objc_arc_literal_assign (off-by-1).
  12153. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  12154. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  12155. return false;
  12156. S.Diag(Loc, diag::warn_arc_literal_assign)
  12157. << (unsigned) Kind
  12158. << (isProperty ? 0 : 1)
  12159. << RHS->getSourceRange();
  12160. return true;
  12161. }
  12162. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  12163. Qualifiers::ObjCLifetime LT,
  12164. Expr *RHS, bool isProperty) {
  12165. // Strip off any implicit cast added to get to the one ARC-specific.
  12166. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  12167. if (cast->getCastKind() == CK_ARCConsumeObject) {
  12168. S.Diag(Loc, diag::warn_arc_retained_assign)
  12169. << (LT == Qualifiers::OCL_ExplicitNone)
  12170. << (isProperty ? 0 : 1)
  12171. << RHS->getSourceRange();
  12172. return true;
  12173. }
  12174. RHS = cast->getSubExpr();
  12175. }
  12176. if (LT == Qualifiers::OCL_Weak &&
  12177. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  12178. return true;
  12179. return false;
  12180. }
  12181. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  12182. QualType LHS, Expr *RHS) {
  12183. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  12184. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  12185. return false;
  12186. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  12187. return true;
  12188. return false;
  12189. }
  12190. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  12191. Expr *LHS, Expr *RHS) {
  12192. QualType LHSType;
  12193. // PropertyRef on LHS type need be directly obtained from
  12194. // its declaration as it has a PseudoType.
  12195. ObjCPropertyRefExpr *PRE
  12196. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  12197. if (PRE && !PRE->isImplicitProperty()) {
  12198. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  12199. if (PD)
  12200. LHSType = PD->getType();
  12201. }
  12202. if (LHSType.isNull())
  12203. LHSType = LHS->getType();
  12204. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  12205. if (LT == Qualifiers::OCL_Weak) {
  12206. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  12207. getCurFunction()->markSafeWeakUse(LHS);
  12208. }
  12209. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  12210. return;
  12211. // FIXME. Check for other life times.
  12212. if (LT != Qualifiers::OCL_None)
  12213. return;
  12214. if (PRE) {
  12215. if (PRE->isImplicitProperty())
  12216. return;
  12217. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  12218. if (!PD)
  12219. return;
  12220. unsigned Attributes = PD->getPropertyAttributes();
  12221. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  12222. // when 'assign' attribute was not explicitly specified
  12223. // by user, ignore it and rely on property type itself
  12224. // for lifetime info.
  12225. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  12226. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  12227. LHSType->isObjCRetainableType())
  12228. return;
  12229. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  12230. if (cast->getCastKind() == CK_ARCConsumeObject) {
  12231. Diag(Loc, diag::warn_arc_retained_property_assign)
  12232. << RHS->getSourceRange();
  12233. return;
  12234. }
  12235. RHS = cast->getSubExpr();
  12236. }
  12237. }
  12238. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  12239. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  12240. return;
  12241. }
  12242. }
  12243. }
  12244. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  12245. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  12246. SourceLocation StmtLoc,
  12247. const NullStmt *Body) {
  12248. // Do not warn if the body is a macro that expands to nothing, e.g:
  12249. //
  12250. // #define CALL(x)
  12251. // if (condition)
  12252. // CALL(0);
  12253. if (Body->hasLeadingEmptyMacro())
  12254. return false;
  12255. // Get line numbers of statement and body.
  12256. bool StmtLineInvalid;
  12257. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  12258. &StmtLineInvalid);
  12259. if (StmtLineInvalid)
  12260. return false;
  12261. bool BodyLineInvalid;
  12262. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  12263. &BodyLineInvalid);
  12264. if (BodyLineInvalid)
  12265. return false;
  12266. // Warn if null statement and body are on the same line.
  12267. if (StmtLine != BodyLine)
  12268. return false;
  12269. return true;
  12270. }
  12271. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  12272. const Stmt *Body,
  12273. unsigned DiagID) {
  12274. // Since this is a syntactic check, don't emit diagnostic for template
  12275. // instantiations, this just adds noise.
  12276. if (CurrentInstantiationScope)
  12277. return;
  12278. // The body should be a null statement.
  12279. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  12280. if (!NBody)
  12281. return;
  12282. // Do the usual checks.
  12283. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  12284. return;
  12285. Diag(NBody->getSemiLoc(), DiagID);
  12286. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12287. }
  12288. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  12289. const Stmt *PossibleBody) {
  12290. assert(!CurrentInstantiationScope); // Ensured by caller
  12291. SourceLocation StmtLoc;
  12292. const Stmt *Body;
  12293. unsigned DiagID;
  12294. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  12295. StmtLoc = FS->getRParenLoc();
  12296. Body = FS->getBody();
  12297. DiagID = diag::warn_empty_for_body;
  12298. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  12299. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  12300. Body = WS->getBody();
  12301. DiagID = diag::warn_empty_while_body;
  12302. } else
  12303. return; // Neither `for' nor `while'.
  12304. // The body should be a null statement.
  12305. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  12306. if (!NBody)
  12307. return;
  12308. // Skip expensive checks if diagnostic is disabled.
  12309. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  12310. return;
  12311. // Do the usual checks.
  12312. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  12313. return;
  12314. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  12315. // noise level low, emit diagnostics only if for/while is followed by a
  12316. // CompoundStmt, e.g.:
  12317. // for (int i = 0; i < n; i++);
  12318. // {
  12319. // a(i);
  12320. // }
  12321. // or if for/while is followed by a statement with more indentation
  12322. // than for/while itself:
  12323. // for (int i = 0; i < n; i++);
  12324. // a(i);
  12325. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  12326. if (!ProbableTypo) {
  12327. bool BodyColInvalid;
  12328. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  12329. PossibleBody->getBeginLoc(), &BodyColInvalid);
  12330. if (BodyColInvalid)
  12331. return;
  12332. bool StmtColInvalid;
  12333. unsigned StmtCol =
  12334. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  12335. if (StmtColInvalid)
  12336. return;
  12337. if (BodyCol > StmtCol)
  12338. ProbableTypo = true;
  12339. }
  12340. if (ProbableTypo) {
  12341. Diag(NBody->getSemiLoc(), DiagID);
  12342. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12343. }
  12344. }
  12345. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  12346. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  12347. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  12348. SourceLocation OpLoc) {
  12349. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  12350. return;
  12351. if (inTemplateInstantiation())
  12352. return;
  12353. // Strip parens and casts away.
  12354. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  12355. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  12356. // Check for a call expression
  12357. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  12358. if (!CE || CE->getNumArgs() != 1)
  12359. return;
  12360. // Check for a call to std::move
  12361. if (!CE->isCallToStdMove())
  12362. return;
  12363. // Get argument from std::move
  12364. RHSExpr = CE->getArg(0);
  12365. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  12366. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  12367. // Two DeclRefExpr's, check that the decls are the same.
  12368. if (LHSDeclRef && RHSDeclRef) {
  12369. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12370. return;
  12371. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12372. RHSDeclRef->getDecl()->getCanonicalDecl())
  12373. return;
  12374. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12375. << LHSExpr->getSourceRange()
  12376. << RHSExpr->getSourceRange();
  12377. return;
  12378. }
  12379. // Member variables require a different approach to check for self moves.
  12380. // MemberExpr's are the same if every nested MemberExpr refers to the same
  12381. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  12382. // the base Expr's are CXXThisExpr's.
  12383. const Expr *LHSBase = LHSExpr;
  12384. const Expr *RHSBase = RHSExpr;
  12385. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  12386. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  12387. if (!LHSME || !RHSME)
  12388. return;
  12389. while (LHSME && RHSME) {
  12390. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  12391. RHSME->getMemberDecl()->getCanonicalDecl())
  12392. return;
  12393. LHSBase = LHSME->getBase();
  12394. RHSBase = RHSME->getBase();
  12395. LHSME = dyn_cast<MemberExpr>(LHSBase);
  12396. RHSME = dyn_cast<MemberExpr>(RHSBase);
  12397. }
  12398. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  12399. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  12400. if (LHSDeclRef && RHSDeclRef) {
  12401. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12402. return;
  12403. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12404. RHSDeclRef->getDecl()->getCanonicalDecl())
  12405. return;
  12406. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12407. << LHSExpr->getSourceRange()
  12408. << RHSExpr->getSourceRange();
  12409. return;
  12410. }
  12411. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  12412. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12413. << LHSExpr->getSourceRange()
  12414. << RHSExpr->getSourceRange();
  12415. }
  12416. //===--- Layout compatibility ----------------------------------------------//
  12417. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  12418. /// Check if two enumeration types are layout-compatible.
  12419. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  12420. // C++11 [dcl.enum] p8:
  12421. // Two enumeration types are layout-compatible if they have the same
  12422. // underlying type.
  12423. return ED1->isComplete() && ED2->isComplete() &&
  12424. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  12425. }
  12426. /// Check if two fields are layout-compatible.
  12427. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  12428. FieldDecl *Field2) {
  12429. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  12430. return false;
  12431. if (Field1->isBitField() != Field2->isBitField())
  12432. return false;
  12433. if (Field1->isBitField()) {
  12434. // Make sure that the bit-fields are the same length.
  12435. unsigned Bits1 = Field1->getBitWidthValue(C);
  12436. unsigned Bits2 = Field2->getBitWidthValue(C);
  12437. if (Bits1 != Bits2)
  12438. return false;
  12439. }
  12440. return true;
  12441. }
  12442. /// Check if two standard-layout structs are layout-compatible.
  12443. /// (C++11 [class.mem] p17)
  12444. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  12445. RecordDecl *RD2) {
  12446. // If both records are C++ classes, check that base classes match.
  12447. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  12448. // If one of records is a CXXRecordDecl we are in C++ mode,
  12449. // thus the other one is a CXXRecordDecl, too.
  12450. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  12451. // Check number of base classes.
  12452. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  12453. return false;
  12454. // Check the base classes.
  12455. for (CXXRecordDecl::base_class_const_iterator
  12456. Base1 = D1CXX->bases_begin(),
  12457. BaseEnd1 = D1CXX->bases_end(),
  12458. Base2 = D2CXX->bases_begin();
  12459. Base1 != BaseEnd1;
  12460. ++Base1, ++Base2) {
  12461. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  12462. return false;
  12463. }
  12464. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  12465. // If only RD2 is a C++ class, it should have zero base classes.
  12466. if (D2CXX->getNumBases() > 0)
  12467. return false;
  12468. }
  12469. // Check the fields.
  12470. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  12471. Field2End = RD2->field_end(),
  12472. Field1 = RD1->field_begin(),
  12473. Field1End = RD1->field_end();
  12474. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  12475. if (!isLayoutCompatible(C, *Field1, *Field2))
  12476. return false;
  12477. }
  12478. if (Field1 != Field1End || Field2 != Field2End)
  12479. return false;
  12480. return true;
  12481. }
  12482. /// Check if two standard-layout unions are layout-compatible.
  12483. /// (C++11 [class.mem] p18)
  12484. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  12485. RecordDecl *RD2) {
  12486. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  12487. for (auto *Field2 : RD2->fields())
  12488. UnmatchedFields.insert(Field2);
  12489. for (auto *Field1 : RD1->fields()) {
  12490. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  12491. I = UnmatchedFields.begin(),
  12492. E = UnmatchedFields.end();
  12493. for ( ; I != E; ++I) {
  12494. if (isLayoutCompatible(C, Field1, *I)) {
  12495. bool Result = UnmatchedFields.erase(*I);
  12496. (void) Result;
  12497. assert(Result);
  12498. break;
  12499. }
  12500. }
  12501. if (I == E)
  12502. return false;
  12503. }
  12504. return UnmatchedFields.empty();
  12505. }
  12506. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  12507. RecordDecl *RD2) {
  12508. if (RD1->isUnion() != RD2->isUnion())
  12509. return false;
  12510. if (RD1->isUnion())
  12511. return isLayoutCompatibleUnion(C, RD1, RD2);
  12512. else
  12513. return isLayoutCompatibleStruct(C, RD1, RD2);
  12514. }
  12515. /// Check if two types are layout-compatible in C++11 sense.
  12516. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  12517. if (T1.isNull() || T2.isNull())
  12518. return false;
  12519. // C++11 [basic.types] p11:
  12520. // If two types T1 and T2 are the same type, then T1 and T2 are
  12521. // layout-compatible types.
  12522. if (C.hasSameType(T1, T2))
  12523. return true;
  12524. T1 = T1.getCanonicalType().getUnqualifiedType();
  12525. T2 = T2.getCanonicalType().getUnqualifiedType();
  12526. const Type::TypeClass TC1 = T1->getTypeClass();
  12527. const Type::TypeClass TC2 = T2->getTypeClass();
  12528. if (TC1 != TC2)
  12529. return false;
  12530. if (TC1 == Type::Enum) {
  12531. return isLayoutCompatible(C,
  12532. cast<EnumType>(T1)->getDecl(),
  12533. cast<EnumType>(T2)->getDecl());
  12534. } else if (TC1 == Type::Record) {
  12535. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  12536. return false;
  12537. return isLayoutCompatible(C,
  12538. cast<RecordType>(T1)->getDecl(),
  12539. cast<RecordType>(T2)->getDecl());
  12540. }
  12541. return false;
  12542. }
  12543. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  12544. /// Given a type tag expression find the type tag itself.
  12545. ///
  12546. /// \param TypeExpr Type tag expression, as it appears in user's code.
  12547. ///
  12548. /// \param VD Declaration of an identifier that appears in a type tag.
  12549. ///
  12550. /// \param MagicValue Type tag magic value.
  12551. ///
  12552. /// \param isConstantEvaluated wether the evalaution should be performed in
  12553. /// constant context.
  12554. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  12555. const ValueDecl **VD, uint64_t *MagicValue,
  12556. bool isConstantEvaluated) {
  12557. while(true) {
  12558. if (!TypeExpr)
  12559. return false;
  12560. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  12561. switch (TypeExpr->getStmtClass()) {
  12562. case Stmt::UnaryOperatorClass: {
  12563. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  12564. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  12565. TypeExpr = UO->getSubExpr();
  12566. continue;
  12567. }
  12568. return false;
  12569. }
  12570. case Stmt::DeclRefExprClass: {
  12571. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  12572. *VD = DRE->getDecl();
  12573. return true;
  12574. }
  12575. case Stmt::IntegerLiteralClass: {
  12576. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  12577. llvm::APInt MagicValueAPInt = IL->getValue();
  12578. if (MagicValueAPInt.getActiveBits() <= 64) {
  12579. *MagicValue = MagicValueAPInt.getZExtValue();
  12580. return true;
  12581. } else
  12582. return false;
  12583. }
  12584. case Stmt::BinaryConditionalOperatorClass:
  12585. case Stmt::ConditionalOperatorClass: {
  12586. const AbstractConditionalOperator *ACO =
  12587. cast<AbstractConditionalOperator>(TypeExpr);
  12588. bool Result;
  12589. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
  12590. isConstantEvaluated)) {
  12591. if (Result)
  12592. TypeExpr = ACO->getTrueExpr();
  12593. else
  12594. TypeExpr = ACO->getFalseExpr();
  12595. continue;
  12596. }
  12597. return false;
  12598. }
  12599. case Stmt::BinaryOperatorClass: {
  12600. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  12601. if (BO->getOpcode() == BO_Comma) {
  12602. TypeExpr = BO->getRHS();
  12603. continue;
  12604. }
  12605. return false;
  12606. }
  12607. default:
  12608. return false;
  12609. }
  12610. }
  12611. }
  12612. /// Retrieve the C type corresponding to type tag TypeExpr.
  12613. ///
  12614. /// \param TypeExpr Expression that specifies a type tag.
  12615. ///
  12616. /// \param MagicValues Registered magic values.
  12617. ///
  12618. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  12619. /// kind.
  12620. ///
  12621. /// \param TypeInfo Information about the corresponding C type.
  12622. ///
  12623. /// \param isConstantEvaluated wether the evalaution should be performed in
  12624. /// constant context.
  12625. ///
  12626. /// \returns true if the corresponding C type was found.
  12627. static bool GetMatchingCType(
  12628. const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
  12629. const ASTContext &Ctx,
  12630. const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
  12631. *MagicValues,
  12632. bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
  12633. bool isConstantEvaluated) {
  12634. FoundWrongKind = false;
  12635. // Variable declaration that has type_tag_for_datatype attribute.
  12636. const ValueDecl *VD = nullptr;
  12637. uint64_t MagicValue;
  12638. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
  12639. return false;
  12640. if (VD) {
  12641. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  12642. if (I->getArgumentKind() != ArgumentKind) {
  12643. FoundWrongKind = true;
  12644. return false;
  12645. }
  12646. TypeInfo.Type = I->getMatchingCType();
  12647. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  12648. TypeInfo.MustBeNull = I->getMustBeNull();
  12649. return true;
  12650. }
  12651. return false;
  12652. }
  12653. if (!MagicValues)
  12654. return false;
  12655. llvm::DenseMap<Sema::TypeTagMagicValue,
  12656. Sema::TypeTagData>::const_iterator I =
  12657. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  12658. if (I == MagicValues->end())
  12659. return false;
  12660. TypeInfo = I->second;
  12661. return true;
  12662. }
  12663. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  12664. uint64_t MagicValue, QualType Type,
  12665. bool LayoutCompatible,
  12666. bool MustBeNull) {
  12667. if (!TypeTagForDatatypeMagicValues)
  12668. TypeTagForDatatypeMagicValues.reset(
  12669. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  12670. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  12671. (*TypeTagForDatatypeMagicValues)[Magic] =
  12672. TypeTagData(Type, LayoutCompatible, MustBeNull);
  12673. }
  12674. static bool IsSameCharType(QualType T1, QualType T2) {
  12675. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  12676. if (!BT1)
  12677. return false;
  12678. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  12679. if (!BT2)
  12680. return false;
  12681. BuiltinType::Kind T1Kind = BT1->getKind();
  12682. BuiltinType::Kind T2Kind = BT2->getKind();
  12683. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  12684. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  12685. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  12686. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  12687. }
  12688. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  12689. const ArrayRef<const Expr *> ExprArgs,
  12690. SourceLocation CallSiteLoc) {
  12691. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  12692. bool IsPointerAttr = Attr->getIsPointer();
  12693. // Retrieve the argument representing the 'type_tag'.
  12694. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  12695. if (TypeTagIdxAST >= ExprArgs.size()) {
  12696. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12697. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  12698. return;
  12699. }
  12700. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  12701. bool FoundWrongKind;
  12702. TypeTagData TypeInfo;
  12703. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  12704. TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
  12705. TypeInfo, isConstantEvaluated())) {
  12706. if (FoundWrongKind)
  12707. Diag(TypeTagExpr->getExprLoc(),
  12708. diag::warn_type_tag_for_datatype_wrong_kind)
  12709. << TypeTagExpr->getSourceRange();
  12710. return;
  12711. }
  12712. // Retrieve the argument representing the 'arg_idx'.
  12713. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  12714. if (ArgumentIdxAST >= ExprArgs.size()) {
  12715. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12716. << 1 << Attr->getArgumentIdx().getSourceIndex();
  12717. return;
  12718. }
  12719. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  12720. if (IsPointerAttr) {
  12721. // Skip implicit cast of pointer to `void *' (as a function argument).
  12722. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  12723. if (ICE->getType()->isVoidPointerType() &&
  12724. ICE->getCastKind() == CK_BitCast)
  12725. ArgumentExpr = ICE->getSubExpr();
  12726. }
  12727. QualType ArgumentType = ArgumentExpr->getType();
  12728. // Passing a `void*' pointer shouldn't trigger a warning.
  12729. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  12730. return;
  12731. if (TypeInfo.MustBeNull) {
  12732. // Type tag with matching void type requires a null pointer.
  12733. if (!ArgumentExpr->isNullPointerConstant(Context,
  12734. Expr::NPC_ValueDependentIsNotNull)) {
  12735. Diag(ArgumentExpr->getExprLoc(),
  12736. diag::warn_type_safety_null_pointer_required)
  12737. << ArgumentKind->getName()
  12738. << ArgumentExpr->getSourceRange()
  12739. << TypeTagExpr->getSourceRange();
  12740. }
  12741. return;
  12742. }
  12743. QualType RequiredType = TypeInfo.Type;
  12744. if (IsPointerAttr)
  12745. RequiredType = Context.getPointerType(RequiredType);
  12746. bool mismatch = false;
  12747. if (!TypeInfo.LayoutCompatible) {
  12748. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12749. // C++11 [basic.fundamental] p1:
  12750. // Plain char, signed char, and unsigned char are three distinct types.
  12751. //
  12752. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12753. // char' depending on the current char signedness mode.
  12754. if (mismatch)
  12755. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12756. RequiredType->getPointeeType())) ||
  12757. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12758. mismatch = false;
  12759. } else
  12760. if (IsPointerAttr)
  12761. mismatch = !isLayoutCompatible(Context,
  12762. ArgumentType->getPointeeType(),
  12763. RequiredType->getPointeeType());
  12764. else
  12765. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12766. if (mismatch)
  12767. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12768. << ArgumentType << ArgumentKind
  12769. << TypeInfo.LayoutCompatible << RequiredType
  12770. << ArgumentExpr->getSourceRange()
  12771. << TypeTagExpr->getSourceRange();
  12772. }
  12773. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12774. CharUnits Alignment) {
  12775. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12776. }
  12777. void Sema::DiagnoseMisalignedMembers() {
  12778. for (MisalignedMember &m : MisalignedMembers) {
  12779. const NamedDecl *ND = m.RD;
  12780. if (ND->getName().empty()) {
  12781. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12782. ND = TD;
  12783. }
  12784. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12785. << m.MD << ND << m.E->getSourceRange();
  12786. }
  12787. MisalignedMembers.clear();
  12788. }
  12789. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12790. E = E->IgnoreParens();
  12791. if (!T->isPointerType() && !T->isIntegerType())
  12792. return;
  12793. if (isa<UnaryOperator>(E) &&
  12794. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12795. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12796. if (isa<MemberExpr>(Op)) {
  12797. auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  12798. if (MA != MisalignedMembers.end() &&
  12799. (T->isIntegerType() ||
  12800. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12801. Context.getTypeAlignInChars(
  12802. T->getPointeeType()) <= MA->Alignment))))
  12803. MisalignedMembers.erase(MA);
  12804. }
  12805. }
  12806. }
  12807. void Sema::RefersToMemberWithReducedAlignment(
  12808. Expr *E,
  12809. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12810. Action) {
  12811. const auto *ME = dyn_cast<MemberExpr>(E);
  12812. if (!ME)
  12813. return;
  12814. // No need to check expressions with an __unaligned-qualified type.
  12815. if (E->getType().getQualifiers().hasUnaligned())
  12816. return;
  12817. // For a chain of MemberExpr like "a.b.c.d" this list
  12818. // will keep FieldDecl's like [d, c, b].
  12819. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12820. const MemberExpr *TopME = nullptr;
  12821. bool AnyIsPacked = false;
  12822. do {
  12823. QualType BaseType = ME->getBase()->getType();
  12824. if (ME->isArrow())
  12825. BaseType = BaseType->getPointeeType();
  12826. RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
  12827. if (RD->isInvalidDecl())
  12828. return;
  12829. ValueDecl *MD = ME->getMemberDecl();
  12830. auto *FD = dyn_cast<FieldDecl>(MD);
  12831. // We do not care about non-data members.
  12832. if (!FD || FD->isInvalidDecl())
  12833. return;
  12834. AnyIsPacked =
  12835. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12836. ReverseMemberChain.push_back(FD);
  12837. TopME = ME;
  12838. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12839. } while (ME);
  12840. assert(TopME && "We did not compute a topmost MemberExpr!");
  12841. // Not the scope of this diagnostic.
  12842. if (!AnyIsPacked)
  12843. return;
  12844. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12845. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12846. // TODO: The innermost base of the member expression may be too complicated.
  12847. // For now, just disregard these cases. This is left for future
  12848. // improvement.
  12849. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12850. return;
  12851. // Alignment expected by the whole expression.
  12852. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12853. // No need to do anything else with this case.
  12854. if (ExpectedAlignment.isOne())
  12855. return;
  12856. // Synthesize offset of the whole access.
  12857. CharUnits Offset;
  12858. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12859. I++) {
  12860. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12861. }
  12862. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12863. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12864. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12865. // The base expression of the innermost MemberExpr may give
  12866. // stronger guarantees than the class containing the member.
  12867. if (DRE && !TopME->isArrow()) {
  12868. const ValueDecl *VD = DRE->getDecl();
  12869. if (!VD->getType()->isReferenceType())
  12870. CompleteObjectAlignment =
  12871. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12872. }
  12873. // Check if the synthesized offset fulfills the alignment.
  12874. if (Offset % ExpectedAlignment != 0 ||
  12875. // It may fulfill the offset it but the effective alignment may still be
  12876. // lower than the expected expression alignment.
  12877. CompleteObjectAlignment < ExpectedAlignment) {
  12878. // If this happens, we want to determine a sensible culprit of this.
  12879. // Intuitively, watching the chain of member expressions from right to
  12880. // left, we start with the required alignment (as required by the field
  12881. // type) but some packed attribute in that chain has reduced the alignment.
  12882. // It may happen that another packed structure increases it again. But if
  12883. // we are here such increase has not been enough. So pointing the first
  12884. // FieldDecl that either is packed or else its RecordDecl is,
  12885. // seems reasonable.
  12886. FieldDecl *FD = nullptr;
  12887. CharUnits Alignment;
  12888. for (FieldDecl *FDI : ReverseMemberChain) {
  12889. if (FDI->hasAttr<PackedAttr>() ||
  12890. FDI->getParent()->hasAttr<PackedAttr>()) {
  12891. FD = FDI;
  12892. Alignment = std::min(
  12893. Context.getTypeAlignInChars(FD->getType()),
  12894. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12895. break;
  12896. }
  12897. }
  12898. assert(FD && "We did not find a packed FieldDecl!");
  12899. Action(E, FD->getParent(), FD, Alignment);
  12900. }
  12901. }
  12902. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12903. using namespace std::placeholders;
  12904. RefersToMemberWithReducedAlignment(
  12905. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12906. _2, _3, _4));
  12907. }