SemaChecking.cpp 229 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211
  1. //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/Initialization.h"
  15. #include "clang/Sema/Sema.h"
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/Sema/Initialization.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/ScopeInfo.h"
  20. #include "clang/Analysis/Analyses/FormatString.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/EvaluatedExprVisitor.h"
  29. #include "clang/AST/DeclObjC.h"
  30. #include "clang/AST/StmtCXX.h"
  31. #include "clang/AST/StmtObjC.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "llvm/ADT/BitVector.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include "clang/Basic/TargetBuiltins.h"
  38. #include "clang/Basic/TargetInfo.h"
  39. #include "clang/Basic/ConvertUTF.h"
  40. #include <limits>
  41. using namespace clang;
  42. using namespace sema;
  43. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  44. unsigned ByteNo) const {
  45. return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
  46. PP.getLangOpts(), PP.getTargetInfo());
  47. }
  48. /// Checks that a call expression's argument count is the desired number.
  49. /// This is useful when doing custom type-checking. Returns true on error.
  50. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  51. unsigned argCount = call->getNumArgs();
  52. if (argCount == desiredArgCount) return false;
  53. if (argCount < desiredArgCount)
  54. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  55. << 0 /*function call*/ << desiredArgCount << argCount
  56. << call->getSourceRange();
  57. // Highlight all the excess arguments.
  58. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  59. call->getArg(argCount - 1)->getLocEnd());
  60. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  61. << 0 /*function call*/ << desiredArgCount << argCount
  62. << call->getArg(1)->getSourceRange();
  63. }
  64. /// Check that the first argument to __builtin_annotation is an integer
  65. /// and the second argument is a non-wide string literal.
  66. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  67. if (checkArgCount(S, TheCall, 2))
  68. return true;
  69. // First argument should be an integer.
  70. Expr *ValArg = TheCall->getArg(0);
  71. QualType Ty = ValArg->getType();
  72. if (!Ty->isIntegerType()) {
  73. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  74. << ValArg->getSourceRange();
  75. return true;
  76. }
  77. // Second argument should be a constant string.
  78. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  79. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  80. if (!Literal || !Literal->isAscii()) {
  81. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  82. << StrArg->getSourceRange();
  83. return true;
  84. }
  85. TheCall->setType(Ty);
  86. return false;
  87. }
  88. ExprResult
  89. Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  90. ExprResult TheCallResult(Owned(TheCall));
  91. // Find out if any arguments are required to be integer constant expressions.
  92. unsigned ICEArguments = 0;
  93. ASTContext::GetBuiltinTypeError Error;
  94. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  95. if (Error != ASTContext::GE_None)
  96. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  97. // If any arguments are required to be ICE's, check and diagnose.
  98. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  99. // Skip arguments not required to be ICE's.
  100. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  101. llvm::APSInt Result;
  102. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  103. return true;
  104. ICEArguments &= ~(1 << ArgNo);
  105. }
  106. switch (BuiltinID) {
  107. case Builtin::BI__builtin___CFStringMakeConstantString:
  108. assert(TheCall->getNumArgs() == 1 &&
  109. "Wrong # arguments to builtin CFStringMakeConstantString");
  110. if (CheckObjCString(TheCall->getArg(0)))
  111. return ExprError();
  112. break;
  113. case Builtin::BI__builtin_stdarg_start:
  114. case Builtin::BI__builtin_va_start:
  115. if (SemaBuiltinVAStart(TheCall))
  116. return ExprError();
  117. break;
  118. case Builtin::BI__builtin_isgreater:
  119. case Builtin::BI__builtin_isgreaterequal:
  120. case Builtin::BI__builtin_isless:
  121. case Builtin::BI__builtin_islessequal:
  122. case Builtin::BI__builtin_islessgreater:
  123. case Builtin::BI__builtin_isunordered:
  124. if (SemaBuiltinUnorderedCompare(TheCall))
  125. return ExprError();
  126. break;
  127. case Builtin::BI__builtin_fpclassify:
  128. if (SemaBuiltinFPClassification(TheCall, 6))
  129. return ExprError();
  130. break;
  131. case Builtin::BI__builtin_isfinite:
  132. case Builtin::BI__builtin_isinf:
  133. case Builtin::BI__builtin_isinf_sign:
  134. case Builtin::BI__builtin_isnan:
  135. case Builtin::BI__builtin_isnormal:
  136. if (SemaBuiltinFPClassification(TheCall, 1))
  137. return ExprError();
  138. break;
  139. case Builtin::BI__builtin_shufflevector:
  140. return SemaBuiltinShuffleVector(TheCall);
  141. // TheCall will be freed by the smart pointer here, but that's fine, since
  142. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  143. case Builtin::BI__builtin_prefetch:
  144. if (SemaBuiltinPrefetch(TheCall))
  145. return ExprError();
  146. break;
  147. case Builtin::BI__builtin_object_size:
  148. if (SemaBuiltinObjectSize(TheCall))
  149. return ExprError();
  150. break;
  151. case Builtin::BI__builtin_longjmp:
  152. if (SemaBuiltinLongjmp(TheCall))
  153. return ExprError();
  154. break;
  155. case Builtin::BI__builtin_classify_type:
  156. if (checkArgCount(*this, TheCall, 1)) return true;
  157. TheCall->setType(Context.IntTy);
  158. break;
  159. case Builtin::BI__builtin_constant_p:
  160. if (checkArgCount(*this, TheCall, 1)) return true;
  161. TheCall->setType(Context.IntTy);
  162. break;
  163. case Builtin::BI__sync_fetch_and_add:
  164. case Builtin::BI__sync_fetch_and_add_1:
  165. case Builtin::BI__sync_fetch_and_add_2:
  166. case Builtin::BI__sync_fetch_and_add_4:
  167. case Builtin::BI__sync_fetch_and_add_8:
  168. case Builtin::BI__sync_fetch_and_add_16:
  169. case Builtin::BI__sync_fetch_and_sub:
  170. case Builtin::BI__sync_fetch_and_sub_1:
  171. case Builtin::BI__sync_fetch_and_sub_2:
  172. case Builtin::BI__sync_fetch_and_sub_4:
  173. case Builtin::BI__sync_fetch_and_sub_8:
  174. case Builtin::BI__sync_fetch_and_sub_16:
  175. case Builtin::BI__sync_fetch_and_or:
  176. case Builtin::BI__sync_fetch_and_or_1:
  177. case Builtin::BI__sync_fetch_and_or_2:
  178. case Builtin::BI__sync_fetch_and_or_4:
  179. case Builtin::BI__sync_fetch_and_or_8:
  180. case Builtin::BI__sync_fetch_and_or_16:
  181. case Builtin::BI__sync_fetch_and_and:
  182. case Builtin::BI__sync_fetch_and_and_1:
  183. case Builtin::BI__sync_fetch_and_and_2:
  184. case Builtin::BI__sync_fetch_and_and_4:
  185. case Builtin::BI__sync_fetch_and_and_8:
  186. case Builtin::BI__sync_fetch_and_and_16:
  187. case Builtin::BI__sync_fetch_and_xor:
  188. case Builtin::BI__sync_fetch_and_xor_1:
  189. case Builtin::BI__sync_fetch_and_xor_2:
  190. case Builtin::BI__sync_fetch_and_xor_4:
  191. case Builtin::BI__sync_fetch_and_xor_8:
  192. case Builtin::BI__sync_fetch_and_xor_16:
  193. case Builtin::BI__sync_add_and_fetch:
  194. case Builtin::BI__sync_add_and_fetch_1:
  195. case Builtin::BI__sync_add_and_fetch_2:
  196. case Builtin::BI__sync_add_and_fetch_4:
  197. case Builtin::BI__sync_add_and_fetch_8:
  198. case Builtin::BI__sync_add_and_fetch_16:
  199. case Builtin::BI__sync_sub_and_fetch:
  200. case Builtin::BI__sync_sub_and_fetch_1:
  201. case Builtin::BI__sync_sub_and_fetch_2:
  202. case Builtin::BI__sync_sub_and_fetch_4:
  203. case Builtin::BI__sync_sub_and_fetch_8:
  204. case Builtin::BI__sync_sub_and_fetch_16:
  205. case Builtin::BI__sync_and_and_fetch:
  206. case Builtin::BI__sync_and_and_fetch_1:
  207. case Builtin::BI__sync_and_and_fetch_2:
  208. case Builtin::BI__sync_and_and_fetch_4:
  209. case Builtin::BI__sync_and_and_fetch_8:
  210. case Builtin::BI__sync_and_and_fetch_16:
  211. case Builtin::BI__sync_or_and_fetch:
  212. case Builtin::BI__sync_or_and_fetch_1:
  213. case Builtin::BI__sync_or_and_fetch_2:
  214. case Builtin::BI__sync_or_and_fetch_4:
  215. case Builtin::BI__sync_or_and_fetch_8:
  216. case Builtin::BI__sync_or_and_fetch_16:
  217. case Builtin::BI__sync_xor_and_fetch:
  218. case Builtin::BI__sync_xor_and_fetch_1:
  219. case Builtin::BI__sync_xor_and_fetch_2:
  220. case Builtin::BI__sync_xor_and_fetch_4:
  221. case Builtin::BI__sync_xor_and_fetch_8:
  222. case Builtin::BI__sync_xor_and_fetch_16:
  223. case Builtin::BI__sync_val_compare_and_swap:
  224. case Builtin::BI__sync_val_compare_and_swap_1:
  225. case Builtin::BI__sync_val_compare_and_swap_2:
  226. case Builtin::BI__sync_val_compare_and_swap_4:
  227. case Builtin::BI__sync_val_compare_and_swap_8:
  228. case Builtin::BI__sync_val_compare_and_swap_16:
  229. case Builtin::BI__sync_bool_compare_and_swap:
  230. case Builtin::BI__sync_bool_compare_and_swap_1:
  231. case Builtin::BI__sync_bool_compare_and_swap_2:
  232. case Builtin::BI__sync_bool_compare_and_swap_4:
  233. case Builtin::BI__sync_bool_compare_and_swap_8:
  234. case Builtin::BI__sync_bool_compare_and_swap_16:
  235. case Builtin::BI__sync_lock_test_and_set:
  236. case Builtin::BI__sync_lock_test_and_set_1:
  237. case Builtin::BI__sync_lock_test_and_set_2:
  238. case Builtin::BI__sync_lock_test_and_set_4:
  239. case Builtin::BI__sync_lock_test_and_set_8:
  240. case Builtin::BI__sync_lock_test_and_set_16:
  241. case Builtin::BI__sync_lock_release:
  242. case Builtin::BI__sync_lock_release_1:
  243. case Builtin::BI__sync_lock_release_2:
  244. case Builtin::BI__sync_lock_release_4:
  245. case Builtin::BI__sync_lock_release_8:
  246. case Builtin::BI__sync_lock_release_16:
  247. case Builtin::BI__sync_swap:
  248. case Builtin::BI__sync_swap_1:
  249. case Builtin::BI__sync_swap_2:
  250. case Builtin::BI__sync_swap_4:
  251. case Builtin::BI__sync_swap_8:
  252. case Builtin::BI__sync_swap_16:
  253. return SemaBuiltinAtomicOverloaded(TheCallResult);
  254. #define BUILTIN(ID, TYPE, ATTRS)
  255. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  256. case Builtin::BI##ID: \
  257. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  258. #include "clang/Basic/Builtins.def"
  259. case Builtin::BI__builtin_annotation:
  260. if (SemaBuiltinAnnotation(*this, TheCall))
  261. return ExprError();
  262. break;
  263. }
  264. // Since the target specific builtins for each arch overlap, only check those
  265. // of the arch we are compiling for.
  266. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  267. switch (Context.getTargetInfo().getTriple().getArch()) {
  268. case llvm::Triple::arm:
  269. case llvm::Triple::thumb:
  270. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  271. return ExprError();
  272. break;
  273. case llvm::Triple::mips:
  274. case llvm::Triple::mipsel:
  275. case llvm::Triple::mips64:
  276. case llvm::Triple::mips64el:
  277. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  278. return ExprError();
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. return TheCallResult;
  285. }
  286. // Get the valid immediate range for the specified NEON type code.
  287. static unsigned RFT(unsigned t, bool shift = false) {
  288. NeonTypeFlags Type(t);
  289. int IsQuad = Type.isQuad();
  290. switch (Type.getEltType()) {
  291. case NeonTypeFlags::Int8:
  292. case NeonTypeFlags::Poly8:
  293. return shift ? 7 : (8 << IsQuad) - 1;
  294. case NeonTypeFlags::Int16:
  295. case NeonTypeFlags::Poly16:
  296. return shift ? 15 : (4 << IsQuad) - 1;
  297. case NeonTypeFlags::Int32:
  298. return shift ? 31 : (2 << IsQuad) - 1;
  299. case NeonTypeFlags::Int64:
  300. return shift ? 63 : (1 << IsQuad) - 1;
  301. case NeonTypeFlags::Float16:
  302. assert(!shift && "cannot shift float types!");
  303. return (4 << IsQuad) - 1;
  304. case NeonTypeFlags::Float32:
  305. assert(!shift && "cannot shift float types!");
  306. return (2 << IsQuad) - 1;
  307. }
  308. llvm_unreachable("Invalid NeonTypeFlag!");
  309. }
  310. /// getNeonEltType - Return the QualType corresponding to the elements of
  311. /// the vector type specified by the NeonTypeFlags. This is used to check
  312. /// the pointer arguments for Neon load/store intrinsics.
  313. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
  314. switch (Flags.getEltType()) {
  315. case NeonTypeFlags::Int8:
  316. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  317. case NeonTypeFlags::Int16:
  318. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  319. case NeonTypeFlags::Int32:
  320. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  321. case NeonTypeFlags::Int64:
  322. return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
  323. case NeonTypeFlags::Poly8:
  324. return Context.SignedCharTy;
  325. case NeonTypeFlags::Poly16:
  326. return Context.ShortTy;
  327. case NeonTypeFlags::Float16:
  328. return Context.UnsignedShortTy;
  329. case NeonTypeFlags::Float32:
  330. return Context.FloatTy;
  331. }
  332. llvm_unreachable("Invalid NeonTypeFlag!");
  333. }
  334. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  335. llvm::APSInt Result;
  336. uint64_t mask = 0;
  337. unsigned TV = 0;
  338. int PtrArgNum = -1;
  339. bool HasConstPtr = false;
  340. switch (BuiltinID) {
  341. #define GET_NEON_OVERLOAD_CHECK
  342. #include "clang/Basic/arm_neon.inc"
  343. #undef GET_NEON_OVERLOAD_CHECK
  344. }
  345. // For NEON intrinsics which are overloaded on vector element type, validate
  346. // the immediate which specifies which variant to emit.
  347. unsigned ImmArg = TheCall->getNumArgs()-1;
  348. if (mask) {
  349. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  350. return true;
  351. TV = Result.getLimitedValue(64);
  352. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  353. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  354. << TheCall->getArg(ImmArg)->getSourceRange();
  355. }
  356. if (PtrArgNum >= 0) {
  357. // Check that pointer arguments have the specified type.
  358. Expr *Arg = TheCall->getArg(PtrArgNum);
  359. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  360. Arg = ICE->getSubExpr();
  361. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  362. QualType RHSTy = RHS.get()->getType();
  363. QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
  364. if (HasConstPtr)
  365. EltTy = EltTy.withConst();
  366. QualType LHSTy = Context.getPointerType(EltTy);
  367. AssignConvertType ConvTy;
  368. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  369. if (RHS.isInvalid())
  370. return true;
  371. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  372. RHS.get(), AA_Assigning))
  373. return true;
  374. }
  375. // For NEON intrinsics which take an immediate value as part of the
  376. // instruction, range check them here.
  377. unsigned i = 0, l = 0, u = 0;
  378. switch (BuiltinID) {
  379. default: return false;
  380. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  381. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  382. case ARM::BI__builtin_arm_vcvtr_f:
  383. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  384. #define GET_NEON_IMMEDIATE_CHECK
  385. #include "clang/Basic/arm_neon.inc"
  386. #undef GET_NEON_IMMEDIATE_CHECK
  387. };
  388. // We can't check the value of a dependent argument.
  389. if (TheCall->getArg(i)->isTypeDependent() ||
  390. TheCall->getArg(i)->isValueDependent())
  391. return false;
  392. // Check that the immediate argument is actually a constant.
  393. if (SemaBuiltinConstantArg(TheCall, i, Result))
  394. return true;
  395. // Range check against the upper/lower values for this isntruction.
  396. unsigned Val = Result.getZExtValue();
  397. if (Val < l || Val > (u + l))
  398. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  399. << l << u+l << TheCall->getArg(i)->getSourceRange();
  400. // FIXME: VFP Intrinsics should error if VFP not present.
  401. return false;
  402. }
  403. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  404. unsigned i = 0, l = 0, u = 0;
  405. switch (BuiltinID) {
  406. default: return false;
  407. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  408. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  409. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  410. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  411. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  412. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  413. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  414. };
  415. // We can't check the value of a dependent argument.
  416. if (TheCall->getArg(i)->isTypeDependent() ||
  417. TheCall->getArg(i)->isValueDependent())
  418. return false;
  419. // Check that the immediate argument is actually a constant.
  420. llvm::APSInt Result;
  421. if (SemaBuiltinConstantArg(TheCall, i, Result))
  422. return true;
  423. // Range check against the upper/lower values for this instruction.
  424. unsigned Val = Result.getZExtValue();
  425. if (Val < l || Val > u)
  426. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  427. << l << u << TheCall->getArg(i)->getSourceRange();
  428. return false;
  429. }
  430. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  431. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  432. /// Returns true when the format fits the function and the FormatStringInfo has
  433. /// been populated.
  434. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  435. FormatStringInfo *FSI) {
  436. FSI->HasVAListArg = Format->getFirstArg() == 0;
  437. FSI->FormatIdx = Format->getFormatIdx() - 1;
  438. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  439. // The way the format attribute works in GCC, the implicit this argument
  440. // of member functions is counted. However, it doesn't appear in our own
  441. // lists, so decrement format_idx in that case.
  442. if (IsCXXMember) {
  443. if(FSI->FormatIdx == 0)
  444. return false;
  445. --FSI->FormatIdx;
  446. if (FSI->FirstDataArg != 0)
  447. --FSI->FirstDataArg;
  448. }
  449. return true;
  450. }
  451. /// Handles the checks for format strings, non-POD arguments to vararg
  452. /// functions, and NULL arguments passed to non-NULL parameters.
  453. void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
  454. unsigned NumArgs,
  455. unsigned NumProtoArgs,
  456. bool IsMemberFunction,
  457. SourceLocation Loc,
  458. SourceRange Range,
  459. VariadicCallType CallType) {
  460. // FIXME: This mechanism should be abstracted to be less fragile and
  461. // more efficient. For example, just map function ids to custom
  462. // handlers.
  463. // Printf and scanf checking.
  464. bool HandledFormatString = false;
  465. for (specific_attr_iterator<FormatAttr>
  466. I = FDecl->specific_attr_begin<FormatAttr>(),
  467. E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
  468. if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
  469. Loc, Range))
  470. HandledFormatString = true;
  471. // Refuse POD arguments that weren't caught by the format string
  472. // checks above.
  473. if (!HandledFormatString && CallType != VariadicDoesNotApply)
  474. for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
  475. variadicArgumentPODCheck(Args[ArgIdx], CallType);
  476. for (specific_attr_iterator<NonNullAttr>
  477. I = FDecl->specific_attr_begin<NonNullAttr>(),
  478. E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
  479. CheckNonNullArguments(*I, Args, Loc);
  480. // Type safety checking.
  481. for (specific_attr_iterator<ArgumentWithTypeTagAttr>
  482. i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
  483. e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
  484. CheckArgumentWithTypeTag(*i, Args);
  485. }
  486. }
  487. /// CheckConstructorCall - Check a constructor call for correctness and safety
  488. /// properties not enforced by the C type system.
  489. void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
  490. unsigned NumArgs,
  491. const FunctionProtoType *Proto,
  492. SourceLocation Loc) {
  493. VariadicCallType CallType =
  494. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  495. checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
  496. /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
  497. }
  498. /// CheckFunctionCall - Check a direct function call for various correctness
  499. /// and safety properties not strictly enforced by the C type system.
  500. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  501. const FunctionProtoType *Proto) {
  502. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
  503. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  504. TheCall->getCallee());
  505. unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
  506. checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
  507. IsMemberFunction, TheCall->getRParenLoc(),
  508. TheCall->getCallee()->getSourceRange(), CallType);
  509. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  510. // None of the checks below are needed for functions that don't have
  511. // simple names (e.g., C++ conversion functions).
  512. if (!FnInfo)
  513. return false;
  514. unsigned CMId = FDecl->getMemoryFunctionKind();
  515. if (CMId == 0)
  516. return false;
  517. // Handle memory setting and copying functions.
  518. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  519. CheckStrlcpycatArguments(TheCall, FnInfo);
  520. else if (CMId == Builtin::BIstrncat)
  521. CheckStrncatArguments(TheCall, FnInfo);
  522. else
  523. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  524. return false;
  525. }
  526. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  527. Expr **Args, unsigned NumArgs) {
  528. VariadicCallType CallType =
  529. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  530. checkCall(Method, Args, NumArgs, Method->param_size(),
  531. /*IsMemberFunction=*/false,
  532. lbrac, Method->getSourceRange(), CallType);
  533. return false;
  534. }
  535. bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
  536. const FunctionProtoType *Proto) {
  537. const VarDecl *V = dyn_cast<VarDecl>(NDecl);
  538. if (!V)
  539. return false;
  540. QualType Ty = V->getType();
  541. if (!Ty->isBlockPointerType())
  542. return false;
  543. VariadicCallType CallType =
  544. Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
  545. unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
  546. checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
  547. NumProtoArgs, /*IsMemberFunction=*/false,
  548. TheCall->getRParenLoc(),
  549. TheCall->getCallee()->getSourceRange(), CallType);
  550. return false;
  551. }
  552. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  553. AtomicExpr::AtomicOp Op) {
  554. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  555. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  556. // All these operations take one of the following forms:
  557. enum {
  558. // C __c11_atomic_init(A *, C)
  559. Init,
  560. // C __c11_atomic_load(A *, int)
  561. Load,
  562. // void __atomic_load(A *, CP, int)
  563. Copy,
  564. // C __c11_atomic_add(A *, M, int)
  565. Arithmetic,
  566. // C __atomic_exchange_n(A *, CP, int)
  567. Xchg,
  568. // void __atomic_exchange(A *, C *, CP, int)
  569. GNUXchg,
  570. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  571. C11CmpXchg,
  572. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  573. GNUCmpXchg
  574. } Form = Init;
  575. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
  576. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
  577. // where:
  578. // C is an appropriate type,
  579. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  580. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  581. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  582. // the int parameters are for orderings.
  583. assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  584. AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
  585. && "need to update code for modified C11 atomics");
  586. bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
  587. Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
  588. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  589. Op == AtomicExpr::AO__atomic_store_n ||
  590. Op == AtomicExpr::AO__atomic_exchange_n ||
  591. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  592. bool IsAddSub = false;
  593. switch (Op) {
  594. case AtomicExpr::AO__c11_atomic_init:
  595. Form = Init;
  596. break;
  597. case AtomicExpr::AO__c11_atomic_load:
  598. case AtomicExpr::AO__atomic_load_n:
  599. Form = Load;
  600. break;
  601. case AtomicExpr::AO__c11_atomic_store:
  602. case AtomicExpr::AO__atomic_load:
  603. case AtomicExpr::AO__atomic_store:
  604. case AtomicExpr::AO__atomic_store_n:
  605. Form = Copy;
  606. break;
  607. case AtomicExpr::AO__c11_atomic_fetch_add:
  608. case AtomicExpr::AO__c11_atomic_fetch_sub:
  609. case AtomicExpr::AO__atomic_fetch_add:
  610. case AtomicExpr::AO__atomic_fetch_sub:
  611. case AtomicExpr::AO__atomic_add_fetch:
  612. case AtomicExpr::AO__atomic_sub_fetch:
  613. IsAddSub = true;
  614. // Fall through.
  615. case AtomicExpr::AO__c11_atomic_fetch_and:
  616. case AtomicExpr::AO__c11_atomic_fetch_or:
  617. case AtomicExpr::AO__c11_atomic_fetch_xor:
  618. case AtomicExpr::AO__atomic_fetch_and:
  619. case AtomicExpr::AO__atomic_fetch_or:
  620. case AtomicExpr::AO__atomic_fetch_xor:
  621. case AtomicExpr::AO__atomic_fetch_nand:
  622. case AtomicExpr::AO__atomic_and_fetch:
  623. case AtomicExpr::AO__atomic_or_fetch:
  624. case AtomicExpr::AO__atomic_xor_fetch:
  625. case AtomicExpr::AO__atomic_nand_fetch:
  626. Form = Arithmetic;
  627. break;
  628. case AtomicExpr::AO__c11_atomic_exchange:
  629. case AtomicExpr::AO__atomic_exchange_n:
  630. Form = Xchg;
  631. break;
  632. case AtomicExpr::AO__atomic_exchange:
  633. Form = GNUXchg;
  634. break;
  635. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  636. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  637. Form = C11CmpXchg;
  638. break;
  639. case AtomicExpr::AO__atomic_compare_exchange:
  640. case AtomicExpr::AO__atomic_compare_exchange_n:
  641. Form = GNUCmpXchg;
  642. break;
  643. }
  644. // Check we have the right number of arguments.
  645. if (TheCall->getNumArgs() < NumArgs[Form]) {
  646. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  647. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  648. << TheCall->getCallee()->getSourceRange();
  649. return ExprError();
  650. } else if (TheCall->getNumArgs() > NumArgs[Form]) {
  651. Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
  652. diag::err_typecheck_call_too_many_args)
  653. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  654. << TheCall->getCallee()->getSourceRange();
  655. return ExprError();
  656. }
  657. // Inspect the first argument of the atomic operation.
  658. Expr *Ptr = TheCall->getArg(0);
  659. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  660. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  661. if (!pointerType) {
  662. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  663. << Ptr->getType() << Ptr->getSourceRange();
  664. return ExprError();
  665. }
  666. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  667. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  668. QualType ValType = AtomTy; // 'C'
  669. if (IsC11) {
  670. if (!AtomTy->isAtomicType()) {
  671. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  672. << Ptr->getType() << Ptr->getSourceRange();
  673. return ExprError();
  674. }
  675. if (AtomTy.isConstQualified()) {
  676. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  677. << Ptr->getType() << Ptr->getSourceRange();
  678. return ExprError();
  679. }
  680. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  681. }
  682. // For an arithmetic operation, the implied arithmetic must be well-formed.
  683. if (Form == Arithmetic) {
  684. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  685. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  686. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  687. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  688. return ExprError();
  689. }
  690. if (!IsAddSub && !ValType->isIntegerType()) {
  691. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  692. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  693. return ExprError();
  694. }
  695. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  696. // For __atomic_*_n operations, the value type must be a scalar integral or
  697. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  698. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  699. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  700. return ExprError();
  701. }
  702. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
  703. // For GNU atomics, require a trivially-copyable type. This is not part of
  704. // the GNU atomics specification, but we enforce it for sanity.
  705. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  706. << Ptr->getType() << Ptr->getSourceRange();
  707. return ExprError();
  708. }
  709. // FIXME: For any builtin other than a load, the ValType must not be
  710. // const-qualified.
  711. switch (ValType.getObjCLifetime()) {
  712. case Qualifiers::OCL_None:
  713. case Qualifiers::OCL_ExplicitNone:
  714. // okay
  715. break;
  716. case Qualifiers::OCL_Weak:
  717. case Qualifiers::OCL_Strong:
  718. case Qualifiers::OCL_Autoreleasing:
  719. // FIXME: Can this happen? By this point, ValType should be known
  720. // to be trivially copyable.
  721. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  722. << ValType << Ptr->getSourceRange();
  723. return ExprError();
  724. }
  725. QualType ResultType = ValType;
  726. if (Form == Copy || Form == GNUXchg || Form == Init)
  727. ResultType = Context.VoidTy;
  728. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  729. ResultType = Context.BoolTy;
  730. // The type of a parameter passed 'by value'. In the GNU atomics, such
  731. // arguments are actually passed as pointers.
  732. QualType ByValType = ValType; // 'CP'
  733. if (!IsC11 && !IsN)
  734. ByValType = Ptr->getType();
  735. // The first argument --- the pointer --- has a fixed type; we
  736. // deduce the types of the rest of the arguments accordingly. Walk
  737. // the remaining arguments, converting them to the deduced value type.
  738. for (unsigned i = 1; i != NumArgs[Form]; ++i) {
  739. QualType Ty;
  740. if (i < NumVals[Form] + 1) {
  741. switch (i) {
  742. case 1:
  743. // The second argument is the non-atomic operand. For arithmetic, this
  744. // is always passed by value, and for a compare_exchange it is always
  745. // passed by address. For the rest, GNU uses by-address and C11 uses
  746. // by-value.
  747. assert(Form != Load);
  748. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  749. Ty = ValType;
  750. else if (Form == Copy || Form == Xchg)
  751. Ty = ByValType;
  752. else if (Form == Arithmetic)
  753. Ty = Context.getPointerDiffType();
  754. else
  755. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  756. break;
  757. case 2:
  758. // The third argument to compare_exchange / GNU exchange is a
  759. // (pointer to a) desired value.
  760. Ty = ByValType;
  761. break;
  762. case 3:
  763. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  764. Ty = Context.BoolTy;
  765. break;
  766. }
  767. } else {
  768. // The order(s) are always converted to int.
  769. Ty = Context.IntTy;
  770. }
  771. InitializedEntity Entity =
  772. InitializedEntity::InitializeParameter(Context, Ty, false);
  773. ExprResult Arg = TheCall->getArg(i);
  774. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  775. if (Arg.isInvalid())
  776. return true;
  777. TheCall->setArg(i, Arg.get());
  778. }
  779. // Permute the arguments into a 'consistent' order.
  780. SmallVector<Expr*, 5> SubExprs;
  781. SubExprs.push_back(Ptr);
  782. switch (Form) {
  783. case Init:
  784. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  785. SubExprs.push_back(TheCall->getArg(1)); // Val1
  786. break;
  787. case Load:
  788. SubExprs.push_back(TheCall->getArg(1)); // Order
  789. break;
  790. case Copy:
  791. case Arithmetic:
  792. case Xchg:
  793. SubExprs.push_back(TheCall->getArg(2)); // Order
  794. SubExprs.push_back(TheCall->getArg(1)); // Val1
  795. break;
  796. case GNUXchg:
  797. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  798. SubExprs.push_back(TheCall->getArg(3)); // Order
  799. SubExprs.push_back(TheCall->getArg(1)); // Val1
  800. SubExprs.push_back(TheCall->getArg(2)); // Val2
  801. break;
  802. case C11CmpXchg:
  803. SubExprs.push_back(TheCall->getArg(3)); // Order
  804. SubExprs.push_back(TheCall->getArg(1)); // Val1
  805. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  806. SubExprs.push_back(TheCall->getArg(2)); // Val2
  807. break;
  808. case GNUCmpXchg:
  809. SubExprs.push_back(TheCall->getArg(4)); // Order
  810. SubExprs.push_back(TheCall->getArg(1)); // Val1
  811. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  812. SubExprs.push_back(TheCall->getArg(2)); // Val2
  813. SubExprs.push_back(TheCall->getArg(3)); // Weak
  814. break;
  815. }
  816. return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  817. SubExprs, ResultType, Op,
  818. TheCall->getRParenLoc()));
  819. }
  820. /// checkBuiltinArgument - Given a call to a builtin function, perform
  821. /// normal type-checking on the given argument, updating the call in
  822. /// place. This is useful when a builtin function requires custom
  823. /// type-checking for some of its arguments but not necessarily all of
  824. /// them.
  825. ///
  826. /// Returns true on error.
  827. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  828. FunctionDecl *Fn = E->getDirectCallee();
  829. assert(Fn && "builtin call without direct callee!");
  830. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  831. InitializedEntity Entity =
  832. InitializedEntity::InitializeParameter(S.Context, Param);
  833. ExprResult Arg = E->getArg(0);
  834. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  835. if (Arg.isInvalid())
  836. return true;
  837. E->setArg(ArgIndex, Arg.take());
  838. return false;
  839. }
  840. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  841. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  842. /// type of its first argument. The main ActOnCallExpr routines have already
  843. /// promoted the types of arguments because all of these calls are prototyped as
  844. /// void(...).
  845. ///
  846. /// This function goes through and does final semantic checking for these
  847. /// builtins,
  848. ExprResult
  849. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  850. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  851. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  852. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  853. // Ensure that we have at least one argument to do type inference from.
  854. if (TheCall->getNumArgs() < 1) {
  855. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  856. << 0 << 1 << TheCall->getNumArgs()
  857. << TheCall->getCallee()->getSourceRange();
  858. return ExprError();
  859. }
  860. // Inspect the first argument of the atomic builtin. This should always be
  861. // a pointer type, whose element is an integral scalar or pointer type.
  862. // Because it is a pointer type, we don't have to worry about any implicit
  863. // casts here.
  864. // FIXME: We don't allow floating point scalars as input.
  865. Expr *FirstArg = TheCall->getArg(0);
  866. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  867. if (FirstArgResult.isInvalid())
  868. return ExprError();
  869. FirstArg = FirstArgResult.take();
  870. TheCall->setArg(0, FirstArg);
  871. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  872. if (!pointerType) {
  873. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  874. << FirstArg->getType() << FirstArg->getSourceRange();
  875. return ExprError();
  876. }
  877. QualType ValType = pointerType->getPointeeType();
  878. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  879. !ValType->isBlockPointerType()) {
  880. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  881. << FirstArg->getType() << FirstArg->getSourceRange();
  882. return ExprError();
  883. }
  884. switch (ValType.getObjCLifetime()) {
  885. case Qualifiers::OCL_None:
  886. case Qualifiers::OCL_ExplicitNone:
  887. // okay
  888. break;
  889. case Qualifiers::OCL_Weak:
  890. case Qualifiers::OCL_Strong:
  891. case Qualifiers::OCL_Autoreleasing:
  892. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  893. << ValType << FirstArg->getSourceRange();
  894. return ExprError();
  895. }
  896. // Strip any qualifiers off ValType.
  897. ValType = ValType.getUnqualifiedType();
  898. // The majority of builtins return a value, but a few have special return
  899. // types, so allow them to override appropriately below.
  900. QualType ResultType = ValType;
  901. // We need to figure out which concrete builtin this maps onto. For example,
  902. // __sync_fetch_and_add with a 2 byte object turns into
  903. // __sync_fetch_and_add_2.
  904. #define BUILTIN_ROW(x) \
  905. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  906. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  907. static const unsigned BuiltinIndices[][5] = {
  908. BUILTIN_ROW(__sync_fetch_and_add),
  909. BUILTIN_ROW(__sync_fetch_and_sub),
  910. BUILTIN_ROW(__sync_fetch_and_or),
  911. BUILTIN_ROW(__sync_fetch_and_and),
  912. BUILTIN_ROW(__sync_fetch_and_xor),
  913. BUILTIN_ROW(__sync_add_and_fetch),
  914. BUILTIN_ROW(__sync_sub_and_fetch),
  915. BUILTIN_ROW(__sync_and_and_fetch),
  916. BUILTIN_ROW(__sync_or_and_fetch),
  917. BUILTIN_ROW(__sync_xor_and_fetch),
  918. BUILTIN_ROW(__sync_val_compare_and_swap),
  919. BUILTIN_ROW(__sync_bool_compare_and_swap),
  920. BUILTIN_ROW(__sync_lock_test_and_set),
  921. BUILTIN_ROW(__sync_lock_release),
  922. BUILTIN_ROW(__sync_swap)
  923. };
  924. #undef BUILTIN_ROW
  925. // Determine the index of the size.
  926. unsigned SizeIndex;
  927. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  928. case 1: SizeIndex = 0; break;
  929. case 2: SizeIndex = 1; break;
  930. case 4: SizeIndex = 2; break;
  931. case 8: SizeIndex = 3; break;
  932. case 16: SizeIndex = 4; break;
  933. default:
  934. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  935. << FirstArg->getType() << FirstArg->getSourceRange();
  936. return ExprError();
  937. }
  938. // Each of these builtins has one pointer argument, followed by some number of
  939. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  940. // that we ignore. Find out which row of BuiltinIndices to read from as well
  941. // as the number of fixed args.
  942. unsigned BuiltinID = FDecl->getBuiltinID();
  943. unsigned BuiltinIndex, NumFixed = 1;
  944. switch (BuiltinID) {
  945. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  946. case Builtin::BI__sync_fetch_and_add:
  947. case Builtin::BI__sync_fetch_and_add_1:
  948. case Builtin::BI__sync_fetch_and_add_2:
  949. case Builtin::BI__sync_fetch_and_add_4:
  950. case Builtin::BI__sync_fetch_and_add_8:
  951. case Builtin::BI__sync_fetch_and_add_16:
  952. BuiltinIndex = 0;
  953. break;
  954. case Builtin::BI__sync_fetch_and_sub:
  955. case Builtin::BI__sync_fetch_and_sub_1:
  956. case Builtin::BI__sync_fetch_and_sub_2:
  957. case Builtin::BI__sync_fetch_and_sub_4:
  958. case Builtin::BI__sync_fetch_and_sub_8:
  959. case Builtin::BI__sync_fetch_and_sub_16:
  960. BuiltinIndex = 1;
  961. break;
  962. case Builtin::BI__sync_fetch_and_or:
  963. case Builtin::BI__sync_fetch_and_or_1:
  964. case Builtin::BI__sync_fetch_and_or_2:
  965. case Builtin::BI__sync_fetch_and_or_4:
  966. case Builtin::BI__sync_fetch_and_or_8:
  967. case Builtin::BI__sync_fetch_and_or_16:
  968. BuiltinIndex = 2;
  969. break;
  970. case Builtin::BI__sync_fetch_and_and:
  971. case Builtin::BI__sync_fetch_and_and_1:
  972. case Builtin::BI__sync_fetch_and_and_2:
  973. case Builtin::BI__sync_fetch_and_and_4:
  974. case Builtin::BI__sync_fetch_and_and_8:
  975. case Builtin::BI__sync_fetch_and_and_16:
  976. BuiltinIndex = 3;
  977. break;
  978. case Builtin::BI__sync_fetch_and_xor:
  979. case Builtin::BI__sync_fetch_and_xor_1:
  980. case Builtin::BI__sync_fetch_and_xor_2:
  981. case Builtin::BI__sync_fetch_and_xor_4:
  982. case Builtin::BI__sync_fetch_and_xor_8:
  983. case Builtin::BI__sync_fetch_and_xor_16:
  984. BuiltinIndex = 4;
  985. break;
  986. case Builtin::BI__sync_add_and_fetch:
  987. case Builtin::BI__sync_add_and_fetch_1:
  988. case Builtin::BI__sync_add_and_fetch_2:
  989. case Builtin::BI__sync_add_and_fetch_4:
  990. case Builtin::BI__sync_add_and_fetch_8:
  991. case Builtin::BI__sync_add_and_fetch_16:
  992. BuiltinIndex = 5;
  993. break;
  994. case Builtin::BI__sync_sub_and_fetch:
  995. case Builtin::BI__sync_sub_and_fetch_1:
  996. case Builtin::BI__sync_sub_and_fetch_2:
  997. case Builtin::BI__sync_sub_and_fetch_4:
  998. case Builtin::BI__sync_sub_and_fetch_8:
  999. case Builtin::BI__sync_sub_and_fetch_16:
  1000. BuiltinIndex = 6;
  1001. break;
  1002. case Builtin::BI__sync_and_and_fetch:
  1003. case Builtin::BI__sync_and_and_fetch_1:
  1004. case Builtin::BI__sync_and_and_fetch_2:
  1005. case Builtin::BI__sync_and_and_fetch_4:
  1006. case Builtin::BI__sync_and_and_fetch_8:
  1007. case Builtin::BI__sync_and_and_fetch_16:
  1008. BuiltinIndex = 7;
  1009. break;
  1010. case Builtin::BI__sync_or_and_fetch:
  1011. case Builtin::BI__sync_or_and_fetch_1:
  1012. case Builtin::BI__sync_or_and_fetch_2:
  1013. case Builtin::BI__sync_or_and_fetch_4:
  1014. case Builtin::BI__sync_or_and_fetch_8:
  1015. case Builtin::BI__sync_or_and_fetch_16:
  1016. BuiltinIndex = 8;
  1017. break;
  1018. case Builtin::BI__sync_xor_and_fetch:
  1019. case Builtin::BI__sync_xor_and_fetch_1:
  1020. case Builtin::BI__sync_xor_and_fetch_2:
  1021. case Builtin::BI__sync_xor_and_fetch_4:
  1022. case Builtin::BI__sync_xor_and_fetch_8:
  1023. case Builtin::BI__sync_xor_and_fetch_16:
  1024. BuiltinIndex = 9;
  1025. break;
  1026. case Builtin::BI__sync_val_compare_and_swap:
  1027. case Builtin::BI__sync_val_compare_and_swap_1:
  1028. case Builtin::BI__sync_val_compare_and_swap_2:
  1029. case Builtin::BI__sync_val_compare_and_swap_4:
  1030. case Builtin::BI__sync_val_compare_and_swap_8:
  1031. case Builtin::BI__sync_val_compare_and_swap_16:
  1032. BuiltinIndex = 10;
  1033. NumFixed = 2;
  1034. break;
  1035. case Builtin::BI__sync_bool_compare_and_swap:
  1036. case Builtin::BI__sync_bool_compare_and_swap_1:
  1037. case Builtin::BI__sync_bool_compare_and_swap_2:
  1038. case Builtin::BI__sync_bool_compare_and_swap_4:
  1039. case Builtin::BI__sync_bool_compare_and_swap_8:
  1040. case Builtin::BI__sync_bool_compare_and_swap_16:
  1041. BuiltinIndex = 11;
  1042. NumFixed = 2;
  1043. ResultType = Context.BoolTy;
  1044. break;
  1045. case Builtin::BI__sync_lock_test_and_set:
  1046. case Builtin::BI__sync_lock_test_and_set_1:
  1047. case Builtin::BI__sync_lock_test_and_set_2:
  1048. case Builtin::BI__sync_lock_test_and_set_4:
  1049. case Builtin::BI__sync_lock_test_and_set_8:
  1050. case Builtin::BI__sync_lock_test_and_set_16:
  1051. BuiltinIndex = 12;
  1052. break;
  1053. case Builtin::BI__sync_lock_release:
  1054. case Builtin::BI__sync_lock_release_1:
  1055. case Builtin::BI__sync_lock_release_2:
  1056. case Builtin::BI__sync_lock_release_4:
  1057. case Builtin::BI__sync_lock_release_8:
  1058. case Builtin::BI__sync_lock_release_16:
  1059. BuiltinIndex = 13;
  1060. NumFixed = 0;
  1061. ResultType = Context.VoidTy;
  1062. break;
  1063. case Builtin::BI__sync_swap:
  1064. case Builtin::BI__sync_swap_1:
  1065. case Builtin::BI__sync_swap_2:
  1066. case Builtin::BI__sync_swap_4:
  1067. case Builtin::BI__sync_swap_8:
  1068. case Builtin::BI__sync_swap_16:
  1069. BuiltinIndex = 14;
  1070. break;
  1071. }
  1072. // Now that we know how many fixed arguments we expect, first check that we
  1073. // have at least that many.
  1074. if (TheCall->getNumArgs() < 1+NumFixed) {
  1075. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1076. << 0 << 1+NumFixed << TheCall->getNumArgs()
  1077. << TheCall->getCallee()->getSourceRange();
  1078. return ExprError();
  1079. }
  1080. // Get the decl for the concrete builtin from this, we can tell what the
  1081. // concrete integer type we should convert to is.
  1082. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  1083. const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
  1084. IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
  1085. FunctionDecl *NewBuiltinDecl =
  1086. cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
  1087. TUScope, false, DRE->getLocStart()));
  1088. // The first argument --- the pointer --- has a fixed type; we
  1089. // deduce the types of the rest of the arguments accordingly. Walk
  1090. // the remaining arguments, converting them to the deduced value type.
  1091. for (unsigned i = 0; i != NumFixed; ++i) {
  1092. ExprResult Arg = TheCall->getArg(i+1);
  1093. // GCC does an implicit conversion to the pointer or integer ValType. This
  1094. // can fail in some cases (1i -> int**), check for this error case now.
  1095. // Initialize the argument.
  1096. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  1097. ValType, /*consume*/ false);
  1098. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1099. if (Arg.isInvalid())
  1100. return ExprError();
  1101. // Okay, we have something that *can* be converted to the right type. Check
  1102. // to see if there is a potentially weird extension going on here. This can
  1103. // happen when you do an atomic operation on something like an char* and
  1104. // pass in 42. The 42 gets converted to char. This is even more strange
  1105. // for things like 45.123 -> char, etc.
  1106. // FIXME: Do this check.
  1107. TheCall->setArg(i+1, Arg.take());
  1108. }
  1109. ASTContext& Context = this->getASTContext();
  1110. // Create a new DeclRefExpr to refer to the new decl.
  1111. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  1112. Context,
  1113. DRE->getQualifierLoc(),
  1114. SourceLocation(),
  1115. NewBuiltinDecl,
  1116. /*enclosing*/ false,
  1117. DRE->getLocation(),
  1118. Context.BuiltinFnTy,
  1119. DRE->getValueKind());
  1120. // Set the callee in the CallExpr.
  1121. // FIXME: This loses syntactic information.
  1122. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  1123. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  1124. CK_BuiltinFnToFnPtr);
  1125. TheCall->setCallee(PromotedCall.take());
  1126. // Change the result type of the call to match the original value type. This
  1127. // is arbitrary, but the codegen for these builtins ins design to handle it
  1128. // gracefully.
  1129. TheCall->setType(ResultType);
  1130. return TheCallResult;
  1131. }
  1132. /// CheckObjCString - Checks that the argument to the builtin
  1133. /// CFString constructor is correct
  1134. /// Note: It might also make sense to do the UTF-16 conversion here (would
  1135. /// simplify the backend).
  1136. bool Sema::CheckObjCString(Expr *Arg) {
  1137. Arg = Arg->IgnoreParenCasts();
  1138. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  1139. if (!Literal || !Literal->isAscii()) {
  1140. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  1141. << Arg->getSourceRange();
  1142. return true;
  1143. }
  1144. if (Literal->containsNonAsciiOrNull()) {
  1145. StringRef String = Literal->getString();
  1146. unsigned NumBytes = String.size();
  1147. SmallVector<UTF16, 128> ToBuf(NumBytes);
  1148. const UTF8 *FromPtr = (const UTF8 *)String.data();
  1149. UTF16 *ToPtr = &ToBuf[0];
  1150. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1151. &ToPtr, ToPtr + NumBytes,
  1152. strictConversion);
  1153. // Check for conversion failure.
  1154. if (Result != conversionOK)
  1155. Diag(Arg->getLocStart(),
  1156. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  1157. }
  1158. return false;
  1159. }
  1160. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  1161. /// Emit an error and return true on failure, return false on success.
  1162. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  1163. Expr *Fn = TheCall->getCallee();
  1164. if (TheCall->getNumArgs() > 2) {
  1165. Diag(TheCall->getArg(2)->getLocStart(),
  1166. diag::err_typecheck_call_too_many_args)
  1167. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1168. << Fn->getSourceRange()
  1169. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1170. (*(TheCall->arg_end()-1))->getLocEnd());
  1171. return true;
  1172. }
  1173. if (TheCall->getNumArgs() < 2) {
  1174. return Diag(TheCall->getLocEnd(),
  1175. diag::err_typecheck_call_too_few_args_at_least)
  1176. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  1177. }
  1178. // Type-check the first argument normally.
  1179. if (checkBuiltinArgument(*this, TheCall, 0))
  1180. return true;
  1181. // Determine whether the current function is variadic or not.
  1182. BlockScopeInfo *CurBlock = getCurBlock();
  1183. bool isVariadic;
  1184. if (CurBlock)
  1185. isVariadic = CurBlock->TheDecl->isVariadic();
  1186. else if (FunctionDecl *FD = getCurFunctionDecl())
  1187. isVariadic = FD->isVariadic();
  1188. else
  1189. isVariadic = getCurMethodDecl()->isVariadic();
  1190. if (!isVariadic) {
  1191. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  1192. return true;
  1193. }
  1194. // Verify that the second argument to the builtin is the last argument of the
  1195. // current function or method.
  1196. bool SecondArgIsLastNamedArgument = false;
  1197. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  1198. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  1199. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  1200. // FIXME: This isn't correct for methods (results in bogus warning).
  1201. // Get the last formal in the current function.
  1202. const ParmVarDecl *LastArg;
  1203. if (CurBlock)
  1204. LastArg = *(CurBlock->TheDecl->param_end()-1);
  1205. else if (FunctionDecl *FD = getCurFunctionDecl())
  1206. LastArg = *(FD->param_end()-1);
  1207. else
  1208. LastArg = *(getCurMethodDecl()->param_end()-1);
  1209. SecondArgIsLastNamedArgument = PV == LastArg;
  1210. }
  1211. }
  1212. if (!SecondArgIsLastNamedArgument)
  1213. Diag(TheCall->getArg(1)->getLocStart(),
  1214. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  1215. return false;
  1216. }
  1217. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  1218. /// friends. This is declared to take (...), so we have to check everything.
  1219. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  1220. if (TheCall->getNumArgs() < 2)
  1221. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1222. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  1223. if (TheCall->getNumArgs() > 2)
  1224. return Diag(TheCall->getArg(2)->getLocStart(),
  1225. diag::err_typecheck_call_too_many_args)
  1226. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1227. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1228. (*(TheCall->arg_end()-1))->getLocEnd());
  1229. ExprResult OrigArg0 = TheCall->getArg(0);
  1230. ExprResult OrigArg1 = TheCall->getArg(1);
  1231. // Do standard promotions between the two arguments, returning their common
  1232. // type.
  1233. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  1234. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  1235. return true;
  1236. // Make sure any conversions are pushed back into the call; this is
  1237. // type safe since unordered compare builtins are declared as "_Bool
  1238. // foo(...)".
  1239. TheCall->setArg(0, OrigArg0.get());
  1240. TheCall->setArg(1, OrigArg1.get());
  1241. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  1242. return false;
  1243. // If the common type isn't a real floating type, then the arguments were
  1244. // invalid for this operation.
  1245. if (Res.isNull() || !Res->isRealFloatingType())
  1246. return Diag(OrigArg0.get()->getLocStart(),
  1247. diag::err_typecheck_call_invalid_ordered_compare)
  1248. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  1249. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  1250. return false;
  1251. }
  1252. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  1253. /// __builtin_isnan and friends. This is declared to take (...), so we have
  1254. /// to check everything. We expect the last argument to be a floating point
  1255. /// value.
  1256. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  1257. if (TheCall->getNumArgs() < NumArgs)
  1258. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1259. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  1260. if (TheCall->getNumArgs() > NumArgs)
  1261. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  1262. diag::err_typecheck_call_too_many_args)
  1263. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  1264. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  1265. (*(TheCall->arg_end()-1))->getLocEnd());
  1266. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  1267. if (OrigArg->isTypeDependent())
  1268. return false;
  1269. // This operation requires a non-_Complex floating-point number.
  1270. if (!OrigArg->getType()->isRealFloatingType())
  1271. return Diag(OrigArg->getLocStart(),
  1272. diag::err_typecheck_call_invalid_unary_fp)
  1273. << OrigArg->getType() << OrigArg->getSourceRange();
  1274. // If this is an implicit conversion from float -> double, remove it.
  1275. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  1276. Expr *CastArg = Cast->getSubExpr();
  1277. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  1278. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  1279. "promotion from float to double is the only expected cast here");
  1280. Cast->setSubExpr(0);
  1281. TheCall->setArg(NumArgs-1, CastArg);
  1282. }
  1283. }
  1284. return false;
  1285. }
  1286. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  1287. // This is declared to take (...), so we have to check everything.
  1288. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  1289. if (TheCall->getNumArgs() < 2)
  1290. return ExprError(Diag(TheCall->getLocEnd(),
  1291. diag::err_typecheck_call_too_few_args_at_least)
  1292. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1293. << TheCall->getSourceRange());
  1294. // Determine which of the following types of shufflevector we're checking:
  1295. // 1) unary, vector mask: (lhs, mask)
  1296. // 2) binary, vector mask: (lhs, rhs, mask)
  1297. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  1298. QualType resType = TheCall->getArg(0)->getType();
  1299. unsigned numElements = 0;
  1300. if (!TheCall->getArg(0)->isTypeDependent() &&
  1301. !TheCall->getArg(1)->isTypeDependent()) {
  1302. QualType LHSType = TheCall->getArg(0)->getType();
  1303. QualType RHSType = TheCall->getArg(1)->getType();
  1304. if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
  1305. Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
  1306. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1307. TheCall->getArg(1)->getLocEnd());
  1308. return ExprError();
  1309. }
  1310. numElements = LHSType->getAs<VectorType>()->getNumElements();
  1311. unsigned numResElements = TheCall->getNumArgs() - 2;
  1312. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  1313. // with mask. If so, verify that RHS is an integer vector type with the
  1314. // same number of elts as lhs.
  1315. if (TheCall->getNumArgs() == 2) {
  1316. if (!RHSType->hasIntegerRepresentation() ||
  1317. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  1318. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1319. << SourceRange(TheCall->getArg(1)->getLocStart(),
  1320. TheCall->getArg(1)->getLocEnd());
  1321. numResElements = numElements;
  1322. }
  1323. else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  1324. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1325. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1326. TheCall->getArg(1)->getLocEnd());
  1327. return ExprError();
  1328. } else if (numElements != numResElements) {
  1329. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  1330. resType = Context.getVectorType(eltType, numResElements,
  1331. VectorType::GenericVector);
  1332. }
  1333. }
  1334. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  1335. if (TheCall->getArg(i)->isTypeDependent() ||
  1336. TheCall->getArg(i)->isValueDependent())
  1337. continue;
  1338. llvm::APSInt Result(32);
  1339. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  1340. return ExprError(Diag(TheCall->getLocStart(),
  1341. diag::err_shufflevector_nonconstant_argument)
  1342. << TheCall->getArg(i)->getSourceRange());
  1343. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  1344. return ExprError(Diag(TheCall->getLocStart(),
  1345. diag::err_shufflevector_argument_too_large)
  1346. << TheCall->getArg(i)->getSourceRange());
  1347. }
  1348. SmallVector<Expr*, 32> exprs;
  1349. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  1350. exprs.push_back(TheCall->getArg(i));
  1351. TheCall->setArg(i, 0);
  1352. }
  1353. return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
  1354. TheCall->getCallee()->getLocStart(),
  1355. TheCall->getRParenLoc()));
  1356. }
  1357. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  1358. // This is declared to take (const void*, ...) and can take two
  1359. // optional constant int args.
  1360. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  1361. unsigned NumArgs = TheCall->getNumArgs();
  1362. if (NumArgs > 3)
  1363. return Diag(TheCall->getLocEnd(),
  1364. diag::err_typecheck_call_too_many_args_at_most)
  1365. << 0 /*function call*/ << 3 << NumArgs
  1366. << TheCall->getSourceRange();
  1367. // Argument 0 is checked for us and the remaining arguments must be
  1368. // constant integers.
  1369. for (unsigned i = 1; i != NumArgs; ++i) {
  1370. Expr *Arg = TheCall->getArg(i);
  1371. // We can't check the value of a dependent argument.
  1372. if (Arg->isTypeDependent() || Arg->isValueDependent())
  1373. continue;
  1374. llvm::APSInt Result;
  1375. if (SemaBuiltinConstantArg(TheCall, i, Result))
  1376. return true;
  1377. // FIXME: gcc issues a warning and rewrites these to 0. These
  1378. // seems especially odd for the third argument since the default
  1379. // is 3.
  1380. if (i == 1) {
  1381. if (Result.getLimitedValue() > 1)
  1382. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1383. << "0" << "1" << Arg->getSourceRange();
  1384. } else {
  1385. if (Result.getLimitedValue() > 3)
  1386. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1387. << "0" << "3" << Arg->getSourceRange();
  1388. }
  1389. }
  1390. return false;
  1391. }
  1392. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  1393. /// TheCall is a constant expression.
  1394. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  1395. llvm::APSInt &Result) {
  1396. Expr *Arg = TheCall->getArg(ArgNum);
  1397. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1398. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1399. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  1400. if (!Arg->isIntegerConstantExpr(Result, Context))
  1401. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  1402. << FDecl->getDeclName() << Arg->getSourceRange();
  1403. return false;
  1404. }
  1405. /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
  1406. /// int type). This simply type checks that type is one of the defined
  1407. /// constants (0-3).
  1408. // For compatibility check 0-3, llvm only handles 0 and 2.
  1409. bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
  1410. llvm::APSInt Result;
  1411. // We can't check the value of a dependent argument.
  1412. if (TheCall->getArg(1)->isTypeDependent() ||
  1413. TheCall->getArg(1)->isValueDependent())
  1414. return false;
  1415. // Check constant-ness first.
  1416. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1417. return true;
  1418. Expr *Arg = TheCall->getArg(1);
  1419. if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
  1420. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1421. << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1422. }
  1423. return false;
  1424. }
  1425. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  1426. /// This checks that val is a constant 1.
  1427. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  1428. Expr *Arg = TheCall->getArg(1);
  1429. llvm::APSInt Result;
  1430. // TODO: This is less than ideal. Overload this to take a value.
  1431. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1432. return true;
  1433. if (Result != 1)
  1434. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  1435. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1436. return false;
  1437. }
  1438. // Determine if an expression is a string literal or constant string.
  1439. // If this function returns false on the arguments to a function expecting a
  1440. // format string, we will usually need to emit a warning.
  1441. // True string literals are then checked by CheckFormatString.
  1442. Sema::StringLiteralCheckType
  1443. Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
  1444. unsigned NumArgs, bool HasVAListArg,
  1445. unsigned format_idx, unsigned firstDataArg,
  1446. FormatStringType Type, VariadicCallType CallType,
  1447. bool inFunctionCall) {
  1448. tryAgain:
  1449. if (E->isTypeDependent() || E->isValueDependent())
  1450. return SLCT_NotALiteral;
  1451. E = E->IgnoreParenCasts();
  1452. if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
  1453. // Technically -Wformat-nonliteral does not warn about this case.
  1454. // The behavior of printf and friends in this case is implementation
  1455. // dependent. Ideally if the format string cannot be null then
  1456. // it should have a 'nonnull' attribute in the function prototype.
  1457. return SLCT_CheckedLiteral;
  1458. switch (E->getStmtClass()) {
  1459. case Stmt::BinaryConditionalOperatorClass:
  1460. case Stmt::ConditionalOperatorClass: {
  1461. // The expression is a literal if both sub-expressions were, and it was
  1462. // completely checked only if both sub-expressions were checked.
  1463. const AbstractConditionalOperator *C =
  1464. cast<AbstractConditionalOperator>(E);
  1465. StringLiteralCheckType Left =
  1466. checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
  1467. HasVAListArg, format_idx, firstDataArg,
  1468. Type, CallType, inFunctionCall);
  1469. if (Left == SLCT_NotALiteral)
  1470. return SLCT_NotALiteral;
  1471. StringLiteralCheckType Right =
  1472. checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
  1473. HasVAListArg, format_idx, firstDataArg,
  1474. Type, CallType, inFunctionCall);
  1475. return Left < Right ? Left : Right;
  1476. }
  1477. case Stmt::ImplicitCastExprClass: {
  1478. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  1479. goto tryAgain;
  1480. }
  1481. case Stmt::OpaqueValueExprClass:
  1482. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  1483. E = src;
  1484. goto tryAgain;
  1485. }
  1486. return SLCT_NotALiteral;
  1487. case Stmt::PredefinedExprClass:
  1488. // While __func__, etc., are technically not string literals, they
  1489. // cannot contain format specifiers and thus are not a security
  1490. // liability.
  1491. return SLCT_UncheckedLiteral;
  1492. case Stmt::DeclRefExprClass: {
  1493. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  1494. // As an exception, do not flag errors for variables binding to
  1495. // const string literals.
  1496. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1497. bool isConstant = false;
  1498. QualType T = DR->getType();
  1499. if (const ArrayType *AT = Context.getAsArrayType(T)) {
  1500. isConstant = AT->getElementType().isConstant(Context);
  1501. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  1502. isConstant = T.isConstant(Context) &&
  1503. PT->getPointeeType().isConstant(Context);
  1504. } else if (T->isObjCObjectPointerType()) {
  1505. // In ObjC, there is usually no "const ObjectPointer" type,
  1506. // so don't check if the pointee type is constant.
  1507. isConstant = T.isConstant(Context);
  1508. }
  1509. if (isConstant) {
  1510. if (const Expr *Init = VD->getAnyInitializer()) {
  1511. // Look through initializers like const char c[] = { "foo" }
  1512. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  1513. if (InitList->isStringLiteralInit())
  1514. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  1515. }
  1516. return checkFormatStringExpr(Init, Args, NumArgs,
  1517. HasVAListArg, format_idx,
  1518. firstDataArg, Type, CallType,
  1519. /*inFunctionCall*/false);
  1520. }
  1521. }
  1522. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  1523. // special check to see if the format string is a function parameter
  1524. // of the function calling the printf function. If the function
  1525. // has an attribute indicating it is a printf-like function, then we
  1526. // should suppress warnings concerning non-literals being used in a call
  1527. // to a vprintf function. For example:
  1528. //
  1529. // void
  1530. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  1531. // va_list ap;
  1532. // va_start(ap, fmt);
  1533. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  1534. // ...
  1535. //
  1536. if (HasVAListArg) {
  1537. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  1538. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  1539. int PVIndex = PV->getFunctionScopeIndex() + 1;
  1540. for (specific_attr_iterator<FormatAttr>
  1541. i = ND->specific_attr_begin<FormatAttr>(),
  1542. e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
  1543. FormatAttr *PVFormat = *i;
  1544. // adjust for implicit parameter
  1545. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1546. if (MD->isInstance())
  1547. ++PVIndex;
  1548. // We also check if the formats are compatible.
  1549. // We can't pass a 'scanf' string to a 'printf' function.
  1550. if (PVIndex == PVFormat->getFormatIdx() &&
  1551. Type == GetFormatStringType(PVFormat))
  1552. return SLCT_UncheckedLiteral;
  1553. }
  1554. }
  1555. }
  1556. }
  1557. }
  1558. return SLCT_NotALiteral;
  1559. }
  1560. case Stmt::CallExprClass:
  1561. case Stmt::CXXMemberCallExprClass: {
  1562. const CallExpr *CE = cast<CallExpr>(E);
  1563. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  1564. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  1565. unsigned ArgIndex = FA->getFormatIdx();
  1566. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1567. if (MD->isInstance())
  1568. --ArgIndex;
  1569. const Expr *Arg = CE->getArg(ArgIndex - 1);
  1570. return checkFormatStringExpr(Arg, Args, NumArgs,
  1571. HasVAListArg, format_idx, firstDataArg,
  1572. Type, CallType, inFunctionCall);
  1573. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1574. unsigned BuiltinID = FD->getBuiltinID();
  1575. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  1576. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  1577. const Expr *Arg = CE->getArg(0);
  1578. return checkFormatStringExpr(Arg, Args, NumArgs,
  1579. HasVAListArg, format_idx,
  1580. firstDataArg, Type, CallType,
  1581. inFunctionCall);
  1582. }
  1583. }
  1584. }
  1585. return SLCT_NotALiteral;
  1586. }
  1587. case Stmt::ObjCStringLiteralClass:
  1588. case Stmt::StringLiteralClass: {
  1589. const StringLiteral *StrE = NULL;
  1590. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  1591. StrE = ObjCFExpr->getString();
  1592. else
  1593. StrE = cast<StringLiteral>(E);
  1594. if (StrE) {
  1595. CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
  1596. firstDataArg, Type, inFunctionCall, CallType);
  1597. return SLCT_CheckedLiteral;
  1598. }
  1599. return SLCT_NotALiteral;
  1600. }
  1601. default:
  1602. return SLCT_NotALiteral;
  1603. }
  1604. }
  1605. void
  1606. Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
  1607. const Expr * const *ExprArgs,
  1608. SourceLocation CallSiteLoc) {
  1609. for (NonNullAttr::args_iterator i = NonNull->args_begin(),
  1610. e = NonNull->args_end();
  1611. i != e; ++i) {
  1612. const Expr *ArgExpr = ExprArgs[*i];
  1613. if (ArgExpr->isNullPointerConstant(Context,
  1614. Expr::NPC_ValueDependentIsNotNull))
  1615. Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  1616. }
  1617. }
  1618. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  1619. return llvm::StringSwitch<FormatStringType>(Format->getType())
  1620. .Case("scanf", FST_Scanf)
  1621. .Cases("printf", "printf0", FST_Printf)
  1622. .Cases("NSString", "CFString", FST_NSString)
  1623. .Case("strftime", FST_Strftime)
  1624. .Case("strfmon", FST_Strfmon)
  1625. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  1626. .Default(FST_Unknown);
  1627. }
  1628. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  1629. /// functions) for correct use of format strings.
  1630. /// Returns true if a format string has been fully checked.
  1631. bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
  1632. unsigned NumArgs, bool IsCXXMember,
  1633. VariadicCallType CallType,
  1634. SourceLocation Loc, SourceRange Range) {
  1635. FormatStringInfo FSI;
  1636. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  1637. return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
  1638. FSI.FirstDataArg, GetFormatStringType(Format),
  1639. CallType, Loc, Range);
  1640. return false;
  1641. }
  1642. bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
  1643. bool HasVAListArg, unsigned format_idx,
  1644. unsigned firstDataArg, FormatStringType Type,
  1645. VariadicCallType CallType,
  1646. SourceLocation Loc, SourceRange Range) {
  1647. // CHECK: printf/scanf-like function is called with no format string.
  1648. if (format_idx >= NumArgs) {
  1649. Diag(Loc, diag::warn_missing_format_string) << Range;
  1650. return false;
  1651. }
  1652. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  1653. // CHECK: format string is not a string literal.
  1654. //
  1655. // Dynamically generated format strings are difficult to
  1656. // automatically vet at compile time. Requiring that format strings
  1657. // are string literals: (1) permits the checking of format strings by
  1658. // the compiler and thereby (2) can practically remove the source of
  1659. // many format string exploits.
  1660. // Format string can be either ObjC string (e.g. @"%d") or
  1661. // C string (e.g. "%d")
  1662. // ObjC string uses the same format specifiers as C string, so we can use
  1663. // the same format string checking logic for both ObjC and C strings.
  1664. StringLiteralCheckType CT =
  1665. checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
  1666. format_idx, firstDataArg, Type, CallType);
  1667. if (CT != SLCT_NotALiteral)
  1668. // Literal format string found, check done!
  1669. return CT == SLCT_CheckedLiteral;
  1670. // Strftime is particular as it always uses a single 'time' argument,
  1671. // so it is safe to pass a non-literal string.
  1672. if (Type == FST_Strftime)
  1673. return false;
  1674. // Do not emit diag when the string param is a macro expansion and the
  1675. // format is either NSString or CFString. This is a hack to prevent
  1676. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  1677. // which are usually used in place of NS and CF string literals.
  1678. if (Type == FST_NSString &&
  1679. SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
  1680. return false;
  1681. // If there are no arguments specified, warn with -Wformat-security, otherwise
  1682. // warn only with -Wformat-nonliteral.
  1683. if (NumArgs == format_idx+1)
  1684. Diag(Args[format_idx]->getLocStart(),
  1685. diag::warn_format_nonliteral_noargs)
  1686. << OrigFormatExpr->getSourceRange();
  1687. else
  1688. Diag(Args[format_idx]->getLocStart(),
  1689. diag::warn_format_nonliteral)
  1690. << OrigFormatExpr->getSourceRange();
  1691. return false;
  1692. }
  1693. namespace {
  1694. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  1695. protected:
  1696. Sema &S;
  1697. const StringLiteral *FExpr;
  1698. const Expr *OrigFormatExpr;
  1699. const unsigned FirstDataArg;
  1700. const unsigned NumDataArgs;
  1701. const char *Beg; // Start of format string.
  1702. const bool HasVAListArg;
  1703. const Expr * const *Args;
  1704. const unsigned NumArgs;
  1705. unsigned FormatIdx;
  1706. llvm::BitVector CoveredArgs;
  1707. bool usesPositionalArgs;
  1708. bool atFirstArg;
  1709. bool inFunctionCall;
  1710. Sema::VariadicCallType CallType;
  1711. public:
  1712. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  1713. const Expr *origFormatExpr, unsigned firstDataArg,
  1714. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  1715. Expr **args, unsigned numArgs,
  1716. unsigned formatIdx, bool inFunctionCall,
  1717. Sema::VariadicCallType callType)
  1718. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  1719. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
  1720. Beg(beg), HasVAListArg(hasVAListArg),
  1721. Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
  1722. usesPositionalArgs(false), atFirstArg(true),
  1723. inFunctionCall(inFunctionCall), CallType(callType) {
  1724. CoveredArgs.resize(numDataArgs);
  1725. CoveredArgs.reset();
  1726. }
  1727. void DoneProcessing();
  1728. void HandleIncompleteSpecifier(const char *startSpecifier,
  1729. unsigned specifierLen);
  1730. void HandleInvalidLengthModifier(
  1731. const analyze_format_string::FormatSpecifier &FS,
  1732. const analyze_format_string::ConversionSpecifier &CS,
  1733. const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
  1734. void HandleNonStandardLengthModifier(
  1735. const analyze_format_string::FormatSpecifier &FS,
  1736. const char *startSpecifier, unsigned specifierLen);
  1737. void HandleNonStandardConversionSpecifier(
  1738. const analyze_format_string::ConversionSpecifier &CS,
  1739. const char *startSpecifier, unsigned specifierLen);
  1740. virtual void HandlePosition(const char *startPos, unsigned posLen);
  1741. virtual void HandleInvalidPosition(const char *startSpecifier,
  1742. unsigned specifierLen,
  1743. analyze_format_string::PositionContext p);
  1744. virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
  1745. void HandleNullChar(const char *nullCharacter);
  1746. template <typename Range>
  1747. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  1748. const Expr *ArgumentExpr,
  1749. PartialDiagnostic PDiag,
  1750. SourceLocation StringLoc,
  1751. bool IsStringLocation, Range StringRange,
  1752. ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
  1753. protected:
  1754. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  1755. const char *startSpec,
  1756. unsigned specifierLen,
  1757. const char *csStart, unsigned csLen);
  1758. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1759. const char *startSpec,
  1760. unsigned specifierLen);
  1761. SourceRange getFormatStringRange();
  1762. CharSourceRange getSpecifierRange(const char *startSpecifier,
  1763. unsigned specifierLen);
  1764. SourceLocation getLocationOfByte(const char *x);
  1765. const Expr *getDataArg(unsigned i) const;
  1766. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  1767. const analyze_format_string::ConversionSpecifier &CS,
  1768. const char *startSpecifier, unsigned specifierLen,
  1769. unsigned argIndex);
  1770. template <typename Range>
  1771. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  1772. bool IsStringLocation, Range StringRange,
  1773. ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
  1774. void CheckPositionalAndNonpositionalArgs(
  1775. const analyze_format_string::FormatSpecifier *FS);
  1776. };
  1777. }
  1778. SourceRange CheckFormatHandler::getFormatStringRange() {
  1779. return OrigFormatExpr->getSourceRange();
  1780. }
  1781. CharSourceRange CheckFormatHandler::
  1782. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  1783. SourceLocation Start = getLocationOfByte(startSpecifier);
  1784. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  1785. // Advance the end SourceLocation by one due to half-open ranges.
  1786. End = End.getLocWithOffset(1);
  1787. return CharSourceRange::getCharRange(Start, End);
  1788. }
  1789. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  1790. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  1791. }
  1792. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  1793. unsigned specifierLen){
  1794. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  1795. getLocationOfByte(startSpecifier),
  1796. /*IsStringLocation*/true,
  1797. getSpecifierRange(startSpecifier, specifierLen));
  1798. }
  1799. void CheckFormatHandler::HandleInvalidLengthModifier(
  1800. const analyze_format_string::FormatSpecifier &FS,
  1801. const analyze_format_string::ConversionSpecifier &CS,
  1802. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  1803. using namespace analyze_format_string;
  1804. const LengthModifier &LM = FS.getLengthModifier();
  1805. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  1806. // See if we know how to fix this length modifier.
  1807. llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  1808. if (FixedLM) {
  1809. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  1810. getLocationOfByte(LM.getStart()),
  1811. /*IsStringLocation*/true,
  1812. getSpecifierRange(startSpecifier, specifierLen));
  1813. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  1814. << FixedLM->toString()
  1815. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  1816. } else {
  1817. FixItHint Hint;
  1818. if (DiagID == diag::warn_format_nonsensical_length)
  1819. Hint = FixItHint::CreateRemoval(LMRange);
  1820. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  1821. getLocationOfByte(LM.getStart()),
  1822. /*IsStringLocation*/true,
  1823. getSpecifierRange(startSpecifier, specifierLen),
  1824. Hint);
  1825. }
  1826. }
  1827. void CheckFormatHandler::HandleNonStandardLengthModifier(
  1828. const analyze_format_string::FormatSpecifier &FS,
  1829. const char *startSpecifier, unsigned specifierLen) {
  1830. using namespace analyze_format_string;
  1831. const LengthModifier &LM = FS.getLengthModifier();
  1832. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  1833. // See if we know how to fix this length modifier.
  1834. llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  1835. if (FixedLM) {
  1836. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  1837. << LM.toString() << 0,
  1838. getLocationOfByte(LM.getStart()),
  1839. /*IsStringLocation*/true,
  1840. getSpecifierRange(startSpecifier, specifierLen));
  1841. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  1842. << FixedLM->toString()
  1843. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  1844. } else {
  1845. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  1846. << LM.toString() << 0,
  1847. getLocationOfByte(LM.getStart()),
  1848. /*IsStringLocation*/true,
  1849. getSpecifierRange(startSpecifier, specifierLen));
  1850. }
  1851. }
  1852. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  1853. const analyze_format_string::ConversionSpecifier &CS,
  1854. const char *startSpecifier, unsigned specifierLen) {
  1855. using namespace analyze_format_string;
  1856. // See if we know how to fix this conversion specifier.
  1857. llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  1858. if (FixedCS) {
  1859. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  1860. << CS.toString() << /*conversion specifier*/1,
  1861. getLocationOfByte(CS.getStart()),
  1862. /*IsStringLocation*/true,
  1863. getSpecifierRange(startSpecifier, specifierLen));
  1864. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  1865. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  1866. << FixedCS->toString()
  1867. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  1868. } else {
  1869. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  1870. << CS.toString() << /*conversion specifier*/1,
  1871. getLocationOfByte(CS.getStart()),
  1872. /*IsStringLocation*/true,
  1873. getSpecifierRange(startSpecifier, specifierLen));
  1874. }
  1875. }
  1876. void CheckFormatHandler::HandlePosition(const char *startPos,
  1877. unsigned posLen) {
  1878. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  1879. getLocationOfByte(startPos),
  1880. /*IsStringLocation*/true,
  1881. getSpecifierRange(startPos, posLen));
  1882. }
  1883. void
  1884. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  1885. analyze_format_string::PositionContext p) {
  1886. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  1887. << (unsigned) p,
  1888. getLocationOfByte(startPos), /*IsStringLocation*/true,
  1889. getSpecifierRange(startPos, posLen));
  1890. }
  1891. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  1892. unsigned posLen) {
  1893. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  1894. getLocationOfByte(startPos),
  1895. /*IsStringLocation*/true,
  1896. getSpecifierRange(startPos, posLen));
  1897. }
  1898. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  1899. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  1900. // The presence of a null character is likely an error.
  1901. EmitFormatDiagnostic(
  1902. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  1903. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  1904. getFormatStringRange());
  1905. }
  1906. }
  1907. // Note that this may return NULL if there was an error parsing or building
  1908. // one of the argument expressions.
  1909. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  1910. return Args[FirstDataArg + i];
  1911. }
  1912. void CheckFormatHandler::DoneProcessing() {
  1913. // Does the number of data arguments exceed the number of
  1914. // format conversions in the format string?
  1915. if (!HasVAListArg) {
  1916. // Find any arguments that weren't covered.
  1917. CoveredArgs.flip();
  1918. signed notCoveredArg = CoveredArgs.find_first();
  1919. if (notCoveredArg >= 0) {
  1920. assert((unsigned)notCoveredArg < NumDataArgs);
  1921. if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
  1922. SourceLocation Loc = E->getLocStart();
  1923. if (!S.getSourceManager().isInSystemMacro(Loc)) {
  1924. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  1925. Loc, /*IsStringLocation*/false,
  1926. getFormatStringRange());
  1927. }
  1928. }
  1929. }
  1930. }
  1931. }
  1932. bool
  1933. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  1934. SourceLocation Loc,
  1935. const char *startSpec,
  1936. unsigned specifierLen,
  1937. const char *csStart,
  1938. unsigned csLen) {
  1939. bool keepGoing = true;
  1940. if (argIndex < NumDataArgs) {
  1941. // Consider the argument coverered, even though the specifier doesn't
  1942. // make sense.
  1943. CoveredArgs.set(argIndex);
  1944. }
  1945. else {
  1946. // If argIndex exceeds the number of data arguments we
  1947. // don't issue a warning because that is just a cascade of warnings (and
  1948. // they may have intended '%%' anyway). We don't want to continue processing
  1949. // the format string after this point, however, as we will like just get
  1950. // gibberish when trying to match arguments.
  1951. keepGoing = false;
  1952. }
  1953. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  1954. << StringRef(csStart, csLen),
  1955. Loc, /*IsStringLocation*/true,
  1956. getSpecifierRange(startSpec, specifierLen));
  1957. return keepGoing;
  1958. }
  1959. void
  1960. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1961. const char *startSpec,
  1962. unsigned specifierLen) {
  1963. EmitFormatDiagnostic(
  1964. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  1965. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  1966. }
  1967. bool
  1968. CheckFormatHandler::CheckNumArgs(
  1969. const analyze_format_string::FormatSpecifier &FS,
  1970. const analyze_format_string::ConversionSpecifier &CS,
  1971. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  1972. if (argIndex >= NumDataArgs) {
  1973. PartialDiagnostic PDiag = FS.usesPositionalArg()
  1974. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  1975. << (argIndex+1) << NumDataArgs)
  1976. : S.PDiag(diag::warn_printf_insufficient_data_args);
  1977. EmitFormatDiagnostic(
  1978. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  1979. getSpecifierRange(startSpecifier, specifierLen));
  1980. return false;
  1981. }
  1982. return true;
  1983. }
  1984. template<typename Range>
  1985. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  1986. SourceLocation Loc,
  1987. bool IsStringLocation,
  1988. Range StringRange,
  1989. ArrayRef<FixItHint> FixIt) {
  1990. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  1991. Loc, IsStringLocation, StringRange, FixIt);
  1992. }
  1993. /// \brief If the format string is not within the funcion call, emit a note
  1994. /// so that the function call and string are in diagnostic messages.
  1995. ///
  1996. /// \param InFunctionCall if true, the format string is within the function
  1997. /// call and only one diagnostic message will be produced. Otherwise, an
  1998. /// extra note will be emitted pointing to location of the format string.
  1999. ///
  2000. /// \param ArgumentExpr the expression that is passed as the format string
  2001. /// argument in the function call. Used for getting locations when two
  2002. /// diagnostics are emitted.
  2003. ///
  2004. /// \param PDiag the callee should already have provided any strings for the
  2005. /// diagnostic message. This function only adds locations and fixits
  2006. /// to diagnostics.
  2007. ///
  2008. /// \param Loc primary location for diagnostic. If two diagnostics are
  2009. /// required, one will be at Loc and a new SourceLocation will be created for
  2010. /// the other one.
  2011. ///
  2012. /// \param IsStringLocation if true, Loc points to the format string should be
  2013. /// used for the note. Otherwise, Loc points to the argument list and will
  2014. /// be used with PDiag.
  2015. ///
  2016. /// \param StringRange some or all of the string to highlight. This is
  2017. /// templated so it can accept either a CharSourceRange or a SourceRange.
  2018. ///
  2019. /// \param FixIt optional fix it hint for the format string.
  2020. template<typename Range>
  2021. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  2022. const Expr *ArgumentExpr,
  2023. PartialDiagnostic PDiag,
  2024. SourceLocation Loc,
  2025. bool IsStringLocation,
  2026. Range StringRange,
  2027. ArrayRef<FixItHint> FixIt) {
  2028. if (InFunctionCall) {
  2029. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  2030. D << StringRange;
  2031. for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
  2032. I != E; ++I) {
  2033. D << *I;
  2034. }
  2035. } else {
  2036. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  2037. << ArgumentExpr->getSourceRange();
  2038. const Sema::SemaDiagnosticBuilder &Note =
  2039. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  2040. diag::note_format_string_defined);
  2041. Note << StringRange;
  2042. for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
  2043. I != E; ++I) {
  2044. Note << *I;
  2045. }
  2046. }
  2047. }
  2048. //===--- CHECK: Printf format string checking ------------------------------===//
  2049. namespace {
  2050. class CheckPrintfHandler : public CheckFormatHandler {
  2051. bool ObjCContext;
  2052. public:
  2053. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  2054. const Expr *origFormatExpr, unsigned firstDataArg,
  2055. unsigned numDataArgs, bool isObjC,
  2056. const char *beg, bool hasVAListArg,
  2057. Expr **Args, unsigned NumArgs,
  2058. unsigned formatIdx, bool inFunctionCall,
  2059. Sema::VariadicCallType CallType)
  2060. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  2061. numDataArgs, beg, hasVAListArg, Args, NumArgs,
  2062. formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
  2063. {}
  2064. bool HandleInvalidPrintfConversionSpecifier(
  2065. const analyze_printf::PrintfSpecifier &FS,
  2066. const char *startSpecifier,
  2067. unsigned specifierLen);
  2068. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  2069. const char *startSpecifier,
  2070. unsigned specifierLen);
  2071. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2072. const char *StartSpecifier,
  2073. unsigned SpecifierLen,
  2074. const Expr *E);
  2075. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  2076. const char *startSpecifier, unsigned specifierLen);
  2077. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  2078. const analyze_printf::OptionalAmount &Amt,
  2079. unsigned type,
  2080. const char *startSpecifier, unsigned specifierLen);
  2081. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2082. const analyze_printf::OptionalFlag &flag,
  2083. const char *startSpecifier, unsigned specifierLen);
  2084. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  2085. const analyze_printf::OptionalFlag &ignoredFlag,
  2086. const analyze_printf::OptionalFlag &flag,
  2087. const char *startSpecifier, unsigned specifierLen);
  2088. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  2089. const Expr *E, const CharSourceRange &CSR);
  2090. };
  2091. }
  2092. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  2093. const analyze_printf::PrintfSpecifier &FS,
  2094. const char *startSpecifier,
  2095. unsigned specifierLen) {
  2096. const analyze_printf::PrintfConversionSpecifier &CS =
  2097. FS.getConversionSpecifier();
  2098. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2099. getLocationOfByte(CS.getStart()),
  2100. startSpecifier, specifierLen,
  2101. CS.getStart(), CS.getLength());
  2102. }
  2103. bool CheckPrintfHandler::HandleAmount(
  2104. const analyze_format_string::OptionalAmount &Amt,
  2105. unsigned k, const char *startSpecifier,
  2106. unsigned specifierLen) {
  2107. if (Amt.hasDataArgument()) {
  2108. if (!HasVAListArg) {
  2109. unsigned argIndex = Amt.getArgIndex();
  2110. if (argIndex >= NumDataArgs) {
  2111. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  2112. << k,
  2113. getLocationOfByte(Amt.getStart()),
  2114. /*IsStringLocation*/true,
  2115. getSpecifierRange(startSpecifier, specifierLen));
  2116. // Don't do any more checking. We will just emit
  2117. // spurious errors.
  2118. return false;
  2119. }
  2120. // Type check the data argument. It should be an 'int'.
  2121. // Although not in conformance with C99, we also allow the argument to be
  2122. // an 'unsigned int' as that is a reasonably safe case. GCC also
  2123. // doesn't emit a warning for that case.
  2124. CoveredArgs.set(argIndex);
  2125. const Expr *Arg = getDataArg(argIndex);
  2126. if (!Arg)
  2127. return false;
  2128. QualType T = Arg->getType();
  2129. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  2130. assert(AT.isValid());
  2131. if (!AT.matchesType(S.Context, T)) {
  2132. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  2133. << k << AT.getRepresentativeTypeName(S.Context)
  2134. << T << Arg->getSourceRange(),
  2135. getLocationOfByte(Amt.getStart()),
  2136. /*IsStringLocation*/true,
  2137. getSpecifierRange(startSpecifier, specifierLen));
  2138. // Don't do any more checking. We will just emit
  2139. // spurious errors.
  2140. return false;
  2141. }
  2142. }
  2143. }
  2144. return true;
  2145. }
  2146. void CheckPrintfHandler::HandleInvalidAmount(
  2147. const analyze_printf::PrintfSpecifier &FS,
  2148. const analyze_printf::OptionalAmount &Amt,
  2149. unsigned type,
  2150. const char *startSpecifier,
  2151. unsigned specifierLen) {
  2152. const analyze_printf::PrintfConversionSpecifier &CS =
  2153. FS.getConversionSpecifier();
  2154. FixItHint fixit =
  2155. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  2156. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  2157. Amt.getConstantLength()))
  2158. : FixItHint();
  2159. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  2160. << type << CS.toString(),
  2161. getLocationOfByte(Amt.getStart()),
  2162. /*IsStringLocation*/true,
  2163. getSpecifierRange(startSpecifier, specifierLen),
  2164. fixit);
  2165. }
  2166. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2167. const analyze_printf::OptionalFlag &flag,
  2168. const char *startSpecifier,
  2169. unsigned specifierLen) {
  2170. // Warn about pointless flag with a fixit removal.
  2171. const analyze_printf::PrintfConversionSpecifier &CS =
  2172. FS.getConversionSpecifier();
  2173. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  2174. << flag.toString() << CS.toString(),
  2175. getLocationOfByte(flag.getPosition()),
  2176. /*IsStringLocation*/true,
  2177. getSpecifierRange(startSpecifier, specifierLen),
  2178. FixItHint::CreateRemoval(
  2179. getSpecifierRange(flag.getPosition(), 1)));
  2180. }
  2181. void CheckPrintfHandler::HandleIgnoredFlag(
  2182. const analyze_printf::PrintfSpecifier &FS,
  2183. const analyze_printf::OptionalFlag &ignoredFlag,
  2184. const analyze_printf::OptionalFlag &flag,
  2185. const char *startSpecifier,
  2186. unsigned specifierLen) {
  2187. // Warn about ignored flag with a fixit removal.
  2188. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  2189. << ignoredFlag.toString() << flag.toString(),
  2190. getLocationOfByte(ignoredFlag.getPosition()),
  2191. /*IsStringLocation*/true,
  2192. getSpecifierRange(startSpecifier, specifierLen),
  2193. FixItHint::CreateRemoval(
  2194. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  2195. }
  2196. // Determines if the specified is a C++ class or struct containing
  2197. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  2198. // "c_str()").
  2199. template<typename MemberKind>
  2200. static llvm::SmallPtrSet<MemberKind*, 1>
  2201. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  2202. const RecordType *RT = Ty->getAs<RecordType>();
  2203. llvm::SmallPtrSet<MemberKind*, 1> Results;
  2204. if (!RT)
  2205. return Results;
  2206. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  2207. if (!RD)
  2208. return Results;
  2209. LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
  2210. Sema::LookupMemberName);
  2211. // We just need to include all members of the right kind turned up by the
  2212. // filter, at this point.
  2213. if (S.LookupQualifiedName(R, RT->getDecl()))
  2214. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2215. NamedDecl *decl = (*I)->getUnderlyingDecl();
  2216. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  2217. Results.insert(FK);
  2218. }
  2219. return Results;
  2220. }
  2221. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  2222. // better diagnostic if so. AT is assumed to be valid.
  2223. // Returns true when a c_str() conversion method is found.
  2224. bool CheckPrintfHandler::checkForCStrMembers(
  2225. const analyze_printf::ArgType &AT, const Expr *E,
  2226. const CharSourceRange &CSR) {
  2227. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  2228. MethodSet Results =
  2229. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  2230. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  2231. MI != ME; ++MI) {
  2232. const CXXMethodDecl *Method = *MI;
  2233. if (Method->getNumParams() == 0 &&
  2234. AT.matchesType(S.Context, Method->getResultType())) {
  2235. // FIXME: Suggest parens if the expression needs them.
  2236. SourceLocation EndLoc =
  2237. S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
  2238. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  2239. << "c_str()"
  2240. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  2241. return true;
  2242. }
  2243. }
  2244. return false;
  2245. }
  2246. bool
  2247. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  2248. &FS,
  2249. const char *startSpecifier,
  2250. unsigned specifierLen) {
  2251. using namespace analyze_format_string;
  2252. using namespace analyze_printf;
  2253. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  2254. if (FS.consumesDataArgument()) {
  2255. if (atFirstArg) {
  2256. atFirstArg = false;
  2257. usesPositionalArgs = FS.usesPositionalArg();
  2258. }
  2259. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2260. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2261. startSpecifier, specifierLen);
  2262. return false;
  2263. }
  2264. }
  2265. // First check if the field width, precision, and conversion specifier
  2266. // have matching data arguments.
  2267. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  2268. startSpecifier, specifierLen)) {
  2269. return false;
  2270. }
  2271. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  2272. startSpecifier, specifierLen)) {
  2273. return false;
  2274. }
  2275. if (!CS.consumesDataArgument()) {
  2276. // FIXME: Technically specifying a precision or field width here
  2277. // makes no sense. Worth issuing a warning at some point.
  2278. return true;
  2279. }
  2280. // Consume the argument.
  2281. unsigned argIndex = FS.getArgIndex();
  2282. if (argIndex < NumDataArgs) {
  2283. // The check to see if the argIndex is valid will come later.
  2284. // We set the bit here because we may exit early from this
  2285. // function if we encounter some other error.
  2286. CoveredArgs.set(argIndex);
  2287. }
  2288. // Check for using an Objective-C specific conversion specifier
  2289. // in a non-ObjC literal.
  2290. if (!ObjCContext && CS.isObjCArg()) {
  2291. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  2292. specifierLen);
  2293. }
  2294. // Check for invalid use of field width
  2295. if (!FS.hasValidFieldWidth()) {
  2296. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  2297. startSpecifier, specifierLen);
  2298. }
  2299. // Check for invalid use of precision
  2300. if (!FS.hasValidPrecision()) {
  2301. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  2302. startSpecifier, specifierLen);
  2303. }
  2304. // Check each flag does not conflict with any other component.
  2305. if (!FS.hasValidThousandsGroupingPrefix())
  2306. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  2307. if (!FS.hasValidLeadingZeros())
  2308. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  2309. if (!FS.hasValidPlusPrefix())
  2310. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  2311. if (!FS.hasValidSpacePrefix())
  2312. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  2313. if (!FS.hasValidAlternativeForm())
  2314. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  2315. if (!FS.hasValidLeftJustified())
  2316. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  2317. // Check that flags are not ignored by another flag
  2318. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  2319. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  2320. startSpecifier, specifierLen);
  2321. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  2322. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  2323. startSpecifier, specifierLen);
  2324. // Check the length modifier is valid with the given conversion specifier.
  2325. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  2326. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2327. diag::warn_format_nonsensical_length);
  2328. else if (!FS.hasStandardLengthModifier())
  2329. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  2330. else if (!FS.hasStandardLengthConversionCombination())
  2331. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2332. diag::warn_format_non_standard_conversion_spec);
  2333. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2334. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2335. // The remaining checks depend on the data arguments.
  2336. if (HasVAListArg)
  2337. return true;
  2338. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2339. return false;
  2340. const Expr *Arg = getDataArg(argIndex);
  2341. if (!Arg)
  2342. return true;
  2343. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  2344. }
  2345. static bool requiresParensToAddCast(const Expr *E) {
  2346. // FIXME: We should have a general way to reason about operator
  2347. // precedence and whether parens are actually needed here.
  2348. // Take care of a few common cases where they aren't.
  2349. const Expr *Inside = E->IgnoreImpCasts();
  2350. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  2351. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  2352. switch (Inside->getStmtClass()) {
  2353. case Stmt::ArraySubscriptExprClass:
  2354. case Stmt::CallExprClass:
  2355. case Stmt::DeclRefExprClass:
  2356. case Stmt::MemberExprClass:
  2357. case Stmt::ObjCIvarRefExprClass:
  2358. case Stmt::ObjCMessageExprClass:
  2359. case Stmt::ObjCPropertyRefExprClass:
  2360. case Stmt::ParenExprClass:
  2361. case Stmt::UnaryOperatorClass:
  2362. return false;
  2363. default:
  2364. return true;
  2365. }
  2366. }
  2367. bool
  2368. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2369. const char *StartSpecifier,
  2370. unsigned SpecifierLen,
  2371. const Expr *E) {
  2372. using namespace analyze_format_string;
  2373. using namespace analyze_printf;
  2374. // Now type check the data expression that matches the
  2375. // format specifier.
  2376. const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
  2377. ObjCContext);
  2378. if (!AT.isValid())
  2379. return true;
  2380. QualType IntendedTy = E->getType();
  2381. if (AT.matchesType(S.Context, IntendedTy))
  2382. return true;
  2383. // Look through argument promotions for our error message's reported type.
  2384. // This includes the integral and floating promotions, but excludes array
  2385. // and function pointer decay; seeing that an argument intended to be a
  2386. // string has type 'char [6]' is probably more confusing than 'char *'.
  2387. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2388. if (ICE->getCastKind() == CK_IntegralCast ||
  2389. ICE->getCastKind() == CK_FloatingCast) {
  2390. E = ICE->getSubExpr();
  2391. IntendedTy = E->getType();
  2392. // Check if we didn't match because of an implicit cast from a 'char'
  2393. // or 'short' to an 'int'. This is done because printf is a varargs
  2394. // function.
  2395. if (ICE->getType() == S.Context.IntTy ||
  2396. ICE->getType() == S.Context.UnsignedIntTy) {
  2397. // All further checking is done on the subexpression.
  2398. if (AT.matchesType(S.Context, IntendedTy))
  2399. return true;
  2400. }
  2401. }
  2402. }
  2403. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  2404. // Special-case some of Darwin's platform-independence types.
  2405. if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
  2406. StringRef Name = UserTy->getDecl()->getName();
  2407. IntendedTy = llvm::StringSwitch<QualType>(Name)
  2408. .Case("NSInteger", S.Context.LongTy)
  2409. .Case("NSUInteger", S.Context.UnsignedLongTy)
  2410. .Case("SInt32", S.Context.IntTy)
  2411. .Case("UInt32", S.Context.UnsignedIntTy)
  2412. .Default(IntendedTy);
  2413. }
  2414. }
  2415. // We may be able to offer a FixItHint if it is a supported type.
  2416. PrintfSpecifier fixedFS = FS;
  2417. bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
  2418. S.Context, ObjCContext);
  2419. if (success) {
  2420. // Get the fix string from the fixed format specifier
  2421. SmallString<16> buf;
  2422. llvm::raw_svector_ostream os(buf);
  2423. fixedFS.toString(os);
  2424. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  2425. if (IntendedTy != E->getType()) {
  2426. // The canonical type for formatting this value is different from the
  2427. // actual type of the expression. (This occurs, for example, with Darwin's
  2428. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  2429. // should be printed as 'long' for 64-bit compatibility.)
  2430. // Rather than emitting a normal format/argument mismatch, we want to
  2431. // add a cast to the recommended type (and correct the format string
  2432. // if necessary).
  2433. SmallString<16> CastBuf;
  2434. llvm::raw_svector_ostream CastFix(CastBuf);
  2435. CastFix << "(";
  2436. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  2437. CastFix << ")";
  2438. SmallVector<FixItHint,4> Hints;
  2439. if (!AT.matchesType(S.Context, IntendedTy))
  2440. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  2441. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  2442. // If there's already a cast present, just replace it.
  2443. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  2444. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  2445. } else if (!requiresParensToAddCast(E)) {
  2446. // If the expression has high enough precedence,
  2447. // just write the C-style cast.
  2448. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  2449. CastFix.str()));
  2450. } else {
  2451. // Otherwise, add parens around the expression as well as the cast.
  2452. CastFix << "(";
  2453. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  2454. CastFix.str()));
  2455. SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
  2456. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  2457. }
  2458. // We extract the name from the typedef because we don't want to show
  2459. // the underlying type in the diagnostic.
  2460. const TypedefType *UserTy = cast<TypedefType>(E->getType());
  2461. StringRef Name = UserTy->getDecl()->getName();
  2462. // Finally, emit the diagnostic.
  2463. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  2464. << Name << IntendedTy
  2465. << E->getSourceRange(),
  2466. E->getLocStart(), /*IsStringLocation=*/false,
  2467. SpecRange, Hints);
  2468. } else {
  2469. EmitFormatDiagnostic(
  2470. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2471. << AT.getRepresentativeTypeName(S.Context) << IntendedTy
  2472. << E->getSourceRange(),
  2473. E->getLocStart(),
  2474. /*IsStringLocation*/false,
  2475. SpecRange,
  2476. FixItHint::CreateReplacement(SpecRange, os.str()));
  2477. }
  2478. } else {
  2479. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  2480. SpecifierLen);
  2481. // Since the warning for passing non-POD types to variadic functions
  2482. // was deferred until now, we emit a warning for non-POD
  2483. // arguments here.
  2484. if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
  2485. unsigned DiagKind;
  2486. if (E->getType()->isObjCObjectType())
  2487. DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
  2488. else
  2489. DiagKind = diag::warn_non_pod_vararg_with_format_string;
  2490. EmitFormatDiagnostic(
  2491. S.PDiag(DiagKind)
  2492. << S.getLangOpts().CPlusPlus0x
  2493. << E->getType()
  2494. << CallType
  2495. << AT.getRepresentativeTypeName(S.Context)
  2496. << CSR
  2497. << E->getSourceRange(),
  2498. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2499. checkForCStrMembers(AT, E, CSR);
  2500. } else
  2501. EmitFormatDiagnostic(
  2502. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2503. << AT.getRepresentativeTypeName(S.Context) << E->getType()
  2504. << CSR
  2505. << E->getSourceRange(),
  2506. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2507. }
  2508. return true;
  2509. }
  2510. //===--- CHECK: Scanf format string checking ------------------------------===//
  2511. namespace {
  2512. class CheckScanfHandler : public CheckFormatHandler {
  2513. public:
  2514. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  2515. const Expr *origFormatExpr, unsigned firstDataArg,
  2516. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2517. Expr **Args, unsigned NumArgs,
  2518. unsigned formatIdx, bool inFunctionCall,
  2519. Sema::VariadicCallType CallType)
  2520. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  2521. numDataArgs, beg, hasVAListArg,
  2522. Args, NumArgs, formatIdx, inFunctionCall, CallType)
  2523. {}
  2524. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  2525. const char *startSpecifier,
  2526. unsigned specifierLen);
  2527. bool HandleInvalidScanfConversionSpecifier(
  2528. const analyze_scanf::ScanfSpecifier &FS,
  2529. const char *startSpecifier,
  2530. unsigned specifierLen);
  2531. void HandleIncompleteScanList(const char *start, const char *end);
  2532. };
  2533. }
  2534. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  2535. const char *end) {
  2536. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  2537. getLocationOfByte(end), /*IsStringLocation*/true,
  2538. getSpecifierRange(start, end - start));
  2539. }
  2540. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  2541. const analyze_scanf::ScanfSpecifier &FS,
  2542. const char *startSpecifier,
  2543. unsigned specifierLen) {
  2544. const analyze_scanf::ScanfConversionSpecifier &CS =
  2545. FS.getConversionSpecifier();
  2546. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2547. getLocationOfByte(CS.getStart()),
  2548. startSpecifier, specifierLen,
  2549. CS.getStart(), CS.getLength());
  2550. }
  2551. bool CheckScanfHandler::HandleScanfSpecifier(
  2552. const analyze_scanf::ScanfSpecifier &FS,
  2553. const char *startSpecifier,
  2554. unsigned specifierLen) {
  2555. using namespace analyze_scanf;
  2556. using namespace analyze_format_string;
  2557. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  2558. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  2559. // be used to decide if we are using positional arguments consistently.
  2560. if (FS.consumesDataArgument()) {
  2561. if (atFirstArg) {
  2562. atFirstArg = false;
  2563. usesPositionalArgs = FS.usesPositionalArg();
  2564. }
  2565. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2566. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2567. startSpecifier, specifierLen);
  2568. return false;
  2569. }
  2570. }
  2571. // Check if the field with is non-zero.
  2572. const OptionalAmount &Amt = FS.getFieldWidth();
  2573. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  2574. if (Amt.getConstantAmount() == 0) {
  2575. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  2576. Amt.getConstantLength());
  2577. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  2578. getLocationOfByte(Amt.getStart()),
  2579. /*IsStringLocation*/true, R,
  2580. FixItHint::CreateRemoval(R));
  2581. }
  2582. }
  2583. if (!FS.consumesDataArgument()) {
  2584. // FIXME: Technically specifying a precision or field width here
  2585. // makes no sense. Worth issuing a warning at some point.
  2586. return true;
  2587. }
  2588. // Consume the argument.
  2589. unsigned argIndex = FS.getArgIndex();
  2590. if (argIndex < NumDataArgs) {
  2591. // The check to see if the argIndex is valid will come later.
  2592. // We set the bit here because we may exit early from this
  2593. // function if we encounter some other error.
  2594. CoveredArgs.set(argIndex);
  2595. }
  2596. // Check the length modifier is valid with the given conversion specifier.
  2597. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  2598. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2599. diag::warn_format_nonsensical_length);
  2600. else if (!FS.hasStandardLengthModifier())
  2601. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  2602. else if (!FS.hasStandardLengthConversionCombination())
  2603. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2604. diag::warn_format_non_standard_conversion_spec);
  2605. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2606. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2607. // The remaining checks depend on the data arguments.
  2608. if (HasVAListArg)
  2609. return true;
  2610. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2611. return false;
  2612. // Check that the argument type matches the format specifier.
  2613. const Expr *Ex = getDataArg(argIndex);
  2614. if (!Ex)
  2615. return true;
  2616. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  2617. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
  2618. ScanfSpecifier fixedFS = FS;
  2619. bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
  2620. S.Context);
  2621. if (success) {
  2622. // Get the fix string from the fixed format specifier.
  2623. SmallString<128> buf;
  2624. llvm::raw_svector_ostream os(buf);
  2625. fixedFS.toString(os);
  2626. EmitFormatDiagnostic(
  2627. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2628. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  2629. << Ex->getSourceRange(),
  2630. Ex->getLocStart(),
  2631. /*IsStringLocation*/false,
  2632. getSpecifierRange(startSpecifier, specifierLen),
  2633. FixItHint::CreateReplacement(
  2634. getSpecifierRange(startSpecifier, specifierLen),
  2635. os.str()));
  2636. } else {
  2637. EmitFormatDiagnostic(
  2638. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2639. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  2640. << Ex->getSourceRange(),
  2641. Ex->getLocStart(),
  2642. /*IsStringLocation*/false,
  2643. getSpecifierRange(startSpecifier, specifierLen));
  2644. }
  2645. }
  2646. return true;
  2647. }
  2648. void Sema::CheckFormatString(const StringLiteral *FExpr,
  2649. const Expr *OrigFormatExpr,
  2650. Expr **Args, unsigned NumArgs,
  2651. bool HasVAListArg, unsigned format_idx,
  2652. unsigned firstDataArg, FormatStringType Type,
  2653. bool inFunctionCall, VariadicCallType CallType) {
  2654. // CHECK: is the format string a wide literal?
  2655. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  2656. CheckFormatHandler::EmitFormatDiagnostic(
  2657. *this, inFunctionCall, Args[format_idx],
  2658. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  2659. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2660. return;
  2661. }
  2662. // Str - The format string. NOTE: this is NOT null-terminated!
  2663. StringRef StrRef = FExpr->getString();
  2664. const char *Str = StrRef.data();
  2665. unsigned StrLen = StrRef.size();
  2666. const unsigned numDataArgs = NumArgs - firstDataArg;
  2667. // CHECK: empty format string?
  2668. if (StrLen == 0 && numDataArgs > 0) {
  2669. CheckFormatHandler::EmitFormatDiagnostic(
  2670. *this, inFunctionCall, Args[format_idx],
  2671. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  2672. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2673. return;
  2674. }
  2675. if (Type == FST_Printf || Type == FST_NSString) {
  2676. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  2677. numDataArgs, (Type == FST_NSString),
  2678. Str, HasVAListArg, Args, NumArgs, format_idx,
  2679. inFunctionCall, CallType);
  2680. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  2681. getLangOpts(),
  2682. Context.getTargetInfo()))
  2683. H.DoneProcessing();
  2684. } else if (Type == FST_Scanf) {
  2685. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
  2686. Str, HasVAListArg, Args, NumArgs, format_idx,
  2687. inFunctionCall, CallType);
  2688. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  2689. getLangOpts(),
  2690. Context.getTargetInfo()))
  2691. H.DoneProcessing();
  2692. } // TODO: handle other formats
  2693. }
  2694. //===--- CHECK: Standard memory functions ---------------------------------===//
  2695. /// \brief Determine whether the given type is a dynamic class type (e.g.,
  2696. /// whether it has a vtable).
  2697. static bool isDynamicClassType(QualType T) {
  2698. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  2699. if (CXXRecordDecl *Definition = Record->getDefinition())
  2700. if (Definition->isDynamicClass())
  2701. return true;
  2702. return false;
  2703. }
  2704. /// \brief If E is a sizeof expression, returns its argument expression,
  2705. /// otherwise returns NULL.
  2706. static const Expr *getSizeOfExprArg(const Expr* E) {
  2707. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2708. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2709. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  2710. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  2711. return 0;
  2712. }
  2713. /// \brief If E is a sizeof expression, returns its argument type.
  2714. static QualType getSizeOfArgType(const Expr* E) {
  2715. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2716. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2717. if (SizeOf->getKind() == clang::UETT_SizeOf)
  2718. return SizeOf->getTypeOfArgument();
  2719. return QualType();
  2720. }
  2721. /// \brief Check for dangerous or invalid arguments to memset().
  2722. ///
  2723. /// This issues warnings on known problematic, dangerous or unspecified
  2724. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  2725. /// function calls.
  2726. ///
  2727. /// \param Call The call expression to diagnose.
  2728. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  2729. unsigned BId,
  2730. IdentifierInfo *FnName) {
  2731. assert(BId != 0);
  2732. // It is possible to have a non-standard definition of memset. Validate
  2733. // we have enough arguments, and if not, abort further checking.
  2734. unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
  2735. if (Call->getNumArgs() < ExpectedNumArgs)
  2736. return;
  2737. unsigned LastArg = (BId == Builtin::BImemset ||
  2738. BId == Builtin::BIstrndup ? 1 : 2);
  2739. unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
  2740. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  2741. // We have special checking when the length is a sizeof expression.
  2742. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  2743. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  2744. llvm::FoldingSetNodeID SizeOfArgID;
  2745. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  2746. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  2747. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  2748. QualType DestTy = Dest->getType();
  2749. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  2750. QualType PointeeTy = DestPtrTy->getPointeeType();
  2751. // Never warn about void type pointers. This can be used to suppress
  2752. // false positives.
  2753. if (PointeeTy->isVoidType())
  2754. continue;
  2755. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  2756. // actually comparing the expressions for equality. Because computing the
  2757. // expression IDs can be expensive, we only do this if the diagnostic is
  2758. // enabled.
  2759. if (SizeOfArg &&
  2760. Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
  2761. SizeOfArg->getExprLoc())) {
  2762. // We only compute IDs for expressions if the warning is enabled, and
  2763. // cache the sizeof arg's ID.
  2764. if (SizeOfArgID == llvm::FoldingSetNodeID())
  2765. SizeOfArg->Profile(SizeOfArgID, Context, true);
  2766. llvm::FoldingSetNodeID DestID;
  2767. Dest->Profile(DestID, Context, true);
  2768. if (DestID == SizeOfArgID) {
  2769. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  2770. // over sizeof(src) as well.
  2771. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  2772. StringRef ReadableName = FnName->getName();
  2773. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  2774. if (UnaryOp->getOpcode() == UO_AddrOf)
  2775. ActionIdx = 1; // If its an address-of operator, just remove it.
  2776. if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
  2777. ActionIdx = 2; // If the pointee's size is sizeof(char),
  2778. // suggest an explicit length.
  2779. // If the function is defined as a builtin macro, do not show macro
  2780. // expansion.
  2781. SourceLocation SL = SizeOfArg->getExprLoc();
  2782. SourceRange DSR = Dest->getSourceRange();
  2783. SourceRange SSR = SizeOfArg->getSourceRange();
  2784. SourceManager &SM = PP.getSourceManager();
  2785. if (SM.isMacroArgExpansion(SL)) {
  2786. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  2787. SL = SM.getSpellingLoc(SL);
  2788. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  2789. SM.getSpellingLoc(DSR.getEnd()));
  2790. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  2791. SM.getSpellingLoc(SSR.getEnd()));
  2792. }
  2793. DiagRuntimeBehavior(SL, SizeOfArg,
  2794. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  2795. << ReadableName
  2796. << PointeeTy
  2797. << DestTy
  2798. << DSR
  2799. << SSR);
  2800. DiagRuntimeBehavior(SL, SizeOfArg,
  2801. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  2802. << ActionIdx
  2803. << SSR);
  2804. break;
  2805. }
  2806. }
  2807. // Also check for cases where the sizeof argument is the exact same
  2808. // type as the memory argument, and where it points to a user-defined
  2809. // record type.
  2810. if (SizeOfArgTy != QualType()) {
  2811. if (PointeeTy->isRecordType() &&
  2812. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  2813. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  2814. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  2815. << FnName << SizeOfArgTy << ArgIdx
  2816. << PointeeTy << Dest->getSourceRange()
  2817. << LenExpr->getSourceRange());
  2818. break;
  2819. }
  2820. }
  2821. // Always complain about dynamic classes.
  2822. if (isDynamicClassType(PointeeTy)) {
  2823. unsigned OperationType = 0;
  2824. // "overwritten" if we're warning about the destination for any call
  2825. // but memcmp; otherwise a verb appropriate to the call.
  2826. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  2827. if (BId == Builtin::BImemcpy)
  2828. OperationType = 1;
  2829. else if(BId == Builtin::BImemmove)
  2830. OperationType = 2;
  2831. else if (BId == Builtin::BImemcmp)
  2832. OperationType = 3;
  2833. }
  2834. DiagRuntimeBehavior(
  2835. Dest->getExprLoc(), Dest,
  2836. PDiag(diag::warn_dyn_class_memaccess)
  2837. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  2838. << FnName << PointeeTy
  2839. << OperationType
  2840. << Call->getCallee()->getSourceRange());
  2841. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  2842. BId != Builtin::BImemset)
  2843. DiagRuntimeBehavior(
  2844. Dest->getExprLoc(), Dest,
  2845. PDiag(diag::warn_arc_object_memaccess)
  2846. << ArgIdx << FnName << PointeeTy
  2847. << Call->getCallee()->getSourceRange());
  2848. else
  2849. continue;
  2850. DiagRuntimeBehavior(
  2851. Dest->getExprLoc(), Dest,
  2852. PDiag(diag::note_bad_memaccess_silence)
  2853. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  2854. break;
  2855. }
  2856. }
  2857. }
  2858. // A little helper routine: ignore addition and subtraction of integer literals.
  2859. // This intentionally does not ignore all integer constant expressions because
  2860. // we don't want to remove sizeof().
  2861. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  2862. Ex = Ex->IgnoreParenCasts();
  2863. for (;;) {
  2864. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  2865. if (!BO || !BO->isAdditiveOp())
  2866. break;
  2867. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  2868. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  2869. if (isa<IntegerLiteral>(RHS))
  2870. Ex = LHS;
  2871. else if (isa<IntegerLiteral>(LHS))
  2872. Ex = RHS;
  2873. else
  2874. break;
  2875. }
  2876. return Ex;
  2877. }
  2878. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  2879. ASTContext &Context) {
  2880. // Only handle constant-sized or VLAs, but not flexible members.
  2881. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  2882. // Only issue the FIXIT for arrays of size > 1.
  2883. if (CAT->getSize().getSExtValue() <= 1)
  2884. return false;
  2885. } else if (!Ty->isVariableArrayType()) {
  2886. return false;
  2887. }
  2888. return true;
  2889. }
  2890. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  2891. // be the size of the source, instead of the destination.
  2892. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  2893. IdentifierInfo *FnName) {
  2894. // Don't crash if the user has the wrong number of arguments
  2895. if (Call->getNumArgs() != 3)
  2896. return;
  2897. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  2898. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  2899. const Expr *CompareWithSrc = NULL;
  2900. // Look for 'strlcpy(dst, x, sizeof(x))'
  2901. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  2902. CompareWithSrc = Ex;
  2903. else {
  2904. // Look for 'strlcpy(dst, x, strlen(x))'
  2905. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  2906. if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
  2907. && SizeCall->getNumArgs() == 1)
  2908. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  2909. }
  2910. }
  2911. if (!CompareWithSrc)
  2912. return;
  2913. // Determine if the argument to sizeof/strlen is equal to the source
  2914. // argument. In principle there's all kinds of things you could do
  2915. // here, for instance creating an == expression and evaluating it with
  2916. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  2917. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  2918. if (!SrcArgDRE)
  2919. return;
  2920. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  2921. if (!CompareWithSrcDRE ||
  2922. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  2923. return;
  2924. const Expr *OriginalSizeArg = Call->getArg(2);
  2925. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  2926. << OriginalSizeArg->getSourceRange() << FnName;
  2927. // Output a FIXIT hint if the destination is an array (rather than a
  2928. // pointer to an array). This could be enhanced to handle some
  2929. // pointers if we know the actual size, like if DstArg is 'array+2'
  2930. // we could say 'sizeof(array)-2'.
  2931. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  2932. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  2933. return;
  2934. SmallString<128> sizeString;
  2935. llvm::raw_svector_ostream OS(sizeString);
  2936. OS << "sizeof(";
  2937. DstArg->printPretty(OS, 0, getPrintingPolicy());
  2938. OS << ")";
  2939. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  2940. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  2941. OS.str());
  2942. }
  2943. /// Check if two expressions refer to the same declaration.
  2944. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  2945. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  2946. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  2947. return D1->getDecl() == D2->getDecl();
  2948. return false;
  2949. }
  2950. static const Expr *getStrlenExprArg(const Expr *E) {
  2951. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  2952. const FunctionDecl *FD = CE->getDirectCallee();
  2953. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  2954. return 0;
  2955. return CE->getArg(0)->IgnoreParenCasts();
  2956. }
  2957. return 0;
  2958. }
  2959. // Warn on anti-patterns as the 'size' argument to strncat.
  2960. // The correct size argument should look like following:
  2961. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  2962. void Sema::CheckStrncatArguments(const CallExpr *CE,
  2963. IdentifierInfo *FnName) {
  2964. // Don't crash if the user has the wrong number of arguments.
  2965. if (CE->getNumArgs() < 3)
  2966. return;
  2967. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  2968. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  2969. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  2970. // Identify common expressions, which are wrongly used as the size argument
  2971. // to strncat and may lead to buffer overflows.
  2972. unsigned PatternType = 0;
  2973. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  2974. // - sizeof(dst)
  2975. if (referToTheSameDecl(SizeOfArg, DstArg))
  2976. PatternType = 1;
  2977. // - sizeof(src)
  2978. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  2979. PatternType = 2;
  2980. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  2981. if (BE->getOpcode() == BO_Sub) {
  2982. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  2983. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  2984. // - sizeof(dst) - strlen(dst)
  2985. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  2986. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  2987. PatternType = 1;
  2988. // - sizeof(src) - (anything)
  2989. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  2990. PatternType = 2;
  2991. }
  2992. }
  2993. if (PatternType == 0)
  2994. return;
  2995. // Generate the diagnostic.
  2996. SourceLocation SL = LenArg->getLocStart();
  2997. SourceRange SR = LenArg->getSourceRange();
  2998. SourceManager &SM = PP.getSourceManager();
  2999. // If the function is defined as a builtin macro, do not show macro expansion.
  3000. if (SM.isMacroArgExpansion(SL)) {
  3001. SL = SM.getSpellingLoc(SL);
  3002. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  3003. SM.getSpellingLoc(SR.getEnd()));
  3004. }
  3005. // Check if the destination is an array (rather than a pointer to an array).
  3006. QualType DstTy = DstArg->getType();
  3007. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  3008. Context);
  3009. if (!isKnownSizeArray) {
  3010. if (PatternType == 1)
  3011. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  3012. else
  3013. Diag(SL, diag::warn_strncat_src_size) << SR;
  3014. return;
  3015. }
  3016. if (PatternType == 1)
  3017. Diag(SL, diag::warn_strncat_large_size) << SR;
  3018. else
  3019. Diag(SL, diag::warn_strncat_src_size) << SR;
  3020. SmallString<128> sizeString;
  3021. llvm::raw_svector_ostream OS(sizeString);
  3022. OS << "sizeof(";
  3023. DstArg->printPretty(OS, 0, getPrintingPolicy());
  3024. OS << ") - ";
  3025. OS << "strlen(";
  3026. DstArg->printPretty(OS, 0, getPrintingPolicy());
  3027. OS << ") - 1";
  3028. Diag(SL, diag::note_strncat_wrong_size)
  3029. << FixItHint::CreateReplacement(SR, OS.str());
  3030. }
  3031. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  3032. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3033. Decl *ParentDecl);
  3034. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3035. Decl *ParentDecl);
  3036. /// CheckReturnStackAddr - Check if a return statement returns the address
  3037. /// of a stack variable.
  3038. void
  3039. Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
  3040. SourceLocation ReturnLoc) {
  3041. Expr *stackE = 0;
  3042. SmallVector<DeclRefExpr *, 8> refVars;
  3043. // Perform checking for returned stack addresses, local blocks,
  3044. // label addresses or references to temporaries.
  3045. if (lhsType->isPointerType() ||
  3046. (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  3047. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
  3048. } else if (lhsType->isReferenceType()) {
  3049. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
  3050. }
  3051. if (stackE == 0)
  3052. return; // Nothing suspicious was found.
  3053. SourceLocation diagLoc;
  3054. SourceRange diagRange;
  3055. if (refVars.empty()) {
  3056. diagLoc = stackE->getLocStart();
  3057. diagRange = stackE->getSourceRange();
  3058. } else {
  3059. // We followed through a reference variable. 'stackE' contains the
  3060. // problematic expression but we will warn at the return statement pointing
  3061. // at the reference variable. We will later display the "trail" of
  3062. // reference variables using notes.
  3063. diagLoc = refVars[0]->getLocStart();
  3064. diagRange = refVars[0]->getSourceRange();
  3065. }
  3066. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  3067. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  3068. : diag::warn_ret_stack_addr)
  3069. << DR->getDecl()->getDeclName() << diagRange;
  3070. } else if (isa<BlockExpr>(stackE)) { // local block.
  3071. Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  3072. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  3073. Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  3074. } else { // local temporary.
  3075. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  3076. : diag::warn_ret_local_temp_addr)
  3077. << diagRange;
  3078. }
  3079. // Display the "trail" of reference variables that we followed until we
  3080. // found the problematic expression using notes.
  3081. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  3082. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  3083. // If this var binds to another reference var, show the range of the next
  3084. // var, otherwise the var binds to the problematic expression, in which case
  3085. // show the range of the expression.
  3086. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  3087. : stackE->getSourceRange();
  3088. Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  3089. << VD->getDeclName() << range;
  3090. }
  3091. }
  3092. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  3093. /// check if the expression in a return statement evaluates to an address
  3094. /// to a location on the stack, a local block, an address of a label, or a
  3095. /// reference to local temporary. The recursion is used to traverse the
  3096. /// AST of the return expression, with recursion backtracking when we
  3097. /// encounter a subexpression that (1) clearly does not lead to one of the
  3098. /// above problematic expressions (2) is something we cannot determine leads to
  3099. /// a problematic expression based on such local checking.
  3100. ///
  3101. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  3102. /// the expression that they point to. Such variables are added to the
  3103. /// 'refVars' vector so that we know what the reference variable "trail" was.
  3104. ///
  3105. /// EvalAddr processes expressions that are pointers that are used as
  3106. /// references (and not L-values). EvalVal handles all other values.
  3107. /// At the base case of the recursion is a check for the above problematic
  3108. /// expressions.
  3109. ///
  3110. /// This implementation handles:
  3111. ///
  3112. /// * pointer-to-pointer casts
  3113. /// * implicit conversions from array references to pointers
  3114. /// * taking the address of fields
  3115. /// * arbitrary interplay between "&" and "*" operators
  3116. /// * pointer arithmetic from an address of a stack variable
  3117. /// * taking the address of an array element where the array is on the stack
  3118. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3119. Decl *ParentDecl) {
  3120. if (E->isTypeDependent())
  3121. return NULL;
  3122. // We should only be called for evaluating pointer expressions.
  3123. assert((E->getType()->isAnyPointerType() ||
  3124. E->getType()->isBlockPointerType() ||
  3125. E->getType()->isObjCQualifiedIdType()) &&
  3126. "EvalAddr only works on pointers");
  3127. E = E->IgnoreParens();
  3128. // Our "symbolic interpreter" is just a dispatch off the currently
  3129. // viewed AST node. We then recursively traverse the AST by calling
  3130. // EvalAddr and EvalVal appropriately.
  3131. switch (E->getStmtClass()) {
  3132. case Stmt::DeclRefExprClass: {
  3133. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  3134. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  3135. // If this is a reference variable, follow through to the expression that
  3136. // it points to.
  3137. if (V->hasLocalStorage() &&
  3138. V->getType()->isReferenceType() && V->hasInit()) {
  3139. // Add the reference variable to the "trail".
  3140. refVars.push_back(DR);
  3141. return EvalAddr(V->getInit(), refVars, ParentDecl);
  3142. }
  3143. return NULL;
  3144. }
  3145. case Stmt::UnaryOperatorClass: {
  3146. // The only unary operator that make sense to handle here
  3147. // is AddrOf. All others don't make sense as pointers.
  3148. UnaryOperator *U = cast<UnaryOperator>(E);
  3149. if (U->getOpcode() == UO_AddrOf)
  3150. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  3151. else
  3152. return NULL;
  3153. }
  3154. case Stmt::BinaryOperatorClass: {
  3155. // Handle pointer arithmetic. All other binary operators are not valid
  3156. // in this context.
  3157. BinaryOperator *B = cast<BinaryOperator>(E);
  3158. BinaryOperatorKind op = B->getOpcode();
  3159. if (op != BO_Add && op != BO_Sub)
  3160. return NULL;
  3161. Expr *Base = B->getLHS();
  3162. // Determine which argument is the real pointer base. It could be
  3163. // the RHS argument instead of the LHS.
  3164. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  3165. assert (Base->getType()->isPointerType());
  3166. return EvalAddr(Base, refVars, ParentDecl);
  3167. }
  3168. // For conditional operators we need to see if either the LHS or RHS are
  3169. // valid DeclRefExpr*s. If one of them is valid, we return it.
  3170. case Stmt::ConditionalOperatorClass: {
  3171. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3172. // Handle the GNU extension for missing LHS.
  3173. if (Expr *lhsExpr = C->getLHS()) {
  3174. // In C++, we can have a throw-expression, which has 'void' type.
  3175. if (!lhsExpr->getType()->isVoidType())
  3176. if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
  3177. return LHS;
  3178. }
  3179. // In C++, we can have a throw-expression, which has 'void' type.
  3180. if (C->getRHS()->getType()->isVoidType())
  3181. return NULL;
  3182. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  3183. }
  3184. case Stmt::BlockExprClass:
  3185. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  3186. return E; // local block.
  3187. return NULL;
  3188. case Stmt::AddrLabelExprClass:
  3189. return E; // address of label.
  3190. case Stmt::ExprWithCleanupsClass:
  3191. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  3192. ParentDecl);
  3193. // For casts, we need to handle conversions from arrays to
  3194. // pointer values, and pointer-to-pointer conversions.
  3195. case Stmt::ImplicitCastExprClass:
  3196. case Stmt::CStyleCastExprClass:
  3197. case Stmt::CXXFunctionalCastExprClass:
  3198. case Stmt::ObjCBridgedCastExprClass:
  3199. case Stmt::CXXStaticCastExprClass:
  3200. case Stmt::CXXDynamicCastExprClass:
  3201. case Stmt::CXXConstCastExprClass:
  3202. case Stmt::CXXReinterpretCastExprClass: {
  3203. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  3204. switch (cast<CastExpr>(E)->getCastKind()) {
  3205. case CK_BitCast:
  3206. case CK_LValueToRValue:
  3207. case CK_NoOp:
  3208. case CK_BaseToDerived:
  3209. case CK_DerivedToBase:
  3210. case CK_UncheckedDerivedToBase:
  3211. case CK_Dynamic:
  3212. case CK_CPointerToObjCPointerCast:
  3213. case CK_BlockPointerToObjCPointerCast:
  3214. case CK_AnyPointerToBlockPointerCast:
  3215. return EvalAddr(SubExpr, refVars, ParentDecl);
  3216. case CK_ArrayToPointerDecay:
  3217. return EvalVal(SubExpr, refVars, ParentDecl);
  3218. default:
  3219. return 0;
  3220. }
  3221. }
  3222. case Stmt::MaterializeTemporaryExprClass:
  3223. if (Expr *Result = EvalAddr(
  3224. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  3225. refVars, ParentDecl))
  3226. return Result;
  3227. return E;
  3228. // Everything else: we simply don't reason about them.
  3229. default:
  3230. return NULL;
  3231. }
  3232. }
  3233. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  3234. /// See the comments for EvalAddr for more details.
  3235. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3236. Decl *ParentDecl) {
  3237. do {
  3238. // We should only be called for evaluating non-pointer expressions, or
  3239. // expressions with a pointer type that are not used as references but instead
  3240. // are l-values (e.g., DeclRefExpr with a pointer type).
  3241. // Our "symbolic interpreter" is just a dispatch off the currently
  3242. // viewed AST node. We then recursively traverse the AST by calling
  3243. // EvalAddr and EvalVal appropriately.
  3244. E = E->IgnoreParens();
  3245. switch (E->getStmtClass()) {
  3246. case Stmt::ImplicitCastExprClass: {
  3247. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  3248. if (IE->getValueKind() == VK_LValue) {
  3249. E = IE->getSubExpr();
  3250. continue;
  3251. }
  3252. return NULL;
  3253. }
  3254. case Stmt::ExprWithCleanupsClass:
  3255. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
  3256. case Stmt::DeclRefExprClass: {
  3257. // When we hit a DeclRefExpr we are looking at code that refers to a
  3258. // variable's name. If it's not a reference variable we check if it has
  3259. // local storage within the function, and if so, return the expression.
  3260. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  3261. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  3262. // Check if it refers to itself, e.g. "int& i = i;".
  3263. if (V == ParentDecl)
  3264. return DR;
  3265. if (V->hasLocalStorage()) {
  3266. if (!V->getType()->isReferenceType())
  3267. return DR;
  3268. // Reference variable, follow through to the expression that
  3269. // it points to.
  3270. if (V->hasInit()) {
  3271. // Add the reference variable to the "trail".
  3272. refVars.push_back(DR);
  3273. return EvalVal(V->getInit(), refVars, V);
  3274. }
  3275. }
  3276. }
  3277. return NULL;
  3278. }
  3279. case Stmt::UnaryOperatorClass: {
  3280. // The only unary operator that make sense to handle here
  3281. // is Deref. All others don't resolve to a "name." This includes
  3282. // handling all sorts of rvalues passed to a unary operator.
  3283. UnaryOperator *U = cast<UnaryOperator>(E);
  3284. if (U->getOpcode() == UO_Deref)
  3285. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  3286. return NULL;
  3287. }
  3288. case Stmt::ArraySubscriptExprClass: {
  3289. // Array subscripts are potential references to data on the stack. We
  3290. // retrieve the DeclRefExpr* for the array variable if it indeed
  3291. // has local storage.
  3292. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
  3293. }
  3294. case Stmt::ConditionalOperatorClass: {
  3295. // For conditional operators we need to see if either the LHS or RHS are
  3296. // non-NULL Expr's. If one is non-NULL, we return it.
  3297. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3298. // Handle the GNU extension for missing LHS.
  3299. if (Expr *lhsExpr = C->getLHS())
  3300. if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
  3301. return LHS;
  3302. return EvalVal(C->getRHS(), refVars, ParentDecl);
  3303. }
  3304. // Accesses to members are potential references to data on the stack.
  3305. case Stmt::MemberExprClass: {
  3306. MemberExpr *M = cast<MemberExpr>(E);
  3307. // Check for indirect access. We only want direct field accesses.
  3308. if (M->isArrow())
  3309. return NULL;
  3310. // Check whether the member type is itself a reference, in which case
  3311. // we're not going to refer to the member, but to what the member refers to.
  3312. if (M->getMemberDecl()->getType()->isReferenceType())
  3313. return NULL;
  3314. return EvalVal(M->getBase(), refVars, ParentDecl);
  3315. }
  3316. case Stmt::MaterializeTemporaryExprClass:
  3317. if (Expr *Result = EvalVal(
  3318. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  3319. refVars, ParentDecl))
  3320. return Result;
  3321. return E;
  3322. default:
  3323. // Check that we don't return or take the address of a reference to a
  3324. // temporary. This is only useful in C++.
  3325. if (!E->isTypeDependent() && E->isRValue())
  3326. return E;
  3327. // Everything else: we simply don't reason about them.
  3328. return NULL;
  3329. }
  3330. } while (true);
  3331. }
  3332. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  3333. /// Check for comparisons of floating point operands using != and ==.
  3334. /// Issue a warning if these are no self-comparisons, as they are not likely
  3335. /// to do what the programmer intended.
  3336. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  3337. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  3338. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  3339. // Special case: check for x == x (which is OK).
  3340. // Do not emit warnings for such cases.
  3341. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  3342. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  3343. if (DRL->getDecl() == DRR->getDecl())
  3344. return;
  3345. // Special case: check for comparisons against literals that can be exactly
  3346. // represented by APFloat. In such cases, do not emit a warning. This
  3347. // is a heuristic: often comparison against such literals are used to
  3348. // detect if a value in a variable has not changed. This clearly can
  3349. // lead to false negatives.
  3350. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  3351. if (FLL->isExact())
  3352. return;
  3353. } else
  3354. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  3355. if (FLR->isExact())
  3356. return;
  3357. // Check for comparisons with builtin types.
  3358. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  3359. if (CL->isBuiltinCall())
  3360. return;
  3361. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  3362. if (CR->isBuiltinCall())
  3363. return;
  3364. // Emit the diagnostic.
  3365. Diag(Loc, diag::warn_floatingpoint_eq)
  3366. << LHS->getSourceRange() << RHS->getSourceRange();
  3367. }
  3368. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  3369. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  3370. namespace {
  3371. /// Structure recording the 'active' range of an integer-valued
  3372. /// expression.
  3373. struct IntRange {
  3374. /// The number of bits active in the int.
  3375. unsigned Width;
  3376. /// True if the int is known not to have negative values.
  3377. bool NonNegative;
  3378. IntRange(unsigned Width, bool NonNegative)
  3379. : Width(Width), NonNegative(NonNegative)
  3380. {}
  3381. /// Returns the range of the bool type.
  3382. static IntRange forBoolType() {
  3383. return IntRange(1, true);
  3384. }
  3385. /// Returns the range of an opaque value of the given integral type.
  3386. static IntRange forValueOfType(ASTContext &C, QualType T) {
  3387. return forValueOfCanonicalType(C,
  3388. T->getCanonicalTypeInternal().getTypePtr());
  3389. }
  3390. /// Returns the range of an opaque value of a canonical integral type.
  3391. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  3392. assert(T->isCanonicalUnqualified());
  3393. if (const VectorType *VT = dyn_cast<VectorType>(T))
  3394. T = VT->getElementType().getTypePtr();
  3395. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  3396. T = CT->getElementType().getTypePtr();
  3397. // For enum types, use the known bit width of the enumerators.
  3398. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  3399. EnumDecl *Enum = ET->getDecl();
  3400. if (!Enum->isCompleteDefinition())
  3401. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  3402. unsigned NumPositive = Enum->getNumPositiveBits();
  3403. unsigned NumNegative = Enum->getNumNegativeBits();
  3404. return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
  3405. }
  3406. const BuiltinType *BT = cast<BuiltinType>(T);
  3407. assert(BT->isInteger());
  3408. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  3409. }
  3410. /// Returns the "target" range of a canonical integral type, i.e.
  3411. /// the range of values expressible in the type.
  3412. ///
  3413. /// This matches forValueOfCanonicalType except that enums have the
  3414. /// full range of their type, not the range of their enumerators.
  3415. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  3416. assert(T->isCanonicalUnqualified());
  3417. if (const VectorType *VT = dyn_cast<VectorType>(T))
  3418. T = VT->getElementType().getTypePtr();
  3419. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  3420. T = CT->getElementType().getTypePtr();
  3421. if (const EnumType *ET = dyn_cast<EnumType>(T))
  3422. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  3423. const BuiltinType *BT = cast<BuiltinType>(T);
  3424. assert(BT->isInteger());
  3425. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  3426. }
  3427. /// Returns the supremum of two ranges: i.e. their conservative merge.
  3428. static IntRange join(IntRange L, IntRange R) {
  3429. return IntRange(std::max(L.Width, R.Width),
  3430. L.NonNegative && R.NonNegative);
  3431. }
  3432. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  3433. static IntRange meet(IntRange L, IntRange R) {
  3434. return IntRange(std::min(L.Width, R.Width),
  3435. L.NonNegative || R.NonNegative);
  3436. }
  3437. };
  3438. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  3439. unsigned MaxWidth) {
  3440. if (value.isSigned() && value.isNegative())
  3441. return IntRange(value.getMinSignedBits(), false);
  3442. if (value.getBitWidth() > MaxWidth)
  3443. value = value.trunc(MaxWidth);
  3444. // isNonNegative() just checks the sign bit without considering
  3445. // signedness.
  3446. return IntRange(value.getActiveBits(), true);
  3447. }
  3448. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  3449. unsigned MaxWidth) {
  3450. if (result.isInt())
  3451. return GetValueRange(C, result.getInt(), MaxWidth);
  3452. if (result.isVector()) {
  3453. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  3454. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  3455. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  3456. R = IntRange::join(R, El);
  3457. }
  3458. return R;
  3459. }
  3460. if (result.isComplexInt()) {
  3461. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  3462. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  3463. return IntRange::join(R, I);
  3464. }
  3465. // This can happen with lossless casts to intptr_t of "based" lvalues.
  3466. // Assume it might use arbitrary bits.
  3467. // FIXME: The only reason we need to pass the type in here is to get
  3468. // the sign right on this one case. It would be nice if APValue
  3469. // preserved this.
  3470. assert(result.isLValue() || result.isAddrLabelDiff());
  3471. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  3472. }
  3473. /// Pseudo-evaluate the given integer expression, estimating the
  3474. /// range of values it might take.
  3475. ///
  3476. /// \param MaxWidth - the width to which the value will be truncated
  3477. static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  3478. E = E->IgnoreParens();
  3479. // Try a full evaluation first.
  3480. Expr::EvalResult result;
  3481. if (E->EvaluateAsRValue(result, C))
  3482. return GetValueRange(C, result.Val, E->getType(), MaxWidth);
  3483. // I think we only want to look through implicit casts here; if the
  3484. // user has an explicit widening cast, we should treat the value as
  3485. // being of the new, wider type.
  3486. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  3487. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  3488. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  3489. IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
  3490. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  3491. // Assume that non-integer casts can span the full range of the type.
  3492. if (!isIntegerCast)
  3493. return OutputTypeRange;
  3494. IntRange SubRange
  3495. = GetExprRange(C, CE->getSubExpr(),
  3496. std::min(MaxWidth, OutputTypeRange.Width));
  3497. // Bail out if the subexpr's range is as wide as the cast type.
  3498. if (SubRange.Width >= OutputTypeRange.Width)
  3499. return OutputTypeRange;
  3500. // Otherwise, we take the smaller width, and we're non-negative if
  3501. // either the output type or the subexpr is.
  3502. return IntRange(SubRange.Width,
  3503. SubRange.NonNegative || OutputTypeRange.NonNegative);
  3504. }
  3505. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3506. // If we can fold the condition, just take that operand.
  3507. bool CondResult;
  3508. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  3509. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  3510. : CO->getFalseExpr(),
  3511. MaxWidth);
  3512. // Otherwise, conservatively merge.
  3513. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  3514. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  3515. return IntRange::join(L, R);
  3516. }
  3517. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3518. switch (BO->getOpcode()) {
  3519. // Boolean-valued operations are single-bit and positive.
  3520. case BO_LAnd:
  3521. case BO_LOr:
  3522. case BO_LT:
  3523. case BO_GT:
  3524. case BO_LE:
  3525. case BO_GE:
  3526. case BO_EQ:
  3527. case BO_NE:
  3528. return IntRange::forBoolType();
  3529. // The type of the assignments is the type of the LHS, so the RHS
  3530. // is not necessarily the same type.
  3531. case BO_MulAssign:
  3532. case BO_DivAssign:
  3533. case BO_RemAssign:
  3534. case BO_AddAssign:
  3535. case BO_SubAssign:
  3536. case BO_XorAssign:
  3537. case BO_OrAssign:
  3538. // TODO: bitfields?
  3539. return IntRange::forValueOfType(C, E->getType());
  3540. // Simple assignments just pass through the RHS, which will have
  3541. // been coerced to the LHS type.
  3542. case BO_Assign:
  3543. // TODO: bitfields?
  3544. return GetExprRange(C, BO->getRHS(), MaxWidth);
  3545. // Operations with opaque sources are black-listed.
  3546. case BO_PtrMemD:
  3547. case BO_PtrMemI:
  3548. return IntRange::forValueOfType(C, E->getType());
  3549. // Bitwise-and uses the *infinum* of the two source ranges.
  3550. case BO_And:
  3551. case BO_AndAssign:
  3552. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  3553. GetExprRange(C, BO->getRHS(), MaxWidth));
  3554. // Left shift gets black-listed based on a judgement call.
  3555. case BO_Shl:
  3556. // ...except that we want to treat '1 << (blah)' as logically
  3557. // positive. It's an important idiom.
  3558. if (IntegerLiteral *I
  3559. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  3560. if (I->getValue() == 1) {
  3561. IntRange R = IntRange::forValueOfType(C, E->getType());
  3562. return IntRange(R.Width, /*NonNegative*/ true);
  3563. }
  3564. }
  3565. // fallthrough
  3566. case BO_ShlAssign:
  3567. return IntRange::forValueOfType(C, E->getType());
  3568. // Right shift by a constant can narrow its left argument.
  3569. case BO_Shr:
  3570. case BO_ShrAssign: {
  3571. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  3572. // If the shift amount is a positive constant, drop the width by
  3573. // that much.
  3574. llvm::APSInt shift;
  3575. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  3576. shift.isNonNegative()) {
  3577. unsigned zext = shift.getZExtValue();
  3578. if (zext >= L.Width)
  3579. L.Width = (L.NonNegative ? 0 : 1);
  3580. else
  3581. L.Width -= zext;
  3582. }
  3583. return L;
  3584. }
  3585. // Comma acts as its right operand.
  3586. case BO_Comma:
  3587. return GetExprRange(C, BO->getRHS(), MaxWidth);
  3588. // Black-list pointer subtractions.
  3589. case BO_Sub:
  3590. if (BO->getLHS()->getType()->isPointerType())
  3591. return IntRange::forValueOfType(C, E->getType());
  3592. break;
  3593. // The width of a division result is mostly determined by the size
  3594. // of the LHS.
  3595. case BO_Div: {
  3596. // Don't 'pre-truncate' the operands.
  3597. unsigned opWidth = C.getIntWidth(E->getType());
  3598. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  3599. // If the divisor is constant, use that.
  3600. llvm::APSInt divisor;
  3601. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  3602. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  3603. if (log2 >= L.Width)
  3604. L.Width = (L.NonNegative ? 0 : 1);
  3605. else
  3606. L.Width = std::min(L.Width - log2, MaxWidth);
  3607. return L;
  3608. }
  3609. // Otherwise, just use the LHS's width.
  3610. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  3611. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  3612. }
  3613. // The result of a remainder can't be larger than the result of
  3614. // either side.
  3615. case BO_Rem: {
  3616. // Don't 'pre-truncate' the operands.
  3617. unsigned opWidth = C.getIntWidth(E->getType());
  3618. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  3619. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  3620. IntRange meet = IntRange::meet(L, R);
  3621. meet.Width = std::min(meet.Width, MaxWidth);
  3622. return meet;
  3623. }
  3624. // The default behavior is okay for these.
  3625. case BO_Mul:
  3626. case BO_Add:
  3627. case BO_Xor:
  3628. case BO_Or:
  3629. break;
  3630. }
  3631. // The default case is to treat the operation as if it were closed
  3632. // on the narrowest type that encompasses both operands.
  3633. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  3634. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  3635. return IntRange::join(L, R);
  3636. }
  3637. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  3638. switch (UO->getOpcode()) {
  3639. // Boolean-valued operations are white-listed.
  3640. case UO_LNot:
  3641. return IntRange::forBoolType();
  3642. // Operations with opaque sources are black-listed.
  3643. case UO_Deref:
  3644. case UO_AddrOf: // should be impossible
  3645. return IntRange::forValueOfType(C, E->getType());
  3646. default:
  3647. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  3648. }
  3649. }
  3650. if (dyn_cast<OffsetOfExpr>(E)) {
  3651. IntRange::forValueOfType(C, E->getType());
  3652. }
  3653. if (FieldDecl *BitField = E->getBitField())
  3654. return IntRange(BitField->getBitWidthValue(C),
  3655. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  3656. return IntRange::forValueOfType(C, E->getType());
  3657. }
  3658. static IntRange GetExprRange(ASTContext &C, Expr *E) {
  3659. return GetExprRange(C, E, C.getIntWidth(E->getType()));
  3660. }
  3661. /// Checks whether the given value, which currently has the given
  3662. /// source semantics, has the same value when coerced through the
  3663. /// target semantics.
  3664. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  3665. const llvm::fltSemantics &Src,
  3666. const llvm::fltSemantics &Tgt) {
  3667. llvm::APFloat truncated = value;
  3668. bool ignored;
  3669. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  3670. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  3671. return truncated.bitwiseIsEqual(value);
  3672. }
  3673. /// Checks whether the given value, which currently has the given
  3674. /// source semantics, has the same value when coerced through the
  3675. /// target semantics.
  3676. ///
  3677. /// The value might be a vector of floats (or a complex number).
  3678. static bool IsSameFloatAfterCast(const APValue &value,
  3679. const llvm::fltSemantics &Src,
  3680. const llvm::fltSemantics &Tgt) {
  3681. if (value.isFloat())
  3682. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  3683. if (value.isVector()) {
  3684. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  3685. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  3686. return false;
  3687. return true;
  3688. }
  3689. assert(value.isComplexFloat());
  3690. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  3691. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  3692. }
  3693. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  3694. static bool IsZero(Sema &S, Expr *E) {
  3695. // Suppress cases where we are comparing against an enum constant.
  3696. if (const DeclRefExpr *DR =
  3697. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  3698. if (isa<EnumConstantDecl>(DR->getDecl()))
  3699. return false;
  3700. // Suppress cases where the '0' value is expanded from a macro.
  3701. if (E->getLocStart().isMacroID())
  3702. return false;
  3703. llvm::APSInt Value;
  3704. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  3705. }
  3706. static bool HasEnumType(Expr *E) {
  3707. // Strip off implicit integral promotions.
  3708. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3709. if (ICE->getCastKind() != CK_IntegralCast &&
  3710. ICE->getCastKind() != CK_NoOp)
  3711. break;
  3712. E = ICE->getSubExpr();
  3713. }
  3714. return E->getType()->isEnumeralType();
  3715. }
  3716. static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  3717. BinaryOperatorKind op = E->getOpcode();
  3718. if (E->isValueDependent())
  3719. return;
  3720. if (op == BO_LT && IsZero(S, E->getRHS())) {
  3721. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3722. << "< 0" << "false" << HasEnumType(E->getLHS())
  3723. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3724. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  3725. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3726. << ">= 0" << "true" << HasEnumType(E->getLHS())
  3727. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3728. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  3729. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3730. << "0 >" << "false" << HasEnumType(E->getRHS())
  3731. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3732. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  3733. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3734. << "0 <=" << "true" << HasEnumType(E->getRHS())
  3735. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3736. }
  3737. }
  3738. static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
  3739. Expr *lit, Expr *other,
  3740. llvm::APSInt Value,
  3741. bool rhsLiteral) {
  3742. BinaryOperatorKind op = E->getOpcode();
  3743. QualType OtherT = other->getType();
  3744. const Type *OtherPtrT = S.Context.getCanonicalType(OtherT).getTypePtr();
  3745. const Type *LitPtrT = S.Context.getCanonicalType(lit->getType()).getTypePtr();
  3746. if (OtherPtrT == LitPtrT)
  3747. return;
  3748. assert((OtherT->isIntegerType() && LitPtrT->isIntegerType())
  3749. && "comparison with non-integer type");
  3750. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  3751. IntRange LitRange = GetExprRange(S.Context, lit);
  3752. if (OtherRange.Width >= LitRange.Width)
  3753. return;
  3754. std::string PrettySourceValue = Value.toString(10);
  3755. bool IsTrue = true;
  3756. if (op == BO_EQ)
  3757. IsTrue = false;
  3758. else if (op == BO_NE)
  3759. IsTrue = true;
  3760. else if (rhsLiteral) {
  3761. if (op == BO_GT || op == BO_GE)
  3762. IsTrue = !LitRange.NonNegative;
  3763. else // op == BO_LT || op == BO_LE
  3764. IsTrue = LitRange.NonNegative;
  3765. }
  3766. else {
  3767. if (op == BO_LT || op == BO_LE)
  3768. IsTrue = !LitRange.NonNegative;
  3769. else // op == BO_GT || op == BO_GE
  3770. IsTrue = LitRange.NonNegative;
  3771. }
  3772. S.Diag(E->getOperatorLoc(), diag::warn_outof_range_compare)
  3773. << PrettySourceValue << other->getType() << IsTrue
  3774. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3775. }
  3776. /// Analyze the operands of the given comparison. Implements the
  3777. /// fallback case from AnalyzeComparison.
  3778. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  3779. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3780. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3781. }
  3782. /// \brief Implements -Wsign-compare.
  3783. ///
  3784. /// \param E the binary operator to check for warnings
  3785. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  3786. // The type the comparison is being performed in.
  3787. QualType T = E->getLHS()->getType();
  3788. assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
  3789. && "comparison with mismatched types");
  3790. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  3791. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  3792. if (E->isValueDependent())
  3793. return AnalyzeImpConvsInComparison(S, E);
  3794. bool IsComparisonConstant = false;
  3795. // Check that an integer constant comparison results in a value
  3796. // of 'true' or 'false'.
  3797. if (T->isIntegralType(S.Context)) {
  3798. llvm::APSInt RHSValue;
  3799. bool IsRHSIntegralLiteral =
  3800. RHS->isIntegerConstantExpr(RHSValue, S.Context);
  3801. llvm::APSInt LHSValue;
  3802. bool IsLHSIntegralLiteral =
  3803. LHS->isIntegerConstantExpr(LHSValue, S.Context);
  3804. if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
  3805. DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
  3806. else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  3807. DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
  3808. else
  3809. IsComparisonConstant =
  3810. (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
  3811. }
  3812. else if (!T->hasUnsignedIntegerRepresentation())
  3813. IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
  3814. // We don't do anything special if this isn't an unsigned integral
  3815. // comparison: we're only interested in integral comparisons, and
  3816. // signed comparisons only happen in cases we don't care to warn about.
  3817. //
  3818. // We also don't care about value-dependent expressions or expressions
  3819. // whose result is a constant.
  3820. if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
  3821. return AnalyzeImpConvsInComparison(S, E);
  3822. // Check to see if one of the (unmodified) operands is of different
  3823. // signedness.
  3824. Expr *signedOperand, *unsignedOperand;
  3825. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  3826. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  3827. "unsigned comparison between two signed integer expressions?");
  3828. signedOperand = LHS;
  3829. unsignedOperand = RHS;
  3830. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  3831. signedOperand = RHS;
  3832. unsignedOperand = LHS;
  3833. } else {
  3834. CheckTrivialUnsignedComparison(S, E);
  3835. return AnalyzeImpConvsInComparison(S, E);
  3836. }
  3837. // Otherwise, calculate the effective range of the signed operand.
  3838. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  3839. // Go ahead and analyze implicit conversions in the operands. Note
  3840. // that we skip the implicit conversions on both sides.
  3841. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  3842. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  3843. // If the signed range is non-negative, -Wsign-compare won't fire,
  3844. // but we should still check for comparisons which are always true
  3845. // or false.
  3846. if (signedRange.NonNegative)
  3847. return CheckTrivialUnsignedComparison(S, E);
  3848. // For (in)equality comparisons, if the unsigned operand is a
  3849. // constant which cannot collide with a overflowed signed operand,
  3850. // then reinterpreting the signed operand as unsigned will not
  3851. // change the result of the comparison.
  3852. if (E->isEqualityOp()) {
  3853. unsigned comparisonWidth = S.Context.getIntWidth(T);
  3854. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  3855. // We should never be unable to prove that the unsigned operand is
  3856. // non-negative.
  3857. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  3858. if (unsignedRange.Width < comparisonWidth)
  3859. return;
  3860. }
  3861. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  3862. S.PDiag(diag::warn_mixed_sign_comparison)
  3863. << LHS->getType() << RHS->getType()
  3864. << LHS->getSourceRange() << RHS->getSourceRange());
  3865. }
  3866. /// Analyzes an attempt to assign the given value to a bitfield.
  3867. ///
  3868. /// Returns true if there was something fishy about the attempt.
  3869. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  3870. SourceLocation InitLoc) {
  3871. assert(Bitfield->isBitField());
  3872. if (Bitfield->isInvalidDecl())
  3873. return false;
  3874. // White-list bool bitfields.
  3875. if (Bitfield->getType()->isBooleanType())
  3876. return false;
  3877. // Ignore value- or type-dependent expressions.
  3878. if (Bitfield->getBitWidth()->isValueDependent() ||
  3879. Bitfield->getBitWidth()->isTypeDependent() ||
  3880. Init->isValueDependent() ||
  3881. Init->isTypeDependent())
  3882. return false;
  3883. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  3884. llvm::APSInt Value;
  3885. if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
  3886. return false;
  3887. unsigned OriginalWidth = Value.getBitWidth();
  3888. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  3889. if (OriginalWidth <= FieldWidth)
  3890. return false;
  3891. // Compute the value which the bitfield will contain.
  3892. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  3893. TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
  3894. // Check whether the stored value is equal to the original value.
  3895. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  3896. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  3897. return false;
  3898. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  3899. // therefore don't strictly fit into a signed bitfield of width 1.
  3900. if (FieldWidth == 1 && Value == 1)
  3901. return false;
  3902. std::string PrettyValue = Value.toString(10);
  3903. std::string PrettyTrunc = TruncatedValue.toString(10);
  3904. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  3905. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  3906. << Init->getSourceRange();
  3907. return true;
  3908. }
  3909. /// Analyze the given simple or compound assignment for warning-worthy
  3910. /// operations.
  3911. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  3912. // Just recurse on the LHS.
  3913. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3914. // We want to recurse on the RHS as normal unless we're assigning to
  3915. // a bitfield.
  3916. if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
  3917. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  3918. E->getOperatorLoc())) {
  3919. // Recurse, ignoring any implicit conversions on the RHS.
  3920. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  3921. E->getOperatorLoc());
  3922. }
  3923. }
  3924. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3925. }
  3926. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3927. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  3928. SourceLocation CContext, unsigned diag,
  3929. bool pruneControlFlow = false) {
  3930. if (pruneControlFlow) {
  3931. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  3932. S.PDiag(diag)
  3933. << SourceType << T << E->getSourceRange()
  3934. << SourceRange(CContext));
  3935. return;
  3936. }
  3937. S.Diag(E->getExprLoc(), diag)
  3938. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  3939. }
  3940. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3941. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  3942. SourceLocation CContext, unsigned diag,
  3943. bool pruneControlFlow = false) {
  3944. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  3945. }
  3946. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  3947. /// cast wouldn't lose information.
  3948. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  3949. SourceLocation CContext) {
  3950. // Try to convert the literal exactly to an integer. If we can, don't warn.
  3951. bool isExact = false;
  3952. const llvm::APFloat &Value = FL->getValue();
  3953. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  3954. T->hasUnsignedIntegerRepresentation());
  3955. if (Value.convertToInteger(IntegerValue,
  3956. llvm::APFloat::rmTowardZero, &isExact)
  3957. == llvm::APFloat::opOK && isExact)
  3958. return;
  3959. SmallString<16> PrettySourceValue;
  3960. Value.toString(PrettySourceValue);
  3961. SmallString<16> PrettyTargetValue;
  3962. if (T->isSpecificBuiltinType(BuiltinType::Bool))
  3963. PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
  3964. else
  3965. IntegerValue.toString(PrettyTargetValue);
  3966. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  3967. << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
  3968. << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
  3969. }
  3970. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  3971. if (!Range.Width) return "0";
  3972. llvm::APSInt ValueInRange = Value;
  3973. ValueInRange.setIsSigned(!Range.NonNegative);
  3974. ValueInRange = ValueInRange.trunc(Range.Width);
  3975. return ValueInRange.toString(10);
  3976. }
  3977. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  3978. if (!isa<ImplicitCastExpr>(Ex))
  3979. return false;
  3980. Expr *InnerE = Ex->IgnoreParenImpCasts();
  3981. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  3982. const Type *Source =
  3983. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  3984. if (Target->isDependentType())
  3985. return false;
  3986. const BuiltinType *FloatCandidateBT =
  3987. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  3988. const Type *BoolCandidateType = ToBool ? Target : Source;
  3989. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  3990. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  3991. }
  3992. void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  3993. SourceLocation CC) {
  3994. unsigned NumArgs = TheCall->getNumArgs();
  3995. for (unsigned i = 0; i < NumArgs; ++i) {
  3996. Expr *CurrA = TheCall->getArg(i);
  3997. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  3998. continue;
  3999. bool IsSwapped = ((i > 0) &&
  4000. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  4001. IsSwapped |= ((i < (NumArgs - 1)) &&
  4002. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  4003. if (IsSwapped) {
  4004. // Warn on this floating-point to bool conversion.
  4005. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  4006. CurrA->getType(), CC,
  4007. diag::warn_impcast_floating_point_to_bool);
  4008. }
  4009. }
  4010. }
  4011. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  4012. SourceLocation CC, bool *ICContext = 0) {
  4013. if (E->isTypeDependent() || E->isValueDependent()) return;
  4014. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  4015. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  4016. if (Source == Target) return;
  4017. if (Target->isDependentType()) return;
  4018. // If the conversion context location is invalid don't complain. We also
  4019. // don't want to emit a warning if the issue occurs from the expansion of
  4020. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  4021. // delay this check as long as possible. Once we detect we are in that
  4022. // scenario, we just return.
  4023. if (CC.isInvalid())
  4024. return;
  4025. // Diagnose implicit casts to bool.
  4026. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  4027. if (isa<StringLiteral>(E))
  4028. // Warn on string literal to bool. Checks for string literals in logical
  4029. // expressions, for instances, assert(0 && "error here"), is prevented
  4030. // by a check in AnalyzeImplicitConversions().
  4031. return DiagnoseImpCast(S, E, T, CC,
  4032. diag::warn_impcast_string_literal_to_bool);
  4033. if (Source->isFunctionType()) {
  4034. // Warn on function to bool. Checks free functions and static member
  4035. // functions. Weakly imported functions are excluded from the check,
  4036. // since it's common to test their value to check whether the linker
  4037. // found a definition for them.
  4038. ValueDecl *D = 0;
  4039. if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
  4040. D = R->getDecl();
  4041. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  4042. D = M->getMemberDecl();
  4043. }
  4044. if (D && !D->isWeak()) {
  4045. if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
  4046. S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
  4047. << F << E->getSourceRange() << SourceRange(CC);
  4048. S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
  4049. << FixItHint::CreateInsertion(E->getExprLoc(), "&");
  4050. QualType ReturnType;
  4051. UnresolvedSet<4> NonTemplateOverloads;
  4052. S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
  4053. if (!ReturnType.isNull()
  4054. && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  4055. S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
  4056. << FixItHint::CreateInsertion(
  4057. S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
  4058. return;
  4059. }
  4060. }
  4061. }
  4062. }
  4063. // Strip vector types.
  4064. if (isa<VectorType>(Source)) {
  4065. if (!isa<VectorType>(Target)) {
  4066. if (S.SourceMgr.isInSystemMacro(CC))
  4067. return;
  4068. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  4069. }
  4070. // If the vector cast is cast between two vectors of the same size, it is
  4071. // a bitcast, not a conversion.
  4072. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  4073. return;
  4074. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  4075. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  4076. }
  4077. // Strip complex types.
  4078. if (isa<ComplexType>(Source)) {
  4079. if (!isa<ComplexType>(Target)) {
  4080. if (S.SourceMgr.isInSystemMacro(CC))
  4081. return;
  4082. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  4083. }
  4084. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  4085. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  4086. }
  4087. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  4088. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  4089. // If the source is floating point...
  4090. if (SourceBT && SourceBT->isFloatingPoint()) {
  4091. // ...and the target is floating point...
  4092. if (TargetBT && TargetBT->isFloatingPoint()) {
  4093. // ...then warn if we're dropping FP rank.
  4094. // Builtin FP kinds are ordered by increasing FP rank.
  4095. if (SourceBT->getKind() > TargetBT->getKind()) {
  4096. // Don't warn about float constants that are precisely
  4097. // representable in the target type.
  4098. Expr::EvalResult result;
  4099. if (E->EvaluateAsRValue(result, S.Context)) {
  4100. // Value might be a float, a float vector, or a float complex.
  4101. if (IsSameFloatAfterCast(result.Val,
  4102. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  4103. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  4104. return;
  4105. }
  4106. if (S.SourceMgr.isInSystemMacro(CC))
  4107. return;
  4108. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  4109. }
  4110. return;
  4111. }
  4112. // If the target is integral, always warn.
  4113. if (TargetBT && TargetBT->isInteger()) {
  4114. if (S.SourceMgr.isInSystemMacro(CC))
  4115. return;
  4116. Expr *InnerE = E->IgnoreParenImpCasts();
  4117. // We also want to warn on, e.g., "int i = -1.234"
  4118. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  4119. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  4120. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  4121. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  4122. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  4123. } else {
  4124. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  4125. }
  4126. }
  4127. // If the target is bool, warn if expr is a function or method call.
  4128. if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
  4129. isa<CallExpr>(E)) {
  4130. // Check last argument of function call to see if it is an
  4131. // implicit cast from a type matching the type the result
  4132. // is being cast to.
  4133. CallExpr *CEx = cast<CallExpr>(E);
  4134. unsigned NumArgs = CEx->getNumArgs();
  4135. if (NumArgs > 0) {
  4136. Expr *LastA = CEx->getArg(NumArgs - 1);
  4137. Expr *InnerE = LastA->IgnoreParenImpCasts();
  4138. const Type *InnerType =
  4139. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  4140. if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
  4141. // Warn on this floating-point to bool conversion
  4142. DiagnoseImpCast(S, E, T, CC,
  4143. diag::warn_impcast_floating_point_to_bool);
  4144. }
  4145. }
  4146. }
  4147. return;
  4148. }
  4149. if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
  4150. == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
  4151. && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
  4152. SourceLocation Loc = E->getSourceRange().getBegin();
  4153. if (Loc.isMacroID())
  4154. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  4155. if (!Loc.isMacroID() || CC.isMacroID())
  4156. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  4157. << T << clang::SourceRange(CC)
  4158. << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
  4159. }
  4160. if (!Source->isIntegerType() || !Target->isIntegerType())
  4161. return;
  4162. // TODO: remove this early return once the false positives for constant->bool
  4163. // in templates, macros, etc, are reduced or removed.
  4164. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  4165. return;
  4166. IntRange SourceRange = GetExprRange(S.Context, E);
  4167. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  4168. if (SourceRange.Width > TargetRange.Width) {
  4169. // If the source is a constant, use a default-on diagnostic.
  4170. // TODO: this should happen for bitfield stores, too.
  4171. llvm::APSInt Value(32);
  4172. if (E->isIntegerConstantExpr(Value, S.Context)) {
  4173. if (S.SourceMgr.isInSystemMacro(CC))
  4174. return;
  4175. std::string PrettySourceValue = Value.toString(10);
  4176. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  4177. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  4178. S.PDiag(diag::warn_impcast_integer_precision_constant)
  4179. << PrettySourceValue << PrettyTargetValue
  4180. << E->getType() << T << E->getSourceRange()
  4181. << clang::SourceRange(CC));
  4182. return;
  4183. }
  4184. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  4185. if (S.SourceMgr.isInSystemMacro(CC))
  4186. return;
  4187. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  4188. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  4189. /* pruneControlFlow */ true);
  4190. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  4191. }
  4192. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  4193. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  4194. SourceRange.Width == TargetRange.Width)) {
  4195. if (S.SourceMgr.isInSystemMacro(CC))
  4196. return;
  4197. unsigned DiagID = diag::warn_impcast_integer_sign;
  4198. // Traditionally, gcc has warned about this under -Wsign-compare.
  4199. // We also want to warn about it in -Wconversion.
  4200. // So if -Wconversion is off, use a completely identical diagnostic
  4201. // in the sign-compare group.
  4202. // The conditional-checking code will
  4203. if (ICContext) {
  4204. DiagID = diag::warn_impcast_integer_sign_conditional;
  4205. *ICContext = true;
  4206. }
  4207. return DiagnoseImpCast(S, E, T, CC, DiagID);
  4208. }
  4209. // Diagnose conversions between different enumeration types.
  4210. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  4211. // type, to give us better diagnostics.
  4212. QualType SourceType = E->getType();
  4213. if (!S.getLangOpts().CPlusPlus) {
  4214. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4215. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  4216. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  4217. SourceType = S.Context.getTypeDeclType(Enum);
  4218. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  4219. }
  4220. }
  4221. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  4222. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  4223. if ((SourceEnum->getDecl()->getIdentifier() ||
  4224. SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  4225. (TargetEnum->getDecl()->getIdentifier() ||
  4226. TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  4227. SourceEnum != TargetEnum) {
  4228. if (S.SourceMgr.isInSystemMacro(CC))
  4229. return;
  4230. return DiagnoseImpCast(S, E, SourceType, T, CC,
  4231. diag::warn_impcast_different_enum_types);
  4232. }
  4233. return;
  4234. }
  4235. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  4236. SourceLocation CC, QualType T);
  4237. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  4238. SourceLocation CC, bool &ICContext) {
  4239. E = E->IgnoreParenImpCasts();
  4240. if (isa<ConditionalOperator>(E))
  4241. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  4242. AnalyzeImplicitConversions(S, E, CC);
  4243. if (E->getType() != T)
  4244. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  4245. return;
  4246. }
  4247. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  4248. SourceLocation CC, QualType T) {
  4249. AnalyzeImplicitConversions(S, E->getCond(), CC);
  4250. bool Suspicious = false;
  4251. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  4252. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  4253. // If -Wconversion would have warned about either of the candidates
  4254. // for a signedness conversion to the context type...
  4255. if (!Suspicious) return;
  4256. // ...but it's currently ignored...
  4257. if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
  4258. CC))
  4259. return;
  4260. // ...then check whether it would have warned about either of the
  4261. // candidates for a signedness conversion to the condition type.
  4262. if (E->getType() == T) return;
  4263. Suspicious = false;
  4264. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  4265. E->getType(), CC, &Suspicious);
  4266. if (!Suspicious)
  4267. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  4268. E->getType(), CC, &Suspicious);
  4269. }
  4270. /// AnalyzeImplicitConversions - Find and report any interesting
  4271. /// implicit conversions in the given expression. There are a couple
  4272. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  4273. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  4274. QualType T = OrigE->getType();
  4275. Expr *E = OrigE->IgnoreParenImpCasts();
  4276. if (E->isTypeDependent() || E->isValueDependent())
  4277. return;
  4278. // For conditional operators, we analyze the arguments as if they
  4279. // were being fed directly into the output.
  4280. if (isa<ConditionalOperator>(E)) {
  4281. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  4282. CheckConditionalOperator(S, CO, CC, T);
  4283. return;
  4284. }
  4285. // Check implicit argument conversions for function calls.
  4286. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  4287. CheckImplicitArgumentConversions(S, Call, CC);
  4288. // Go ahead and check any implicit conversions we might have skipped.
  4289. // The non-canonical typecheck is just an optimization;
  4290. // CheckImplicitConversion will filter out dead implicit conversions.
  4291. if (E->getType() != T)
  4292. CheckImplicitConversion(S, E, T, CC);
  4293. // Now continue drilling into this expression.
  4294. // Skip past explicit casts.
  4295. if (isa<ExplicitCastExpr>(E)) {
  4296. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  4297. return AnalyzeImplicitConversions(S, E, CC);
  4298. }
  4299. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  4300. // Do a somewhat different check with comparison operators.
  4301. if (BO->isComparisonOp())
  4302. return AnalyzeComparison(S, BO);
  4303. // And with simple assignments.
  4304. if (BO->getOpcode() == BO_Assign)
  4305. return AnalyzeAssignment(S, BO);
  4306. }
  4307. // These break the otherwise-useful invariant below. Fortunately,
  4308. // we don't really need to recurse into them, because any internal
  4309. // expressions should have been analyzed already when they were
  4310. // built into statements.
  4311. if (isa<StmtExpr>(E)) return;
  4312. // Don't descend into unevaluated contexts.
  4313. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  4314. // Now just recurse over the expression's children.
  4315. CC = E->getExprLoc();
  4316. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  4317. bool IsLogicalOperator = BO && BO->isLogicalOp();
  4318. for (Stmt::child_range I = E->children(); I; ++I) {
  4319. Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
  4320. if (!ChildExpr)
  4321. continue;
  4322. if (IsLogicalOperator &&
  4323. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  4324. // Ignore checking string literals that are in logical operators.
  4325. continue;
  4326. AnalyzeImplicitConversions(S, ChildExpr, CC);
  4327. }
  4328. }
  4329. } // end anonymous namespace
  4330. /// Diagnoses "dangerous" implicit conversions within the given
  4331. /// expression (which is a full expression). Implements -Wconversion
  4332. /// and -Wsign-compare.
  4333. ///
  4334. /// \param CC the "context" location of the implicit conversion, i.e.
  4335. /// the most location of the syntactic entity requiring the implicit
  4336. /// conversion
  4337. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  4338. // Don't diagnose in unevaluated contexts.
  4339. if (isUnevaluatedContext())
  4340. return;
  4341. // Don't diagnose for value- or type-dependent expressions.
  4342. if (E->isTypeDependent() || E->isValueDependent())
  4343. return;
  4344. // Check for array bounds violations in cases where the check isn't triggered
  4345. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  4346. // ArraySubscriptExpr is on the RHS of a variable initialization.
  4347. CheckArrayAccess(E);
  4348. // This is not the right CC for (e.g.) a variable initialization.
  4349. AnalyzeImplicitConversions(*this, E, CC);
  4350. }
  4351. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  4352. FieldDecl *BitField,
  4353. Expr *Init) {
  4354. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  4355. }
  4356. /// CheckParmsForFunctionDef - Check that the parameters of the given
  4357. /// function are appropriate for the definition of a function. This
  4358. /// takes care of any checks that cannot be performed on the
  4359. /// declaration itself, e.g., that the types of each of the function
  4360. /// parameters are complete.
  4361. bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
  4362. bool CheckParameterNames) {
  4363. bool HasInvalidParm = false;
  4364. for (; P != PEnd; ++P) {
  4365. ParmVarDecl *Param = *P;
  4366. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  4367. // function declarator that is part of a function definition of
  4368. // that function shall not have incomplete type.
  4369. //
  4370. // This is also C++ [dcl.fct]p6.
  4371. if (!Param->isInvalidDecl() &&
  4372. RequireCompleteType(Param->getLocation(), Param->getType(),
  4373. diag::err_typecheck_decl_incomplete_type)) {
  4374. Param->setInvalidDecl();
  4375. HasInvalidParm = true;
  4376. }
  4377. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  4378. // declaration of each parameter shall include an identifier.
  4379. if (CheckParameterNames &&
  4380. Param->getIdentifier() == 0 &&
  4381. !Param->isImplicit() &&
  4382. !getLangOpts().CPlusPlus)
  4383. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  4384. // C99 6.7.5.3p12:
  4385. // If the function declarator is not part of a definition of that
  4386. // function, parameters may have incomplete type and may use the [*]
  4387. // notation in their sequences of declarator specifiers to specify
  4388. // variable length array types.
  4389. QualType PType = Param->getOriginalType();
  4390. if (const ArrayType *AT = Context.getAsArrayType(PType)) {
  4391. if (AT->getSizeModifier() == ArrayType::Star) {
  4392. // FIXME: This diagnosic should point the '[*]' if source-location
  4393. // information is added for it.
  4394. Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
  4395. }
  4396. }
  4397. }
  4398. return HasInvalidParm;
  4399. }
  4400. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  4401. /// pointer cast increases the alignment requirements.
  4402. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  4403. // This is actually a lot of work to potentially be doing on every
  4404. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  4405. if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
  4406. TRange.getBegin())
  4407. == DiagnosticsEngine::Ignored)
  4408. return;
  4409. // Ignore dependent types.
  4410. if (T->isDependentType() || Op->getType()->isDependentType())
  4411. return;
  4412. // Require that the destination be a pointer type.
  4413. const PointerType *DestPtr = T->getAs<PointerType>();
  4414. if (!DestPtr) return;
  4415. // If the destination has alignment 1, we're done.
  4416. QualType DestPointee = DestPtr->getPointeeType();
  4417. if (DestPointee->isIncompleteType()) return;
  4418. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  4419. if (DestAlign.isOne()) return;
  4420. // Require that the source be a pointer type.
  4421. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  4422. if (!SrcPtr) return;
  4423. QualType SrcPointee = SrcPtr->getPointeeType();
  4424. // Whitelist casts from cv void*. We already implicitly
  4425. // whitelisted casts to cv void*, since they have alignment 1.
  4426. // Also whitelist casts involving incomplete types, which implicitly
  4427. // includes 'void'.
  4428. if (SrcPointee->isIncompleteType()) return;
  4429. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  4430. if (SrcAlign >= DestAlign) return;
  4431. Diag(TRange.getBegin(), diag::warn_cast_align)
  4432. << Op->getType() << T
  4433. << static_cast<unsigned>(SrcAlign.getQuantity())
  4434. << static_cast<unsigned>(DestAlign.getQuantity())
  4435. << TRange << Op->getSourceRange();
  4436. }
  4437. static const Type* getElementType(const Expr *BaseExpr) {
  4438. const Type* EltType = BaseExpr->getType().getTypePtr();
  4439. if (EltType->isAnyPointerType())
  4440. return EltType->getPointeeType().getTypePtr();
  4441. else if (EltType->isArrayType())
  4442. return EltType->getBaseElementTypeUnsafe();
  4443. return EltType;
  4444. }
  4445. /// \brief Check whether this array fits the idiom of a size-one tail padded
  4446. /// array member of a struct.
  4447. ///
  4448. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  4449. /// commonly used to emulate flexible arrays in C89 code.
  4450. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  4451. const NamedDecl *ND) {
  4452. if (Size != 1 || !ND) return false;
  4453. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  4454. if (!FD) return false;
  4455. // Don't consider sizes resulting from macro expansions or template argument
  4456. // substitution to form C89 tail-padded arrays.
  4457. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  4458. while (TInfo) {
  4459. TypeLoc TL = TInfo->getTypeLoc();
  4460. // Look through typedefs.
  4461. const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
  4462. if (TTL) {
  4463. const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
  4464. TInfo = TDL->getTypeSourceInfo();
  4465. continue;
  4466. }
  4467. ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
  4468. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  4469. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  4470. return false;
  4471. break;
  4472. }
  4473. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  4474. if (!RD) return false;
  4475. if (RD->isUnion()) return false;
  4476. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  4477. if (!CRD->isStandardLayout()) return false;
  4478. }
  4479. // See if this is the last field decl in the record.
  4480. const Decl *D = FD;
  4481. while ((D = D->getNextDeclInContext()))
  4482. if (isa<FieldDecl>(D))
  4483. return false;
  4484. return true;
  4485. }
  4486. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  4487. const ArraySubscriptExpr *ASE,
  4488. bool AllowOnePastEnd, bool IndexNegated) {
  4489. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  4490. if (IndexExpr->isValueDependent())
  4491. return;
  4492. const Type *EffectiveType = getElementType(BaseExpr);
  4493. BaseExpr = BaseExpr->IgnoreParenCasts();
  4494. const ConstantArrayType *ArrayTy =
  4495. Context.getAsConstantArrayType(BaseExpr->getType());
  4496. if (!ArrayTy)
  4497. return;
  4498. llvm::APSInt index;
  4499. if (!IndexExpr->EvaluateAsInt(index, Context))
  4500. return;
  4501. if (IndexNegated)
  4502. index = -index;
  4503. const NamedDecl *ND = NULL;
  4504. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  4505. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  4506. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  4507. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  4508. if (index.isUnsigned() || !index.isNegative()) {
  4509. llvm::APInt size = ArrayTy->getSize();
  4510. if (!size.isStrictlyPositive())
  4511. return;
  4512. const Type* BaseType = getElementType(BaseExpr);
  4513. if (BaseType != EffectiveType) {
  4514. // Make sure we're comparing apples to apples when comparing index to size
  4515. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  4516. uint64_t array_typesize = Context.getTypeSize(BaseType);
  4517. // Handle ptrarith_typesize being zero, such as when casting to void*
  4518. if (!ptrarith_typesize) ptrarith_typesize = 1;
  4519. if (ptrarith_typesize != array_typesize) {
  4520. // There's a cast to a different size type involved
  4521. uint64_t ratio = array_typesize / ptrarith_typesize;
  4522. // TODO: Be smarter about handling cases where array_typesize is not a
  4523. // multiple of ptrarith_typesize
  4524. if (ptrarith_typesize * ratio == array_typesize)
  4525. size *= llvm::APInt(size.getBitWidth(), ratio);
  4526. }
  4527. }
  4528. if (size.getBitWidth() > index.getBitWidth())
  4529. index = index.zext(size.getBitWidth());
  4530. else if (size.getBitWidth() < index.getBitWidth())
  4531. size = size.zext(index.getBitWidth());
  4532. // For array subscripting the index must be less than size, but for pointer
  4533. // arithmetic also allow the index (offset) to be equal to size since
  4534. // computing the next address after the end of the array is legal and
  4535. // commonly done e.g. in C++ iterators and range-based for loops.
  4536. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  4537. return;
  4538. // Also don't warn for arrays of size 1 which are members of some
  4539. // structure. These are often used to approximate flexible arrays in C89
  4540. // code.
  4541. if (IsTailPaddedMemberArray(*this, size, ND))
  4542. return;
  4543. // Suppress the warning if the subscript expression (as identified by the
  4544. // ']' location) and the index expression are both from macro expansions
  4545. // within a system header.
  4546. if (ASE) {
  4547. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  4548. ASE->getRBracketLoc());
  4549. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  4550. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  4551. IndexExpr->getLocStart());
  4552. if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
  4553. return;
  4554. }
  4555. }
  4556. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  4557. if (ASE)
  4558. DiagID = diag::warn_array_index_exceeds_bounds;
  4559. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  4560. PDiag(DiagID) << index.toString(10, true)
  4561. << size.toString(10, true)
  4562. << (unsigned)size.getLimitedValue(~0U)
  4563. << IndexExpr->getSourceRange());
  4564. } else {
  4565. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  4566. if (!ASE) {
  4567. DiagID = diag::warn_ptr_arith_precedes_bounds;
  4568. if (index.isNegative()) index = -index;
  4569. }
  4570. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  4571. PDiag(DiagID) << index.toString(10, true)
  4572. << IndexExpr->getSourceRange());
  4573. }
  4574. if (!ND) {
  4575. // Try harder to find a NamedDecl to point at in the note.
  4576. while (const ArraySubscriptExpr *ASE =
  4577. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  4578. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  4579. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  4580. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  4581. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  4582. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  4583. }
  4584. if (ND)
  4585. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  4586. PDiag(diag::note_array_index_out_of_bounds)
  4587. << ND->getDeclName());
  4588. }
  4589. void Sema::CheckArrayAccess(const Expr *expr) {
  4590. int AllowOnePastEnd = 0;
  4591. while (expr) {
  4592. expr = expr->IgnoreParenImpCasts();
  4593. switch (expr->getStmtClass()) {
  4594. case Stmt::ArraySubscriptExprClass: {
  4595. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  4596. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  4597. AllowOnePastEnd > 0);
  4598. return;
  4599. }
  4600. case Stmt::UnaryOperatorClass: {
  4601. // Only unwrap the * and & unary operators
  4602. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  4603. expr = UO->getSubExpr();
  4604. switch (UO->getOpcode()) {
  4605. case UO_AddrOf:
  4606. AllowOnePastEnd++;
  4607. break;
  4608. case UO_Deref:
  4609. AllowOnePastEnd--;
  4610. break;
  4611. default:
  4612. return;
  4613. }
  4614. break;
  4615. }
  4616. case Stmt::ConditionalOperatorClass: {
  4617. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  4618. if (const Expr *lhs = cond->getLHS())
  4619. CheckArrayAccess(lhs);
  4620. if (const Expr *rhs = cond->getRHS())
  4621. CheckArrayAccess(rhs);
  4622. return;
  4623. }
  4624. default:
  4625. return;
  4626. }
  4627. }
  4628. }
  4629. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  4630. namespace {
  4631. struct RetainCycleOwner {
  4632. RetainCycleOwner() : Variable(0), Indirect(false) {}
  4633. VarDecl *Variable;
  4634. SourceRange Range;
  4635. SourceLocation Loc;
  4636. bool Indirect;
  4637. void setLocsFrom(Expr *e) {
  4638. Loc = e->getExprLoc();
  4639. Range = e->getSourceRange();
  4640. }
  4641. };
  4642. }
  4643. /// Consider whether capturing the given variable can possibly lead to
  4644. /// a retain cycle.
  4645. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  4646. // In ARC, it's captured strongly iff the variable has __strong
  4647. // lifetime. In MRR, it's captured strongly if the variable is
  4648. // __block and has an appropriate type.
  4649. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  4650. return false;
  4651. owner.Variable = var;
  4652. if (ref)
  4653. owner.setLocsFrom(ref);
  4654. return true;
  4655. }
  4656. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  4657. while (true) {
  4658. e = e->IgnoreParens();
  4659. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  4660. switch (cast->getCastKind()) {
  4661. case CK_BitCast:
  4662. case CK_LValueBitCast:
  4663. case CK_LValueToRValue:
  4664. case CK_ARCReclaimReturnedObject:
  4665. e = cast->getSubExpr();
  4666. continue;
  4667. default:
  4668. return false;
  4669. }
  4670. }
  4671. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  4672. ObjCIvarDecl *ivar = ref->getDecl();
  4673. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  4674. return false;
  4675. // Try to find a retain cycle in the base.
  4676. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  4677. return false;
  4678. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  4679. owner.Indirect = true;
  4680. return true;
  4681. }
  4682. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  4683. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  4684. if (!var) return false;
  4685. return considerVariable(var, ref, owner);
  4686. }
  4687. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  4688. if (member->isArrow()) return false;
  4689. // Don't count this as an indirect ownership.
  4690. e = member->getBase();
  4691. continue;
  4692. }
  4693. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  4694. // Only pay attention to pseudo-objects on property references.
  4695. ObjCPropertyRefExpr *pre
  4696. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  4697. ->IgnoreParens());
  4698. if (!pre) return false;
  4699. if (pre->isImplicitProperty()) return false;
  4700. ObjCPropertyDecl *property = pre->getExplicitProperty();
  4701. if (!property->isRetaining() &&
  4702. !(property->getPropertyIvarDecl() &&
  4703. property->getPropertyIvarDecl()->getType()
  4704. .getObjCLifetime() == Qualifiers::OCL_Strong))
  4705. return false;
  4706. owner.Indirect = true;
  4707. if (pre->isSuperReceiver()) {
  4708. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  4709. if (!owner.Variable)
  4710. return false;
  4711. owner.Loc = pre->getLocation();
  4712. owner.Range = pre->getSourceRange();
  4713. return true;
  4714. }
  4715. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  4716. ->getSourceExpr());
  4717. continue;
  4718. }
  4719. // Array ivars?
  4720. return false;
  4721. }
  4722. }
  4723. namespace {
  4724. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  4725. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  4726. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  4727. Variable(variable), Capturer(0) {}
  4728. VarDecl *Variable;
  4729. Expr *Capturer;
  4730. void VisitDeclRefExpr(DeclRefExpr *ref) {
  4731. if (ref->getDecl() == Variable && !Capturer)
  4732. Capturer = ref;
  4733. }
  4734. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  4735. if (Capturer) return;
  4736. Visit(ref->getBase());
  4737. if (Capturer && ref->isFreeIvar())
  4738. Capturer = ref;
  4739. }
  4740. void VisitBlockExpr(BlockExpr *block) {
  4741. // Look inside nested blocks
  4742. if (block->getBlockDecl()->capturesVariable(Variable))
  4743. Visit(block->getBlockDecl()->getBody());
  4744. }
  4745. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  4746. if (Capturer) return;
  4747. if (OVE->getSourceExpr())
  4748. Visit(OVE->getSourceExpr());
  4749. }
  4750. };
  4751. }
  4752. /// Check whether the given argument is a block which captures a
  4753. /// variable.
  4754. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  4755. assert(owner.Variable && owner.Loc.isValid());
  4756. e = e->IgnoreParenCasts();
  4757. // Look through [^{...} copy] and Block_copy(^{...}).
  4758. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  4759. Selector Cmd = ME->getSelector();
  4760. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  4761. e = ME->getInstanceReceiver();
  4762. if (!e)
  4763. return 0;
  4764. e = e->IgnoreParenCasts();
  4765. }
  4766. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  4767. if (CE->getNumArgs() == 1) {
  4768. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  4769. if (Fn && Fn->getIdentifier()->isStr("_Block_copy"))
  4770. e = CE->getArg(0)->IgnoreParenCasts();
  4771. }
  4772. }
  4773. BlockExpr *block = dyn_cast<BlockExpr>(e);
  4774. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  4775. return 0;
  4776. FindCaptureVisitor visitor(S.Context, owner.Variable);
  4777. visitor.Visit(block->getBlockDecl()->getBody());
  4778. return visitor.Capturer;
  4779. }
  4780. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  4781. RetainCycleOwner &owner) {
  4782. assert(capturer);
  4783. assert(owner.Variable && owner.Loc.isValid());
  4784. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  4785. << owner.Variable << capturer->getSourceRange();
  4786. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  4787. << owner.Indirect << owner.Range;
  4788. }
  4789. /// Check for a keyword selector that starts with the word 'add' or
  4790. /// 'set'.
  4791. static bool isSetterLikeSelector(Selector sel) {
  4792. if (sel.isUnarySelector()) return false;
  4793. StringRef str = sel.getNameForSlot(0);
  4794. while (!str.empty() && str.front() == '_') str = str.substr(1);
  4795. if (str.startswith("set"))
  4796. str = str.substr(3);
  4797. else if (str.startswith("add")) {
  4798. // Specially whitelist 'addOperationWithBlock:'.
  4799. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  4800. return false;
  4801. str = str.substr(3);
  4802. }
  4803. else
  4804. return false;
  4805. if (str.empty()) return true;
  4806. return !islower(str.front());
  4807. }
  4808. /// Check a message send to see if it's likely to cause a retain cycle.
  4809. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  4810. // Only check instance methods whose selector looks like a setter.
  4811. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  4812. return;
  4813. // Try to find a variable that the receiver is strongly owned by.
  4814. RetainCycleOwner owner;
  4815. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  4816. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  4817. return;
  4818. } else {
  4819. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  4820. owner.Variable = getCurMethodDecl()->getSelfDecl();
  4821. owner.Loc = msg->getSuperLoc();
  4822. owner.Range = msg->getSuperLoc();
  4823. }
  4824. // Check whether the receiver is captured by any of the arguments.
  4825. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  4826. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  4827. return diagnoseRetainCycle(*this, capturer, owner);
  4828. }
  4829. /// Check a property assign to see if it's likely to cause a retain cycle.
  4830. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  4831. RetainCycleOwner owner;
  4832. if (!findRetainCycleOwner(*this, receiver, owner))
  4833. return;
  4834. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  4835. diagnoseRetainCycle(*this, capturer, owner);
  4836. }
  4837. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  4838. RetainCycleOwner Owner;
  4839. if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
  4840. return;
  4841. // Because we don't have an expression for the variable, we have to set the
  4842. // location explicitly here.
  4843. Owner.Loc = Var->getLocation();
  4844. Owner.Range = Var->getSourceRange();
  4845. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  4846. diagnoseRetainCycle(*this, Capturer, Owner);
  4847. }
  4848. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  4849. QualType LHS, Expr *RHS) {
  4850. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  4851. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  4852. return false;
  4853. // strip off any implicit cast added to get to the one arc-specific
  4854. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4855. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4856. Diag(Loc, diag::warn_arc_retained_assign)
  4857. << (LT == Qualifiers::OCL_ExplicitNone) << 1
  4858. << RHS->getSourceRange();
  4859. return true;
  4860. }
  4861. RHS = cast->getSubExpr();
  4862. }
  4863. return false;
  4864. }
  4865. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  4866. Expr *LHS, Expr *RHS) {
  4867. QualType LHSType;
  4868. // PropertyRef on LHS type need be directly obtained from
  4869. // its declaration as it has a PsuedoType.
  4870. ObjCPropertyRefExpr *PRE
  4871. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  4872. if (PRE && !PRE->isImplicitProperty()) {
  4873. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  4874. if (PD)
  4875. LHSType = PD->getType();
  4876. }
  4877. if (LHSType.isNull())
  4878. LHSType = LHS->getType();
  4879. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  4880. return;
  4881. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  4882. // FIXME. Check for other life times.
  4883. if (LT != Qualifiers::OCL_None)
  4884. return;
  4885. if (PRE) {
  4886. if (PRE->isImplicitProperty())
  4887. return;
  4888. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  4889. if (!PD)
  4890. return;
  4891. unsigned Attributes = PD->getPropertyAttributes();
  4892. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  4893. // when 'assign' attribute was not explicitly specified
  4894. // by user, ignore it and rely on property type itself
  4895. // for lifetime info.
  4896. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  4897. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  4898. LHSType->isObjCRetainableType())
  4899. return;
  4900. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4901. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4902. Diag(Loc, diag::warn_arc_retained_property_assign)
  4903. << RHS->getSourceRange();
  4904. return;
  4905. }
  4906. RHS = cast->getSubExpr();
  4907. }
  4908. }
  4909. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  4910. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4911. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4912. Diag(Loc, diag::warn_arc_retained_assign)
  4913. << 0 << 0<< RHS->getSourceRange();
  4914. return;
  4915. }
  4916. RHS = cast->getSubExpr();
  4917. }
  4918. }
  4919. }
  4920. }
  4921. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  4922. namespace {
  4923. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  4924. SourceLocation StmtLoc,
  4925. const NullStmt *Body) {
  4926. // Do not warn if the body is a macro that expands to nothing, e.g:
  4927. //
  4928. // #define CALL(x)
  4929. // if (condition)
  4930. // CALL(0);
  4931. //
  4932. if (Body->hasLeadingEmptyMacro())
  4933. return false;
  4934. // Get line numbers of statement and body.
  4935. bool StmtLineInvalid;
  4936. unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
  4937. &StmtLineInvalid);
  4938. if (StmtLineInvalid)
  4939. return false;
  4940. bool BodyLineInvalid;
  4941. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  4942. &BodyLineInvalid);
  4943. if (BodyLineInvalid)
  4944. return false;
  4945. // Warn if null statement and body are on the same line.
  4946. if (StmtLine != BodyLine)
  4947. return false;
  4948. return true;
  4949. }
  4950. } // Unnamed namespace
  4951. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  4952. const Stmt *Body,
  4953. unsigned DiagID) {
  4954. // Since this is a syntactic check, don't emit diagnostic for template
  4955. // instantiations, this just adds noise.
  4956. if (CurrentInstantiationScope)
  4957. return;
  4958. // The body should be a null statement.
  4959. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  4960. if (!NBody)
  4961. return;
  4962. // Do the usual checks.
  4963. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  4964. return;
  4965. Diag(NBody->getSemiLoc(), DiagID);
  4966. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  4967. }
  4968. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  4969. const Stmt *PossibleBody) {
  4970. assert(!CurrentInstantiationScope); // Ensured by caller
  4971. SourceLocation StmtLoc;
  4972. const Stmt *Body;
  4973. unsigned DiagID;
  4974. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  4975. StmtLoc = FS->getRParenLoc();
  4976. Body = FS->getBody();
  4977. DiagID = diag::warn_empty_for_body;
  4978. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  4979. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  4980. Body = WS->getBody();
  4981. DiagID = diag::warn_empty_while_body;
  4982. } else
  4983. return; // Neither `for' nor `while'.
  4984. // The body should be a null statement.
  4985. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  4986. if (!NBody)
  4987. return;
  4988. // Skip expensive checks if diagnostic is disabled.
  4989. if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
  4990. DiagnosticsEngine::Ignored)
  4991. return;
  4992. // Do the usual checks.
  4993. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  4994. return;
  4995. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  4996. // noise level low, emit diagnostics only if for/while is followed by a
  4997. // CompoundStmt, e.g.:
  4998. // for (int i = 0; i < n; i++);
  4999. // {
  5000. // a(i);
  5001. // }
  5002. // or if for/while is followed by a statement with more indentation
  5003. // than for/while itself:
  5004. // for (int i = 0; i < n; i++);
  5005. // a(i);
  5006. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  5007. if (!ProbableTypo) {
  5008. bool BodyColInvalid;
  5009. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  5010. PossibleBody->getLocStart(),
  5011. &BodyColInvalid);
  5012. if (BodyColInvalid)
  5013. return;
  5014. bool StmtColInvalid;
  5015. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  5016. S->getLocStart(),
  5017. &StmtColInvalid);
  5018. if (StmtColInvalid)
  5019. return;
  5020. if (BodyCol > StmtCol)
  5021. ProbableTypo = true;
  5022. }
  5023. if (ProbableTypo) {
  5024. Diag(NBody->getSemiLoc(), DiagID);
  5025. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  5026. }
  5027. }
  5028. //===--- Layout compatibility ----------------------------------------------//
  5029. namespace {
  5030. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  5031. /// \brief Check if two enumeration types are layout-compatible.
  5032. bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  5033. // C++11 [dcl.enum] p8:
  5034. // Two enumeration types are layout-compatible if they have the same
  5035. // underlying type.
  5036. return ED1->isComplete() && ED2->isComplete() &&
  5037. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  5038. }
  5039. /// \brief Check if two fields are layout-compatible.
  5040. bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
  5041. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  5042. return false;
  5043. if (Field1->isBitField() != Field2->isBitField())
  5044. return false;
  5045. if (Field1->isBitField()) {
  5046. // Make sure that the bit-fields are the same length.
  5047. unsigned Bits1 = Field1->getBitWidthValue(C);
  5048. unsigned Bits2 = Field2->getBitWidthValue(C);
  5049. if (Bits1 != Bits2)
  5050. return false;
  5051. }
  5052. return true;
  5053. }
  5054. /// \brief Check if two standard-layout structs are layout-compatible.
  5055. /// (C++11 [class.mem] p17)
  5056. bool isLayoutCompatibleStruct(ASTContext &C,
  5057. RecordDecl *RD1,
  5058. RecordDecl *RD2) {
  5059. // If both records are C++ classes, check that base classes match.
  5060. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  5061. // If one of records is a CXXRecordDecl we are in C++ mode,
  5062. // thus the other one is a CXXRecordDecl, too.
  5063. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  5064. // Check number of base classes.
  5065. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  5066. return false;
  5067. // Check the base classes.
  5068. for (CXXRecordDecl::base_class_const_iterator
  5069. Base1 = D1CXX->bases_begin(),
  5070. BaseEnd1 = D1CXX->bases_end(),
  5071. Base2 = D2CXX->bases_begin();
  5072. Base1 != BaseEnd1;
  5073. ++Base1, ++Base2) {
  5074. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  5075. return false;
  5076. }
  5077. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  5078. // If only RD2 is a C++ class, it should have zero base classes.
  5079. if (D2CXX->getNumBases() > 0)
  5080. return false;
  5081. }
  5082. // Check the fields.
  5083. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  5084. Field2End = RD2->field_end(),
  5085. Field1 = RD1->field_begin(),
  5086. Field1End = RD1->field_end();
  5087. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  5088. if (!isLayoutCompatible(C, *Field1, *Field2))
  5089. return false;
  5090. }
  5091. if (Field1 != Field1End || Field2 != Field2End)
  5092. return false;
  5093. return true;
  5094. }
  5095. /// \brief Check if two standard-layout unions are layout-compatible.
  5096. /// (C++11 [class.mem] p18)
  5097. bool isLayoutCompatibleUnion(ASTContext &C,
  5098. RecordDecl *RD1,
  5099. RecordDecl *RD2) {
  5100. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  5101. for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
  5102. Field2End = RD2->field_end();
  5103. Field2 != Field2End; ++Field2) {
  5104. UnmatchedFields.insert(*Field2);
  5105. }
  5106. for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
  5107. Field1End = RD1->field_end();
  5108. Field1 != Field1End; ++Field1) {
  5109. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  5110. I = UnmatchedFields.begin(),
  5111. E = UnmatchedFields.end();
  5112. for ( ; I != E; ++I) {
  5113. if (isLayoutCompatible(C, *Field1, *I)) {
  5114. bool Result = UnmatchedFields.erase(*I);
  5115. (void) Result;
  5116. assert(Result);
  5117. break;
  5118. }
  5119. }
  5120. if (I == E)
  5121. return false;
  5122. }
  5123. return UnmatchedFields.empty();
  5124. }
  5125. bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
  5126. if (RD1->isUnion() != RD2->isUnion())
  5127. return false;
  5128. if (RD1->isUnion())
  5129. return isLayoutCompatibleUnion(C, RD1, RD2);
  5130. else
  5131. return isLayoutCompatibleStruct(C, RD1, RD2);
  5132. }
  5133. /// \brief Check if two types are layout-compatible in C++11 sense.
  5134. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  5135. if (T1.isNull() || T2.isNull())
  5136. return false;
  5137. // C++11 [basic.types] p11:
  5138. // If two types T1 and T2 are the same type, then T1 and T2 are
  5139. // layout-compatible types.
  5140. if (C.hasSameType(T1, T2))
  5141. return true;
  5142. T1 = T1.getCanonicalType().getUnqualifiedType();
  5143. T2 = T2.getCanonicalType().getUnqualifiedType();
  5144. const Type::TypeClass TC1 = T1->getTypeClass();
  5145. const Type::TypeClass TC2 = T2->getTypeClass();
  5146. if (TC1 != TC2)
  5147. return false;
  5148. if (TC1 == Type::Enum) {
  5149. return isLayoutCompatible(C,
  5150. cast<EnumType>(T1)->getDecl(),
  5151. cast<EnumType>(T2)->getDecl());
  5152. } else if (TC1 == Type::Record) {
  5153. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  5154. return false;
  5155. return isLayoutCompatible(C,
  5156. cast<RecordType>(T1)->getDecl(),
  5157. cast<RecordType>(T2)->getDecl());
  5158. }
  5159. return false;
  5160. }
  5161. }
  5162. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  5163. namespace {
  5164. /// \brief Given a type tag expression find the type tag itself.
  5165. ///
  5166. /// \param TypeExpr Type tag expression, as it appears in user's code.
  5167. ///
  5168. /// \param VD Declaration of an identifier that appears in a type tag.
  5169. ///
  5170. /// \param MagicValue Type tag magic value.
  5171. bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  5172. const ValueDecl **VD, uint64_t *MagicValue) {
  5173. while(true) {
  5174. if (!TypeExpr)
  5175. return false;
  5176. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  5177. switch (TypeExpr->getStmtClass()) {
  5178. case Stmt::UnaryOperatorClass: {
  5179. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  5180. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  5181. TypeExpr = UO->getSubExpr();
  5182. continue;
  5183. }
  5184. return false;
  5185. }
  5186. case Stmt::DeclRefExprClass: {
  5187. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  5188. *VD = DRE->getDecl();
  5189. return true;
  5190. }
  5191. case Stmt::IntegerLiteralClass: {
  5192. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  5193. llvm::APInt MagicValueAPInt = IL->getValue();
  5194. if (MagicValueAPInt.getActiveBits() <= 64) {
  5195. *MagicValue = MagicValueAPInt.getZExtValue();
  5196. return true;
  5197. } else
  5198. return false;
  5199. }
  5200. case Stmt::BinaryConditionalOperatorClass:
  5201. case Stmt::ConditionalOperatorClass: {
  5202. const AbstractConditionalOperator *ACO =
  5203. cast<AbstractConditionalOperator>(TypeExpr);
  5204. bool Result;
  5205. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  5206. if (Result)
  5207. TypeExpr = ACO->getTrueExpr();
  5208. else
  5209. TypeExpr = ACO->getFalseExpr();
  5210. continue;
  5211. }
  5212. return false;
  5213. }
  5214. case Stmt::BinaryOperatorClass: {
  5215. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  5216. if (BO->getOpcode() == BO_Comma) {
  5217. TypeExpr = BO->getRHS();
  5218. continue;
  5219. }
  5220. return false;
  5221. }
  5222. default:
  5223. return false;
  5224. }
  5225. }
  5226. }
  5227. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  5228. ///
  5229. /// \param TypeExpr Expression that specifies a type tag.
  5230. ///
  5231. /// \param MagicValues Registered magic values.
  5232. ///
  5233. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  5234. /// kind.
  5235. ///
  5236. /// \param TypeInfo Information about the corresponding C type.
  5237. ///
  5238. /// \returns true if the corresponding C type was found.
  5239. bool GetMatchingCType(
  5240. const IdentifierInfo *ArgumentKind,
  5241. const Expr *TypeExpr, const ASTContext &Ctx,
  5242. const llvm::DenseMap<Sema::TypeTagMagicValue,
  5243. Sema::TypeTagData> *MagicValues,
  5244. bool &FoundWrongKind,
  5245. Sema::TypeTagData &TypeInfo) {
  5246. FoundWrongKind = false;
  5247. // Variable declaration that has type_tag_for_datatype attribute.
  5248. const ValueDecl *VD = NULL;
  5249. uint64_t MagicValue;
  5250. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  5251. return false;
  5252. if (VD) {
  5253. for (specific_attr_iterator<TypeTagForDatatypeAttr>
  5254. I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
  5255. E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
  5256. I != E; ++I) {
  5257. if (I->getArgumentKind() != ArgumentKind) {
  5258. FoundWrongKind = true;
  5259. return false;
  5260. }
  5261. TypeInfo.Type = I->getMatchingCType();
  5262. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  5263. TypeInfo.MustBeNull = I->getMustBeNull();
  5264. return true;
  5265. }
  5266. return false;
  5267. }
  5268. if (!MagicValues)
  5269. return false;
  5270. llvm::DenseMap<Sema::TypeTagMagicValue,
  5271. Sema::TypeTagData>::const_iterator I =
  5272. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  5273. if (I == MagicValues->end())
  5274. return false;
  5275. TypeInfo = I->second;
  5276. return true;
  5277. }
  5278. } // unnamed namespace
  5279. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  5280. uint64_t MagicValue, QualType Type,
  5281. bool LayoutCompatible,
  5282. bool MustBeNull) {
  5283. if (!TypeTagForDatatypeMagicValues)
  5284. TypeTagForDatatypeMagicValues.reset(
  5285. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  5286. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  5287. (*TypeTagForDatatypeMagicValues)[Magic] =
  5288. TypeTagData(Type, LayoutCompatible, MustBeNull);
  5289. }
  5290. namespace {
  5291. bool IsSameCharType(QualType T1, QualType T2) {
  5292. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  5293. if (!BT1)
  5294. return false;
  5295. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  5296. if (!BT2)
  5297. return false;
  5298. BuiltinType::Kind T1Kind = BT1->getKind();
  5299. BuiltinType::Kind T2Kind = BT2->getKind();
  5300. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  5301. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  5302. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  5303. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  5304. }
  5305. } // unnamed namespace
  5306. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  5307. const Expr * const *ExprArgs) {
  5308. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  5309. bool IsPointerAttr = Attr->getIsPointer();
  5310. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  5311. bool FoundWrongKind;
  5312. TypeTagData TypeInfo;
  5313. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  5314. TypeTagForDatatypeMagicValues.get(),
  5315. FoundWrongKind, TypeInfo)) {
  5316. if (FoundWrongKind)
  5317. Diag(TypeTagExpr->getExprLoc(),
  5318. diag::warn_type_tag_for_datatype_wrong_kind)
  5319. << TypeTagExpr->getSourceRange();
  5320. return;
  5321. }
  5322. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  5323. if (IsPointerAttr) {
  5324. // Skip implicit cast of pointer to `void *' (as a function argument).
  5325. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  5326. if (ICE->getType()->isVoidPointerType())
  5327. ArgumentExpr = ICE->getSubExpr();
  5328. }
  5329. QualType ArgumentType = ArgumentExpr->getType();
  5330. // Passing a `void*' pointer shouldn't trigger a warning.
  5331. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  5332. return;
  5333. if (TypeInfo.MustBeNull) {
  5334. // Type tag with matching void type requires a null pointer.
  5335. if (!ArgumentExpr->isNullPointerConstant(Context,
  5336. Expr::NPC_ValueDependentIsNotNull)) {
  5337. Diag(ArgumentExpr->getExprLoc(),
  5338. diag::warn_type_safety_null_pointer_required)
  5339. << ArgumentKind->getName()
  5340. << ArgumentExpr->getSourceRange()
  5341. << TypeTagExpr->getSourceRange();
  5342. }
  5343. return;
  5344. }
  5345. QualType RequiredType = TypeInfo.Type;
  5346. if (IsPointerAttr)
  5347. RequiredType = Context.getPointerType(RequiredType);
  5348. bool mismatch = false;
  5349. if (!TypeInfo.LayoutCompatible) {
  5350. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  5351. // C++11 [basic.fundamental] p1:
  5352. // Plain char, signed char, and unsigned char are three distinct types.
  5353. //
  5354. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  5355. // char' depending on the current char signedness mode.
  5356. if (mismatch)
  5357. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  5358. RequiredType->getPointeeType())) ||
  5359. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  5360. mismatch = false;
  5361. } else
  5362. if (IsPointerAttr)
  5363. mismatch = !isLayoutCompatible(Context,
  5364. ArgumentType->getPointeeType(),
  5365. RequiredType->getPointeeType());
  5366. else
  5367. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  5368. if (mismatch)
  5369. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  5370. << ArgumentType << ArgumentKind->getName()
  5371. << TypeInfo.LayoutCompatible << RequiredType
  5372. << ArgumentExpr->getSourceRange()
  5373. << TypeTagExpr->getSourceRange();
  5374. }