SemaChecking.cpp 203 KB

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