CGExprScalar.cpp 182 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708
  1. //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGCleanup.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CodeGenFunction.h"
  17. #include "CodeGenModule.h"
  18. #include "ConstantEmitter.h"
  19. #include "TargetInfo.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/RecordLayout.h"
  24. #include "clang/AST/StmtVisitor.h"
  25. #include "clang/Basic/CodeGenOptions.h"
  26. #include "clang/Basic/FixedPoint.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "llvm/ADT/Optional.h"
  29. #include "llvm/IR/CFG.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/Function.h"
  33. #include "llvm/IR/GetElementPtrTypeIterator.h"
  34. #include "llvm/IR/GlobalVariable.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/Module.h"
  37. #include <cstdarg>
  38. using namespace clang;
  39. using namespace CodeGen;
  40. using llvm::Value;
  41. //===----------------------------------------------------------------------===//
  42. // Scalar Expression Emitter
  43. //===----------------------------------------------------------------------===//
  44. namespace {
  45. /// Determine whether the given binary operation may overflow.
  46. /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
  47. /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
  48. /// the returned overflow check is precise. The returned value is 'true' for
  49. /// all other opcodes, to be conservative.
  50. bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
  51. BinaryOperator::Opcode Opcode, bool Signed,
  52. llvm::APInt &Result) {
  53. // Assume overflow is possible, unless we can prove otherwise.
  54. bool Overflow = true;
  55. const auto &LHSAP = LHS->getValue();
  56. const auto &RHSAP = RHS->getValue();
  57. if (Opcode == BO_Add) {
  58. if (Signed)
  59. Result = LHSAP.sadd_ov(RHSAP, Overflow);
  60. else
  61. Result = LHSAP.uadd_ov(RHSAP, Overflow);
  62. } else if (Opcode == BO_Sub) {
  63. if (Signed)
  64. Result = LHSAP.ssub_ov(RHSAP, Overflow);
  65. else
  66. Result = LHSAP.usub_ov(RHSAP, Overflow);
  67. } else if (Opcode == BO_Mul) {
  68. if (Signed)
  69. Result = LHSAP.smul_ov(RHSAP, Overflow);
  70. else
  71. Result = LHSAP.umul_ov(RHSAP, Overflow);
  72. } else if (Opcode == BO_Div || Opcode == BO_Rem) {
  73. if (Signed && !RHS->isZero())
  74. Result = LHSAP.sdiv_ov(RHSAP, Overflow);
  75. else
  76. return false;
  77. }
  78. return Overflow;
  79. }
  80. struct BinOpInfo {
  81. Value *LHS;
  82. Value *RHS;
  83. QualType Ty; // Computation Type.
  84. BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
  85. FPOptions FPFeatures;
  86. const Expr *E; // Entire expr, for error unsupported. May not be binop.
  87. /// Check if the binop can result in integer overflow.
  88. bool mayHaveIntegerOverflow() const {
  89. // Without constant input, we can't rule out overflow.
  90. auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
  91. auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
  92. if (!LHSCI || !RHSCI)
  93. return true;
  94. llvm::APInt Result;
  95. return ::mayHaveIntegerOverflow(
  96. LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
  97. }
  98. /// Check if the binop computes a division or a remainder.
  99. bool isDivremOp() const {
  100. return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
  101. Opcode == BO_RemAssign;
  102. }
  103. /// Check if the binop can result in an integer division by zero.
  104. bool mayHaveIntegerDivisionByZero() const {
  105. if (isDivremOp())
  106. if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
  107. return CI->isZero();
  108. return true;
  109. }
  110. /// Check if the binop can result in a float division by zero.
  111. bool mayHaveFloatDivisionByZero() const {
  112. if (isDivremOp())
  113. if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
  114. return CFP->isZero();
  115. return true;
  116. }
  117. /// Check if either operand is a fixed point type or integer type, with at
  118. /// least one being a fixed point type. In any case, this
  119. /// operation did not follow usual arithmetic conversion and both operands may
  120. /// not be the same.
  121. bool isFixedPointBinOp() const {
  122. // We cannot simply check the result type since comparison operations return
  123. // an int.
  124. if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
  125. QualType LHSType = BinOp->getLHS()->getType();
  126. QualType RHSType = BinOp->getRHS()->getType();
  127. return LHSType->isFixedPointType() || RHSType->isFixedPointType();
  128. }
  129. return false;
  130. }
  131. };
  132. static bool MustVisitNullValue(const Expr *E) {
  133. // If a null pointer expression's type is the C++0x nullptr_t, then
  134. // it's not necessarily a simple constant and it must be evaluated
  135. // for its potential side effects.
  136. return E->getType()->isNullPtrType();
  137. }
  138. /// If \p E is a widened promoted integer, get its base (unpromoted) type.
  139. static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
  140. const Expr *E) {
  141. const Expr *Base = E->IgnoreImpCasts();
  142. if (E == Base)
  143. return llvm::None;
  144. QualType BaseTy = Base->getType();
  145. if (!BaseTy->isPromotableIntegerType() ||
  146. Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
  147. return llvm::None;
  148. return BaseTy;
  149. }
  150. /// Check if \p E is a widened promoted integer.
  151. static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
  152. return getUnwidenedIntegerType(Ctx, E).hasValue();
  153. }
  154. /// Check if we can skip the overflow check for \p Op.
  155. static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
  156. assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
  157. "Expected a unary or binary operator");
  158. // If the binop has constant inputs and we can prove there is no overflow,
  159. // we can elide the overflow check.
  160. if (!Op.mayHaveIntegerOverflow())
  161. return true;
  162. // If a unary op has a widened operand, the op cannot overflow.
  163. if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
  164. return !UO->canOverflow();
  165. // We usually don't need overflow checks for binops with widened operands.
  166. // Multiplication with promoted unsigned operands is a special case.
  167. const auto *BO = cast<BinaryOperator>(Op.E);
  168. auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
  169. if (!OptionalLHSTy)
  170. return false;
  171. auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
  172. if (!OptionalRHSTy)
  173. return false;
  174. QualType LHSTy = *OptionalLHSTy;
  175. QualType RHSTy = *OptionalRHSTy;
  176. // This is the simple case: binops without unsigned multiplication, and with
  177. // widened operands. No overflow check is needed here.
  178. if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
  179. !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
  180. return true;
  181. // For unsigned multiplication the overflow check can be elided if either one
  182. // of the unpromoted types are less than half the size of the promoted type.
  183. unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
  184. return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
  185. (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
  186. }
  187. /// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions.
  188. static void updateFastMathFlags(llvm::FastMathFlags &FMF,
  189. FPOptions FPFeatures) {
  190. FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
  191. }
  192. /// Propagate fast-math flags from \p Op to the instruction in \p V.
  193. static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) {
  194. if (auto *I = dyn_cast<llvm::Instruction>(V)) {
  195. llvm::FastMathFlags FMF = I->getFastMathFlags();
  196. updateFastMathFlags(FMF, Op.FPFeatures);
  197. I->setFastMathFlags(FMF);
  198. }
  199. return V;
  200. }
  201. class ScalarExprEmitter
  202. : public StmtVisitor<ScalarExprEmitter, Value*> {
  203. CodeGenFunction &CGF;
  204. CGBuilderTy &Builder;
  205. bool IgnoreResultAssign;
  206. llvm::LLVMContext &VMContext;
  207. public:
  208. ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
  209. : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
  210. VMContext(cgf.getLLVMContext()) {
  211. }
  212. //===--------------------------------------------------------------------===//
  213. // Utilities
  214. //===--------------------------------------------------------------------===//
  215. bool TestAndClearIgnoreResultAssign() {
  216. bool I = IgnoreResultAssign;
  217. IgnoreResultAssign = false;
  218. return I;
  219. }
  220. llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
  221. LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
  222. LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
  223. return CGF.EmitCheckedLValue(E, TCK);
  224. }
  225. void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
  226. const BinOpInfo &Info);
  227. Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  228. return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
  229. }
  230. void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
  231. const AlignValueAttr *AVAttr = nullptr;
  232. if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  233. const ValueDecl *VD = DRE->getDecl();
  234. if (VD->getType()->isReferenceType()) {
  235. if (const auto *TTy =
  236. dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
  237. AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
  238. } else {
  239. // Assumptions for function parameters are emitted at the start of the
  240. // function, so there is no need to repeat that here,
  241. // unless the alignment-assumption sanitizer is enabled,
  242. // then we prefer the assumption over alignment attribute
  243. // on IR function param.
  244. if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
  245. return;
  246. AVAttr = VD->getAttr<AlignValueAttr>();
  247. }
  248. }
  249. if (!AVAttr)
  250. if (const auto *TTy =
  251. dyn_cast<TypedefType>(E->getType()))
  252. AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
  253. if (!AVAttr)
  254. return;
  255. Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
  256. llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
  257. CGF.EmitAlignmentAssumption(V, E, AVAttr->getLocation(),
  258. AlignmentCI->getZExtValue());
  259. }
  260. /// EmitLoadOfLValue - Given an expression with complex type that represents a
  261. /// value l-value, this method emits the address of the l-value, then loads
  262. /// and returns the result.
  263. Value *EmitLoadOfLValue(const Expr *E) {
  264. Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
  265. E->getExprLoc());
  266. EmitLValueAlignmentAssumption(E, V);
  267. return V;
  268. }
  269. /// EmitConversionToBool - Convert the specified expression value to a
  270. /// boolean (i1) truth value. This is equivalent to "Val != 0".
  271. Value *EmitConversionToBool(Value *Src, QualType DstTy);
  272. /// Emit a check that a conversion from a floating-point type does not
  273. /// overflow.
  274. void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
  275. Value *Src, QualType SrcType, QualType DstType,
  276. llvm::Type *DstTy, SourceLocation Loc);
  277. /// Known implicit conversion check kinds.
  278. /// Keep in sync with the enum of the same name in ubsan_handlers.h
  279. enum ImplicitConversionCheckKind : unsigned char {
  280. ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
  281. ICCK_UnsignedIntegerTruncation = 1,
  282. ICCK_SignedIntegerTruncation = 2,
  283. ICCK_IntegerSignChange = 3,
  284. ICCK_SignedIntegerTruncationOrSignChange = 4,
  285. };
  286. /// Emit a check that an [implicit] truncation of an integer does not
  287. /// discard any bits. It is not UB, so we use the value after truncation.
  288. void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
  289. QualType DstType, SourceLocation Loc);
  290. /// Emit a check that an [implicit] conversion of an integer does not change
  291. /// the sign of the value. It is not UB, so we use the value after conversion.
  292. /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
  293. void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
  294. QualType DstType, SourceLocation Loc);
  295. /// Emit a conversion from the specified type to the specified destination
  296. /// type, both of which are LLVM scalar types.
  297. struct ScalarConversionOpts {
  298. bool TreatBooleanAsSigned;
  299. bool EmitImplicitIntegerTruncationChecks;
  300. bool EmitImplicitIntegerSignChangeChecks;
  301. ScalarConversionOpts()
  302. : TreatBooleanAsSigned(false),
  303. EmitImplicitIntegerTruncationChecks(false),
  304. EmitImplicitIntegerSignChangeChecks(false) {}
  305. ScalarConversionOpts(clang::SanitizerSet SanOpts)
  306. : TreatBooleanAsSigned(false),
  307. EmitImplicitIntegerTruncationChecks(
  308. SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
  309. EmitImplicitIntegerSignChangeChecks(
  310. SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
  311. };
  312. Value *
  313. EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
  314. SourceLocation Loc,
  315. ScalarConversionOpts Opts = ScalarConversionOpts());
  316. /// Convert between either a fixed point and other fixed point or fixed point
  317. /// and an integer.
  318. Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
  319. SourceLocation Loc);
  320. Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema,
  321. FixedPointSemantics &DstFixedSema,
  322. SourceLocation Loc,
  323. bool DstIsInteger = false);
  324. /// Emit a conversion from the specified complex type to the specified
  325. /// destination type, where the destination type is an LLVM scalar type.
  326. Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
  327. QualType SrcTy, QualType DstTy,
  328. SourceLocation Loc);
  329. /// EmitNullValue - Emit a value that corresponds to null for the given type.
  330. Value *EmitNullValue(QualType Ty);
  331. /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
  332. Value *EmitFloatToBoolConversion(Value *V) {
  333. // Compare against 0.0 for fp scalars.
  334. llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
  335. return Builder.CreateFCmpUNE(V, Zero, "tobool");
  336. }
  337. /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
  338. Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
  339. Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
  340. return Builder.CreateICmpNE(V, Zero, "tobool");
  341. }
  342. Value *EmitIntToBoolConversion(Value *V) {
  343. // Because of the type rules of C, we often end up computing a
  344. // logical value, then zero extending it to int, then wanting it
  345. // as a logical value again. Optimize this common case.
  346. if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
  347. if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
  348. Value *Result = ZI->getOperand(0);
  349. // If there aren't any more uses, zap the instruction to save space.
  350. // Note that there can be more uses, for example if this
  351. // is the result of an assignment.
  352. if (ZI->use_empty())
  353. ZI->eraseFromParent();
  354. return Result;
  355. }
  356. }
  357. return Builder.CreateIsNotNull(V, "tobool");
  358. }
  359. //===--------------------------------------------------------------------===//
  360. // Visitor Methods
  361. //===--------------------------------------------------------------------===//
  362. Value *Visit(Expr *E) {
  363. ApplyDebugLocation DL(CGF, E);
  364. return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
  365. }
  366. Value *VisitStmt(Stmt *S) {
  367. S->dump(CGF.getContext().getSourceManager());
  368. llvm_unreachable("Stmt can't have complex result type!");
  369. }
  370. Value *VisitExpr(Expr *S);
  371. Value *VisitConstantExpr(ConstantExpr *E) {
  372. return Visit(E->getSubExpr());
  373. }
  374. Value *VisitParenExpr(ParenExpr *PE) {
  375. return Visit(PE->getSubExpr());
  376. }
  377. Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
  378. return Visit(E->getReplacement());
  379. }
  380. Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  381. return Visit(GE->getResultExpr());
  382. }
  383. Value *VisitCoawaitExpr(CoawaitExpr *S) {
  384. return CGF.EmitCoawaitExpr(*S).getScalarVal();
  385. }
  386. Value *VisitCoyieldExpr(CoyieldExpr *S) {
  387. return CGF.EmitCoyieldExpr(*S).getScalarVal();
  388. }
  389. Value *VisitUnaryCoawait(const UnaryOperator *E) {
  390. return Visit(E->getSubExpr());
  391. }
  392. // Leaves.
  393. Value *VisitIntegerLiteral(const IntegerLiteral *E) {
  394. return Builder.getInt(E->getValue());
  395. }
  396. Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
  397. return Builder.getInt(E->getValue());
  398. }
  399. Value *VisitFloatingLiteral(const FloatingLiteral *E) {
  400. return llvm::ConstantFP::get(VMContext, E->getValue());
  401. }
  402. Value *VisitCharacterLiteral(const CharacterLiteral *E) {
  403. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  404. }
  405. Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  406. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  407. }
  408. Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  409. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  410. }
  411. Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  412. return EmitNullValue(E->getType());
  413. }
  414. Value *VisitGNUNullExpr(const GNUNullExpr *E) {
  415. return EmitNullValue(E->getType());
  416. }
  417. Value *VisitOffsetOfExpr(OffsetOfExpr *E);
  418. Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  419. Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
  420. llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
  421. return Builder.CreateBitCast(V, ConvertType(E->getType()));
  422. }
  423. Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
  424. return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
  425. }
  426. Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  427. return CGF.EmitPseudoObjectRValue(E).getScalarVal();
  428. }
  429. Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
  430. if (E->isGLValue())
  431. return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
  432. E->getExprLoc());
  433. // Otherwise, assume the mapping is the scalar directly.
  434. return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
  435. }
  436. // l-values.
  437. Value *VisitDeclRefExpr(DeclRefExpr *E) {
  438. if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
  439. return CGF.emitScalarConstant(Constant, E);
  440. return EmitLoadOfLValue(E);
  441. }
  442. Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
  443. return CGF.EmitObjCSelectorExpr(E);
  444. }
  445. Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
  446. return CGF.EmitObjCProtocolExpr(E);
  447. }
  448. Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  449. return EmitLoadOfLValue(E);
  450. }
  451. Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
  452. if (E->getMethodDecl() &&
  453. E->getMethodDecl()->getReturnType()->isReferenceType())
  454. return EmitLoadOfLValue(E);
  455. return CGF.EmitObjCMessageExpr(E).getScalarVal();
  456. }
  457. Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
  458. LValue LV = CGF.EmitObjCIsaExpr(E);
  459. Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
  460. return V;
  461. }
  462. Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
  463. VersionTuple Version = E->getVersion();
  464. // If we're checking for a platform older than our minimum deployment
  465. // target, we can fold the check away.
  466. if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
  467. return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
  468. Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
  469. llvm::Value *Args[] = {
  470. llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
  471. llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
  472. llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
  473. };
  474. return CGF.EmitBuiltinAvailable(Args);
  475. }
  476. Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
  477. Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
  478. Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
  479. Value *VisitMemberExpr(MemberExpr *E);
  480. Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
  481. Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  482. return EmitLoadOfLValue(E);
  483. }
  484. Value *VisitInitListExpr(InitListExpr *E);
  485. Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
  486. assert(CGF.getArrayInitIndex() &&
  487. "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
  488. return CGF.getArrayInitIndex();
  489. }
  490. Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  491. return EmitNullValue(E->getType());
  492. }
  493. Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
  494. CGF.CGM.EmitExplicitCastExprType(E, &CGF);
  495. return VisitCastExpr(E);
  496. }
  497. Value *VisitCastExpr(CastExpr *E);
  498. Value *VisitCallExpr(const CallExpr *E) {
  499. if (E->getCallReturnType(CGF.getContext())->isReferenceType())
  500. return EmitLoadOfLValue(E);
  501. Value *V = CGF.EmitCallExpr(E).getScalarVal();
  502. EmitLValueAlignmentAssumption(E, V);
  503. return V;
  504. }
  505. Value *VisitStmtExpr(const StmtExpr *E);
  506. // Unary Operators.
  507. Value *VisitUnaryPostDec(const UnaryOperator *E) {
  508. LValue LV = EmitLValue(E->getSubExpr());
  509. return EmitScalarPrePostIncDec(E, LV, false, false);
  510. }
  511. Value *VisitUnaryPostInc(const UnaryOperator *E) {
  512. LValue LV = EmitLValue(E->getSubExpr());
  513. return EmitScalarPrePostIncDec(E, LV, true, false);
  514. }
  515. Value *VisitUnaryPreDec(const UnaryOperator *E) {
  516. LValue LV = EmitLValue(E->getSubExpr());
  517. return EmitScalarPrePostIncDec(E, LV, false, true);
  518. }
  519. Value *VisitUnaryPreInc(const UnaryOperator *E) {
  520. LValue LV = EmitLValue(E->getSubExpr());
  521. return EmitScalarPrePostIncDec(E, LV, true, true);
  522. }
  523. llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
  524. llvm::Value *InVal,
  525. bool IsInc);
  526. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  527. bool isInc, bool isPre);
  528. Value *VisitUnaryAddrOf(const UnaryOperator *E) {
  529. if (isa<MemberPointerType>(E->getType())) // never sugared
  530. return CGF.CGM.getMemberPointerConstant(E);
  531. return EmitLValue(E->getSubExpr()).getPointer();
  532. }
  533. Value *VisitUnaryDeref(const UnaryOperator *E) {
  534. if (E->getType()->isVoidType())
  535. return Visit(E->getSubExpr()); // the actual value should be unused
  536. return EmitLoadOfLValue(E);
  537. }
  538. Value *VisitUnaryPlus(const UnaryOperator *E) {
  539. // This differs from gcc, though, most likely due to a bug in gcc.
  540. TestAndClearIgnoreResultAssign();
  541. return Visit(E->getSubExpr());
  542. }
  543. Value *VisitUnaryMinus (const UnaryOperator *E);
  544. Value *VisitUnaryNot (const UnaryOperator *E);
  545. Value *VisitUnaryLNot (const UnaryOperator *E);
  546. Value *VisitUnaryReal (const UnaryOperator *E);
  547. Value *VisitUnaryImag (const UnaryOperator *E);
  548. Value *VisitUnaryExtension(const UnaryOperator *E) {
  549. return Visit(E->getSubExpr());
  550. }
  551. // C++
  552. Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
  553. return EmitLoadOfLValue(E);
  554. }
  555. Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
  556. auto &Ctx = CGF.getContext();
  557. APValue Evaluated =
  558. SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
  559. return ConstantEmitter(CGF.CGM, &CGF)
  560. .emitAbstract(SLE->getLocation(), Evaluated, SLE->getType());
  561. }
  562. Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  563. CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
  564. return Visit(DAE->getExpr());
  565. }
  566. Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
  567. CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
  568. return Visit(DIE->getExpr());
  569. }
  570. Value *VisitCXXThisExpr(CXXThisExpr *TE) {
  571. return CGF.LoadCXXThis();
  572. }
  573. Value *VisitExprWithCleanups(ExprWithCleanups *E);
  574. Value *VisitCXXNewExpr(const CXXNewExpr *E) {
  575. return CGF.EmitCXXNewExpr(E);
  576. }
  577. Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  578. CGF.EmitCXXDeleteExpr(E);
  579. return nullptr;
  580. }
  581. Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
  582. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  583. }
  584. Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  585. return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
  586. }
  587. Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  588. return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
  589. }
  590. Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
  591. // C++ [expr.pseudo]p1:
  592. // The result shall only be used as the operand for the function call
  593. // operator (), and the result of such a call has type void. The only
  594. // effect is the evaluation of the postfix-expression before the dot or
  595. // arrow.
  596. CGF.EmitScalarExpr(E->getBase());
  597. return nullptr;
  598. }
  599. Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  600. return EmitNullValue(E->getType());
  601. }
  602. Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
  603. CGF.EmitCXXThrowExpr(E);
  604. return nullptr;
  605. }
  606. Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  607. return Builder.getInt1(E->getValue());
  608. }
  609. // Binary Operators.
  610. Value *EmitMul(const BinOpInfo &Ops) {
  611. if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
  612. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  613. case LangOptions::SOB_Defined:
  614. return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
  615. case LangOptions::SOB_Undefined:
  616. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  617. return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
  618. LLVM_FALLTHROUGH;
  619. case LangOptions::SOB_Trapping:
  620. if (CanElideOverflowCheck(CGF.getContext(), Ops))
  621. return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
  622. return EmitOverflowCheckedBinOp(Ops);
  623. }
  624. }
  625. if (Ops.Ty->isUnsignedIntegerType() &&
  626. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  627. !CanElideOverflowCheck(CGF.getContext(), Ops))
  628. return EmitOverflowCheckedBinOp(Ops);
  629. if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
  630. Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
  631. return propagateFMFlags(V, Ops);
  632. }
  633. return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
  634. }
  635. /// Create a binary op that checks for overflow.
  636. /// Currently only supports +, - and *.
  637. Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
  638. // Check for undefined division and modulus behaviors.
  639. void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
  640. llvm::Value *Zero,bool isDiv);
  641. // Common helper for getting how wide LHS of shift is.
  642. static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
  643. Value *EmitDiv(const BinOpInfo &Ops);
  644. Value *EmitRem(const BinOpInfo &Ops);
  645. Value *EmitAdd(const BinOpInfo &Ops);
  646. Value *EmitSub(const BinOpInfo &Ops);
  647. Value *EmitShl(const BinOpInfo &Ops);
  648. Value *EmitShr(const BinOpInfo &Ops);
  649. Value *EmitAnd(const BinOpInfo &Ops) {
  650. return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
  651. }
  652. Value *EmitXor(const BinOpInfo &Ops) {
  653. return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
  654. }
  655. Value *EmitOr (const BinOpInfo &Ops) {
  656. return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
  657. }
  658. // Helper functions for fixed point binary operations.
  659. Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
  660. BinOpInfo EmitBinOps(const BinaryOperator *E);
  661. LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
  662. Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
  663. Value *&Result);
  664. Value *EmitCompoundAssign(const CompoundAssignOperator *E,
  665. Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
  666. // Binary operators and binary compound assignment operators.
  667. #define HANDLEBINOP(OP) \
  668. Value *VisitBin ## OP(const BinaryOperator *E) { \
  669. return Emit ## OP(EmitBinOps(E)); \
  670. } \
  671. Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
  672. return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
  673. }
  674. HANDLEBINOP(Mul)
  675. HANDLEBINOP(Div)
  676. HANDLEBINOP(Rem)
  677. HANDLEBINOP(Add)
  678. HANDLEBINOP(Sub)
  679. HANDLEBINOP(Shl)
  680. HANDLEBINOP(Shr)
  681. HANDLEBINOP(And)
  682. HANDLEBINOP(Xor)
  683. HANDLEBINOP(Or)
  684. #undef HANDLEBINOP
  685. // Comparisons.
  686. Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
  687. llvm::CmpInst::Predicate SICmpOpc,
  688. llvm::CmpInst::Predicate FCmpOpc);
  689. #define VISITCOMP(CODE, UI, SI, FP) \
  690. Value *VisitBin##CODE(const BinaryOperator *E) { \
  691. return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
  692. llvm::FCmpInst::FP); }
  693. VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
  694. VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
  695. VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
  696. VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
  697. VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
  698. VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
  699. #undef VISITCOMP
  700. Value *VisitBinAssign (const BinaryOperator *E);
  701. Value *VisitBinLAnd (const BinaryOperator *E);
  702. Value *VisitBinLOr (const BinaryOperator *E);
  703. Value *VisitBinComma (const BinaryOperator *E);
  704. Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
  705. Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
  706. // Other Operators.
  707. Value *VisitBlockExpr(const BlockExpr *BE);
  708. Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
  709. Value *VisitChooseExpr(ChooseExpr *CE);
  710. Value *VisitVAArgExpr(VAArgExpr *VE);
  711. Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
  712. return CGF.EmitObjCStringLiteral(E);
  713. }
  714. Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
  715. return CGF.EmitObjCBoxedExpr(E);
  716. }
  717. Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
  718. return CGF.EmitObjCArrayLiteral(E);
  719. }
  720. Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
  721. return CGF.EmitObjCDictionaryLiteral(E);
  722. }
  723. Value *VisitAsTypeExpr(AsTypeExpr *CE);
  724. Value *VisitAtomicExpr(AtomicExpr *AE);
  725. };
  726. } // end anonymous namespace.
  727. //===----------------------------------------------------------------------===//
  728. // Utilities
  729. //===----------------------------------------------------------------------===//
  730. /// EmitConversionToBool - Convert the specified expression value to a
  731. /// boolean (i1) truth value. This is equivalent to "Val != 0".
  732. Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
  733. assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
  734. if (SrcType->isRealFloatingType())
  735. return EmitFloatToBoolConversion(Src);
  736. if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
  737. return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
  738. assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
  739. "Unknown scalar type to convert");
  740. if (isa<llvm::IntegerType>(Src->getType()))
  741. return EmitIntToBoolConversion(Src);
  742. assert(isa<llvm::PointerType>(Src->getType()));
  743. return EmitPointerToBoolConversion(Src, SrcType);
  744. }
  745. void ScalarExprEmitter::EmitFloatConversionCheck(
  746. Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
  747. QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
  748. assert(SrcType->isFloatingType() && "not a conversion from floating point");
  749. if (!isa<llvm::IntegerType>(DstTy))
  750. return;
  751. CodeGenFunction::SanitizerScope SanScope(&CGF);
  752. using llvm::APFloat;
  753. using llvm::APSInt;
  754. llvm::Value *Check = nullptr;
  755. const llvm::fltSemantics &SrcSema =
  756. CGF.getContext().getFloatTypeSemantics(OrigSrcType);
  757. // Floating-point to integer. This has undefined behavior if the source is
  758. // +-Inf, NaN, or doesn't fit into the destination type (after truncation
  759. // to an integer).
  760. unsigned Width = CGF.getContext().getIntWidth(DstType);
  761. bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
  762. APSInt Min = APSInt::getMinValue(Width, Unsigned);
  763. APFloat MinSrc(SrcSema, APFloat::uninitialized);
  764. if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
  765. APFloat::opOverflow)
  766. // Don't need an overflow check for lower bound. Just check for
  767. // -Inf/NaN.
  768. MinSrc = APFloat::getInf(SrcSema, true);
  769. else
  770. // Find the largest value which is too small to represent (before
  771. // truncation toward zero).
  772. MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
  773. APSInt Max = APSInt::getMaxValue(Width, Unsigned);
  774. APFloat MaxSrc(SrcSema, APFloat::uninitialized);
  775. if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
  776. APFloat::opOverflow)
  777. // Don't need an overflow check for upper bound. Just check for
  778. // +Inf/NaN.
  779. MaxSrc = APFloat::getInf(SrcSema, false);
  780. else
  781. // Find the smallest value which is too large to represent (before
  782. // truncation toward zero).
  783. MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
  784. // If we're converting from __half, convert the range to float to match
  785. // the type of src.
  786. if (OrigSrcType->isHalfType()) {
  787. const llvm::fltSemantics &Sema =
  788. CGF.getContext().getFloatTypeSemantics(SrcType);
  789. bool IsInexact;
  790. MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
  791. MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
  792. }
  793. llvm::Value *GE =
  794. Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
  795. llvm::Value *LE =
  796. Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
  797. Check = Builder.CreateAnd(GE, LE);
  798. llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
  799. CGF.EmitCheckTypeDescriptor(OrigSrcType),
  800. CGF.EmitCheckTypeDescriptor(DstType)};
  801. CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
  802. SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
  803. }
  804. // Should be called within CodeGenFunction::SanitizerScope RAII scope.
  805. // Returns 'i1 false' when the truncation Src -> Dst was lossy.
  806. static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  807. std::pair<llvm::Value *, SanitizerMask>>
  808. EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
  809. QualType DstType, CGBuilderTy &Builder) {
  810. llvm::Type *SrcTy = Src->getType();
  811. llvm::Type *DstTy = Dst->getType();
  812. (void)DstTy; // Only used in assert()
  813. // This should be truncation of integral types.
  814. assert(Src != Dst);
  815. assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
  816. assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
  817. "non-integer llvm type");
  818. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  819. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  820. // If both (src and dst) types are unsigned, then it's an unsigned truncation.
  821. // Else, it is a signed truncation.
  822. ScalarExprEmitter::ImplicitConversionCheckKind Kind;
  823. SanitizerMask Mask;
  824. if (!SrcSigned && !DstSigned) {
  825. Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
  826. Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
  827. } else {
  828. Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
  829. Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
  830. }
  831. llvm::Value *Check = nullptr;
  832. // 1. Extend the truncated value back to the same width as the Src.
  833. Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
  834. // 2. Equality-compare with the original source value
  835. Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
  836. // If the comparison result is 'i1 false', then the truncation was lossy.
  837. return std::make_pair(Kind, std::make_pair(Check, Mask));
  838. }
  839. void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
  840. Value *Dst, QualType DstType,
  841. SourceLocation Loc) {
  842. if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
  843. return;
  844. // We only care about int->int conversions here.
  845. // We ignore conversions to/from pointer and/or bool.
  846. if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
  847. return;
  848. unsigned SrcBits = Src->getType()->getScalarSizeInBits();
  849. unsigned DstBits = Dst->getType()->getScalarSizeInBits();
  850. // This must be truncation. Else we do not care.
  851. if (SrcBits <= DstBits)
  852. return;
  853. assert(!DstType->isBooleanType() && "we should not get here with booleans.");
  854. // If the integer sign change sanitizer is enabled,
  855. // and we are truncating from larger unsigned type to smaller signed type,
  856. // let that next sanitizer deal with it.
  857. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  858. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  859. if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
  860. (!SrcSigned && DstSigned))
  861. return;
  862. CodeGenFunction::SanitizerScope SanScope(&CGF);
  863. std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  864. std::pair<llvm::Value *, SanitizerMask>>
  865. Check =
  866. EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
  867. // If the comparison result is 'i1 false', then the truncation was lossy.
  868. // Do we care about this type of truncation?
  869. if (!CGF.SanOpts.has(Check.second.second))
  870. return;
  871. llvm::Constant *StaticArgs[] = {
  872. CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
  873. CGF.EmitCheckTypeDescriptor(DstType),
  874. llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
  875. CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
  876. {Src, Dst});
  877. }
  878. // Should be called within CodeGenFunction::SanitizerScope RAII scope.
  879. // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
  880. static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  881. std::pair<llvm::Value *, SanitizerMask>>
  882. EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
  883. QualType DstType, CGBuilderTy &Builder) {
  884. llvm::Type *SrcTy = Src->getType();
  885. llvm::Type *DstTy = Dst->getType();
  886. assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
  887. "non-integer llvm type");
  888. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  889. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  890. (void)SrcSigned; // Only used in assert()
  891. (void)DstSigned; // Only used in assert()
  892. unsigned SrcBits = SrcTy->getScalarSizeInBits();
  893. unsigned DstBits = DstTy->getScalarSizeInBits();
  894. (void)SrcBits; // Only used in assert()
  895. (void)DstBits; // Only used in assert()
  896. assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
  897. "either the widths should be different, or the signednesses.");
  898. // NOTE: zero value is considered to be non-negative.
  899. auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
  900. const char *Name) -> Value * {
  901. // Is this value a signed type?
  902. bool VSigned = VType->isSignedIntegerOrEnumerationType();
  903. llvm::Type *VTy = V->getType();
  904. if (!VSigned) {
  905. // If the value is unsigned, then it is never negative.
  906. // FIXME: can we encounter non-scalar VTy here?
  907. return llvm::ConstantInt::getFalse(VTy->getContext());
  908. }
  909. // Get the zero of the same type with which we will be comparing.
  910. llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
  911. // %V.isnegative = icmp slt %V, 0
  912. // I.e is %V *strictly* less than zero, does it have negative value?
  913. return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
  914. llvm::Twine(Name) + "." + V->getName() +
  915. ".negativitycheck");
  916. };
  917. // 1. Was the old Value negative?
  918. llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
  919. // 2. Is the new Value negative?
  920. llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
  921. // 3. Now, was the 'negativity status' preserved during the conversion?
  922. // NOTE: conversion from negative to zero is considered to change the sign.
  923. // (We want to get 'false' when the conversion changed the sign)
  924. // So we should just equality-compare the negativity statuses.
  925. llvm::Value *Check = nullptr;
  926. Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
  927. // If the comparison result is 'false', then the conversion changed the sign.
  928. return std::make_pair(
  929. ScalarExprEmitter::ICCK_IntegerSignChange,
  930. std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
  931. }
  932. void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
  933. Value *Dst, QualType DstType,
  934. SourceLocation Loc) {
  935. if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
  936. return;
  937. llvm::Type *SrcTy = Src->getType();
  938. llvm::Type *DstTy = Dst->getType();
  939. // We only care about int->int conversions here.
  940. // We ignore conversions to/from pointer and/or bool.
  941. if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
  942. return;
  943. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  944. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  945. unsigned SrcBits = SrcTy->getScalarSizeInBits();
  946. unsigned DstBits = DstTy->getScalarSizeInBits();
  947. // Now, we do not need to emit the check in *all* of the cases.
  948. // We can avoid emitting it in some obvious cases where it would have been
  949. // dropped by the opt passes (instcombine) always anyways.
  950. // If it's a cast between effectively the same type, no check.
  951. // NOTE: this is *not* equivalent to checking the canonical types.
  952. if (SrcSigned == DstSigned && SrcBits == DstBits)
  953. return;
  954. // At least one of the values needs to have signed type.
  955. // If both are unsigned, then obviously, neither of them can be negative.
  956. if (!SrcSigned && !DstSigned)
  957. return;
  958. // If the conversion is to *larger* *signed* type, then no check is needed.
  959. // Because either sign-extension happens (so the sign will remain),
  960. // or zero-extension will happen (the sign bit will be zero.)
  961. if ((DstBits > SrcBits) && DstSigned)
  962. return;
  963. if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
  964. (SrcBits > DstBits) && SrcSigned) {
  965. // If the signed integer truncation sanitizer is enabled,
  966. // and this is a truncation from signed type, then no check is needed.
  967. // Because here sign change check is interchangeable with truncation check.
  968. return;
  969. }
  970. // That's it. We can't rule out any more cases with the data we have.
  971. CodeGenFunction::SanitizerScope SanScope(&CGF);
  972. std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  973. std::pair<llvm::Value *, SanitizerMask>>
  974. Check;
  975. // Each of these checks needs to return 'false' when an issue was detected.
  976. ImplicitConversionCheckKind CheckKind;
  977. llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
  978. // So we can 'and' all the checks together, and still get 'false',
  979. // if at least one of the checks detected an issue.
  980. Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
  981. CheckKind = Check.first;
  982. Checks.emplace_back(Check.second);
  983. if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
  984. (SrcBits > DstBits) && !SrcSigned && DstSigned) {
  985. // If the signed integer truncation sanitizer was enabled,
  986. // and we are truncating from larger unsigned type to smaller signed type,
  987. // let's handle the case we skipped in that check.
  988. Check =
  989. EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
  990. CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
  991. Checks.emplace_back(Check.second);
  992. // If the comparison result is 'i1 false', then the truncation was lossy.
  993. }
  994. llvm::Constant *StaticArgs[] = {
  995. CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
  996. CGF.EmitCheckTypeDescriptor(DstType),
  997. llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
  998. // EmitCheck() will 'and' all the checks together.
  999. CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
  1000. {Src, Dst});
  1001. }
  1002. /// Emit a conversion from the specified type to the specified destination type,
  1003. /// both of which are LLVM scalar types.
  1004. Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
  1005. QualType DstType,
  1006. SourceLocation Loc,
  1007. ScalarConversionOpts Opts) {
  1008. // All conversions involving fixed point types should be handled by the
  1009. // EmitFixedPoint family functions. This is done to prevent bloating up this
  1010. // function more, and although fixed point numbers are represented by
  1011. // integers, we do not want to follow any logic that assumes they should be
  1012. // treated as integers.
  1013. // TODO(leonardchan): When necessary, add another if statement checking for
  1014. // conversions to fixed point types from other types.
  1015. if (SrcType->isFixedPointType()) {
  1016. if (DstType->isBooleanType())
  1017. // It is important that we check this before checking if the dest type is
  1018. // an integer because booleans are technically integer types.
  1019. // We do not need to check the padding bit on unsigned types if unsigned
  1020. // padding is enabled because overflow into this bit is undefined
  1021. // behavior.
  1022. return Builder.CreateIsNotNull(Src, "tobool");
  1023. if (DstType->isFixedPointType() || DstType->isIntegerType())
  1024. return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
  1025. llvm_unreachable(
  1026. "Unhandled scalar conversion from a fixed point type to another type.");
  1027. } else if (DstType->isFixedPointType()) {
  1028. if (SrcType->isIntegerType())
  1029. // This also includes converting booleans and enums to fixed point types.
  1030. return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
  1031. llvm_unreachable(
  1032. "Unhandled scalar conversion to a fixed point type from another type.");
  1033. }
  1034. QualType NoncanonicalSrcType = SrcType;
  1035. QualType NoncanonicalDstType = DstType;
  1036. SrcType = CGF.getContext().getCanonicalType(SrcType);
  1037. DstType = CGF.getContext().getCanonicalType(DstType);
  1038. if (SrcType == DstType) return Src;
  1039. if (DstType->isVoidType()) return nullptr;
  1040. llvm::Value *OrigSrc = Src;
  1041. QualType OrigSrcType = SrcType;
  1042. llvm::Type *SrcTy = Src->getType();
  1043. // Handle conversions to bool first, they are special: comparisons against 0.
  1044. if (DstType->isBooleanType())
  1045. return EmitConversionToBool(Src, SrcType);
  1046. llvm::Type *DstTy = ConvertType(DstType);
  1047. // Cast from half through float if half isn't a native type.
  1048. if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  1049. // Cast to FP using the intrinsic if the half type itself isn't supported.
  1050. if (DstTy->isFloatingPointTy()) {
  1051. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
  1052. return Builder.CreateCall(
  1053. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
  1054. Src);
  1055. } else {
  1056. // Cast to other types through float, using either the intrinsic or FPExt,
  1057. // depending on whether the half type itself is supported
  1058. // (as opposed to operations on half, available with NativeHalfType).
  1059. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  1060. Src = Builder.CreateCall(
  1061. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
  1062. CGF.CGM.FloatTy),
  1063. Src);
  1064. } else {
  1065. Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
  1066. }
  1067. SrcType = CGF.getContext().FloatTy;
  1068. SrcTy = CGF.FloatTy;
  1069. }
  1070. }
  1071. // Ignore conversions like int -> uint.
  1072. if (SrcTy == DstTy) {
  1073. if (Opts.EmitImplicitIntegerSignChangeChecks)
  1074. EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
  1075. NoncanonicalDstType, Loc);
  1076. return Src;
  1077. }
  1078. // Handle pointer conversions next: pointers can only be converted to/from
  1079. // other pointers and integers. Check for pointer types in terms of LLVM, as
  1080. // some native types (like Obj-C id) may map to a pointer type.
  1081. if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
  1082. // The source value may be an integer, or a pointer.
  1083. if (isa<llvm::PointerType>(SrcTy))
  1084. return Builder.CreateBitCast(Src, DstTy, "conv");
  1085. assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
  1086. // First, convert to the correct width so that we control the kind of
  1087. // extension.
  1088. llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
  1089. bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
  1090. llvm::Value* IntResult =
  1091. Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
  1092. // Then, cast to pointer.
  1093. return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
  1094. }
  1095. if (isa<llvm::PointerType>(SrcTy)) {
  1096. // Must be an ptr to int cast.
  1097. assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
  1098. return Builder.CreatePtrToInt(Src, DstTy, "conv");
  1099. }
  1100. // A scalar can be splatted to an extended vector of the same element type
  1101. if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
  1102. // Sema should add casts to make sure that the source expression's type is
  1103. // the same as the vector's element type (sans qualifiers)
  1104. assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
  1105. SrcType.getTypePtr() &&
  1106. "Splatted expr doesn't match with vector element type?");
  1107. // Splat the element across to all elements
  1108. unsigned NumElements = DstTy->getVectorNumElements();
  1109. return Builder.CreateVectorSplat(NumElements, Src, "splat");
  1110. }
  1111. if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
  1112. // Allow bitcast from vector to integer/fp of the same size.
  1113. unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
  1114. unsigned DstSize = DstTy->getPrimitiveSizeInBits();
  1115. if (SrcSize == DstSize)
  1116. return Builder.CreateBitCast(Src, DstTy, "conv");
  1117. // Conversions between vectors of different sizes are not allowed except
  1118. // when vectors of half are involved. Operations on storage-only half
  1119. // vectors require promoting half vector operands to float vectors and
  1120. // truncating the result, which is either an int or float vector, to a
  1121. // short or half vector.
  1122. // Source and destination are both expected to be vectors.
  1123. llvm::Type *SrcElementTy = SrcTy->getVectorElementType();
  1124. llvm::Type *DstElementTy = DstTy->getVectorElementType();
  1125. (void)DstElementTy;
  1126. assert(((SrcElementTy->isIntegerTy() &&
  1127. DstElementTy->isIntegerTy()) ||
  1128. (SrcElementTy->isFloatingPointTy() &&
  1129. DstElementTy->isFloatingPointTy())) &&
  1130. "unexpected conversion between a floating-point vector and an "
  1131. "integer vector");
  1132. // Truncate an i32 vector to an i16 vector.
  1133. if (SrcElementTy->isIntegerTy())
  1134. return Builder.CreateIntCast(Src, DstTy, false, "conv");
  1135. // Truncate a float vector to a half vector.
  1136. if (SrcSize > DstSize)
  1137. return Builder.CreateFPTrunc(Src, DstTy, "conv");
  1138. // Promote a half vector to a float vector.
  1139. return Builder.CreateFPExt(Src, DstTy, "conv");
  1140. }
  1141. // Finally, we have the arithmetic types: real int/float.
  1142. Value *Res = nullptr;
  1143. llvm::Type *ResTy = DstTy;
  1144. // An overflowing conversion has undefined behavior if either the source type
  1145. // or the destination type is a floating-point type. However, we consider the
  1146. // range of representable values for all floating-point types to be
  1147. // [-inf,+inf], so no overflow can ever happen when the destination type is a
  1148. // floating-point type.
  1149. if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
  1150. OrigSrcType->isFloatingType())
  1151. EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
  1152. Loc);
  1153. // Cast to half through float if half isn't a native type.
  1154. if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  1155. // Make sure we cast in a single step if from another FP type.
  1156. if (SrcTy->isFloatingPointTy()) {
  1157. // Use the intrinsic if the half type itself isn't supported
  1158. // (as opposed to operations on half, available with NativeHalfType).
  1159. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
  1160. return Builder.CreateCall(
  1161. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
  1162. // If the half type is supported, just use an fptrunc.
  1163. return Builder.CreateFPTrunc(Src, DstTy);
  1164. }
  1165. DstTy = CGF.FloatTy;
  1166. }
  1167. if (isa<llvm::IntegerType>(SrcTy)) {
  1168. bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
  1169. if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
  1170. InputSigned = true;
  1171. }
  1172. if (isa<llvm::IntegerType>(DstTy))
  1173. Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
  1174. else if (InputSigned)
  1175. Res = Builder.CreateSIToFP(Src, DstTy, "conv");
  1176. else
  1177. Res = Builder.CreateUIToFP(Src, DstTy, "conv");
  1178. } else if (isa<llvm::IntegerType>(DstTy)) {
  1179. assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
  1180. if (DstType->isSignedIntegerOrEnumerationType())
  1181. Res = Builder.CreateFPToSI(Src, DstTy, "conv");
  1182. else
  1183. Res = Builder.CreateFPToUI(Src, DstTy, "conv");
  1184. } else {
  1185. assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
  1186. "Unknown real conversion");
  1187. if (DstTy->getTypeID() < SrcTy->getTypeID())
  1188. Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
  1189. else
  1190. Res = Builder.CreateFPExt(Src, DstTy, "conv");
  1191. }
  1192. if (DstTy != ResTy) {
  1193. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  1194. assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
  1195. Res = Builder.CreateCall(
  1196. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
  1197. Res);
  1198. } else {
  1199. Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
  1200. }
  1201. }
  1202. if (Opts.EmitImplicitIntegerTruncationChecks)
  1203. EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
  1204. NoncanonicalDstType, Loc);
  1205. if (Opts.EmitImplicitIntegerSignChangeChecks)
  1206. EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
  1207. NoncanonicalDstType, Loc);
  1208. return Res;
  1209. }
  1210. Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
  1211. QualType DstTy,
  1212. SourceLocation Loc) {
  1213. FixedPointSemantics SrcFPSema =
  1214. CGF.getContext().getFixedPointSemantics(SrcTy);
  1215. FixedPointSemantics DstFPSema =
  1216. CGF.getContext().getFixedPointSemantics(DstTy);
  1217. return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc,
  1218. DstTy->isIntegerType());
  1219. }
  1220. Value *ScalarExprEmitter::EmitFixedPointConversion(
  1221. Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema,
  1222. SourceLocation Loc, bool DstIsInteger) {
  1223. using llvm::APInt;
  1224. using llvm::ConstantInt;
  1225. using llvm::Value;
  1226. unsigned SrcWidth = SrcFPSema.getWidth();
  1227. unsigned DstWidth = DstFPSema.getWidth();
  1228. unsigned SrcScale = SrcFPSema.getScale();
  1229. unsigned DstScale = DstFPSema.getScale();
  1230. bool SrcIsSigned = SrcFPSema.isSigned();
  1231. bool DstIsSigned = DstFPSema.isSigned();
  1232. llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth);
  1233. Value *Result = Src;
  1234. unsigned ResultWidth = SrcWidth;
  1235. // Downscale.
  1236. if (DstScale < SrcScale) {
  1237. // When converting to integers, we round towards zero. For negative numbers,
  1238. // right shifting rounds towards negative infinity. In this case, we can
  1239. // just round up before shifting.
  1240. if (DstIsInteger && SrcIsSigned) {
  1241. Value *Zero = llvm::Constant::getNullValue(Result->getType());
  1242. Value *IsNegative = Builder.CreateICmpSLT(Result, Zero);
  1243. Value *LowBits = ConstantInt::get(
  1244. CGF.getLLVMContext(), APInt::getLowBitsSet(ResultWidth, SrcScale));
  1245. Value *Rounded = Builder.CreateAdd(Result, LowBits);
  1246. Result = Builder.CreateSelect(IsNegative, Rounded, Result);
  1247. }
  1248. Result = SrcIsSigned
  1249. ? Builder.CreateAShr(Result, SrcScale - DstScale, "downscale")
  1250. : Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
  1251. }
  1252. if (!DstFPSema.isSaturated()) {
  1253. // Resize.
  1254. Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
  1255. // Upscale.
  1256. if (DstScale > SrcScale)
  1257. Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
  1258. } else {
  1259. // Adjust the number of fractional bits.
  1260. if (DstScale > SrcScale) {
  1261. // Compare to DstWidth to prevent resizing twice.
  1262. ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
  1263. llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth);
  1264. Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
  1265. Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
  1266. }
  1267. // Handle saturation.
  1268. bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits();
  1269. if (LessIntBits) {
  1270. Value *Max = ConstantInt::get(
  1271. CGF.getLLVMContext(),
  1272. APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth));
  1273. Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max)
  1274. : Builder.CreateICmpUGT(Result, Max);
  1275. Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax");
  1276. }
  1277. // Cannot overflow min to dest type if src is unsigned since all fixed
  1278. // point types can cover the unsigned min of 0.
  1279. if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
  1280. Value *Min = ConstantInt::get(
  1281. CGF.getLLVMContext(),
  1282. APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth));
  1283. Value *TooLow = Builder.CreateICmpSLT(Result, Min);
  1284. Result = Builder.CreateSelect(TooLow, Min, Result, "satmin");
  1285. }
  1286. // Resize the integer part to get the final destination size.
  1287. if (ResultWidth != DstWidth)
  1288. Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
  1289. }
  1290. return Result;
  1291. }
  1292. /// Emit a conversion from the specified complex type to the specified
  1293. /// destination type, where the destination type is an LLVM scalar type.
  1294. Value *ScalarExprEmitter::EmitComplexToScalarConversion(
  1295. CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
  1296. SourceLocation Loc) {
  1297. // Get the source element type.
  1298. SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
  1299. // Handle conversions to bool first, they are special: comparisons against 0.
  1300. if (DstTy->isBooleanType()) {
  1301. // Complex != 0 -> (Real != 0) | (Imag != 0)
  1302. Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
  1303. Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
  1304. return Builder.CreateOr(Src.first, Src.second, "tobool");
  1305. }
  1306. // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
  1307. // the imaginary part of the complex value is discarded and the value of the
  1308. // real part is converted according to the conversion rules for the
  1309. // corresponding real type.
  1310. return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
  1311. }
  1312. Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
  1313. return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
  1314. }
  1315. /// Emit a sanitization check for the given "binary" operation (which
  1316. /// might actually be a unary increment which has been lowered to a binary
  1317. /// operation). The check passes if all values in \p Checks (which are \c i1),
  1318. /// are \c true.
  1319. void ScalarExprEmitter::EmitBinOpCheck(
  1320. ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
  1321. assert(CGF.IsSanitizerScope);
  1322. SanitizerHandler Check;
  1323. SmallVector<llvm::Constant *, 4> StaticData;
  1324. SmallVector<llvm::Value *, 2> DynamicData;
  1325. BinaryOperatorKind Opcode = Info.Opcode;
  1326. if (BinaryOperator::isCompoundAssignmentOp(Opcode))
  1327. Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
  1328. StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
  1329. const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
  1330. if (UO && UO->getOpcode() == UO_Minus) {
  1331. Check = SanitizerHandler::NegateOverflow;
  1332. StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
  1333. DynamicData.push_back(Info.RHS);
  1334. } else {
  1335. if (BinaryOperator::isShiftOp(Opcode)) {
  1336. // Shift LHS negative or too large, or RHS out of bounds.
  1337. Check = SanitizerHandler::ShiftOutOfBounds;
  1338. const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
  1339. StaticData.push_back(
  1340. CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
  1341. StaticData.push_back(
  1342. CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
  1343. } else if (Opcode == BO_Div || Opcode == BO_Rem) {
  1344. // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
  1345. Check = SanitizerHandler::DivremOverflow;
  1346. StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
  1347. } else {
  1348. // Arithmetic overflow (+, -, *).
  1349. switch (Opcode) {
  1350. case BO_Add: Check = SanitizerHandler::AddOverflow; break;
  1351. case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
  1352. case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
  1353. default: llvm_unreachable("unexpected opcode for bin op check");
  1354. }
  1355. StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
  1356. }
  1357. DynamicData.push_back(Info.LHS);
  1358. DynamicData.push_back(Info.RHS);
  1359. }
  1360. CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
  1361. }
  1362. //===----------------------------------------------------------------------===//
  1363. // Visitor Methods
  1364. //===----------------------------------------------------------------------===//
  1365. Value *ScalarExprEmitter::VisitExpr(Expr *E) {
  1366. CGF.ErrorUnsupported(E, "scalar expression");
  1367. if (E->getType()->isVoidType())
  1368. return nullptr;
  1369. return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  1370. }
  1371. Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
  1372. // Vector Mask Case
  1373. if (E->getNumSubExprs() == 2) {
  1374. Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
  1375. Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
  1376. Value *Mask;
  1377. llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
  1378. unsigned LHSElts = LTy->getNumElements();
  1379. Mask = RHS;
  1380. llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
  1381. // Mask off the high bits of each shuffle index.
  1382. Value *MaskBits =
  1383. llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
  1384. Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
  1385. // newv = undef
  1386. // mask = mask & maskbits
  1387. // for each elt
  1388. // n = extract mask i
  1389. // x = extract val n
  1390. // newv = insert newv, x, i
  1391. llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
  1392. MTy->getNumElements());
  1393. Value* NewV = llvm::UndefValue::get(RTy);
  1394. for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
  1395. Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
  1396. Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
  1397. Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
  1398. NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
  1399. }
  1400. return NewV;
  1401. }
  1402. Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
  1403. Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
  1404. SmallVector<llvm::Constant*, 32> indices;
  1405. for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
  1406. llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
  1407. // Check for -1 and output it as undef in the IR.
  1408. if (Idx.isSigned() && Idx.isAllOnesValue())
  1409. indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
  1410. else
  1411. indices.push_back(Builder.getInt32(Idx.getZExtValue()));
  1412. }
  1413. Value *SV = llvm::ConstantVector::get(indices);
  1414. return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
  1415. }
  1416. Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
  1417. QualType SrcType = E->getSrcExpr()->getType(),
  1418. DstType = E->getType();
  1419. Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
  1420. SrcType = CGF.getContext().getCanonicalType(SrcType);
  1421. DstType = CGF.getContext().getCanonicalType(DstType);
  1422. if (SrcType == DstType) return Src;
  1423. assert(SrcType->isVectorType() &&
  1424. "ConvertVector source type must be a vector");
  1425. assert(DstType->isVectorType() &&
  1426. "ConvertVector destination type must be a vector");
  1427. llvm::Type *SrcTy = Src->getType();
  1428. llvm::Type *DstTy = ConvertType(DstType);
  1429. // Ignore conversions like int -> uint.
  1430. if (SrcTy == DstTy)
  1431. return Src;
  1432. QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
  1433. DstEltType = DstType->castAs<VectorType>()->getElementType();
  1434. assert(SrcTy->isVectorTy() &&
  1435. "ConvertVector source IR type must be a vector");
  1436. assert(DstTy->isVectorTy() &&
  1437. "ConvertVector destination IR type must be a vector");
  1438. llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
  1439. *DstEltTy = DstTy->getVectorElementType();
  1440. if (DstEltType->isBooleanType()) {
  1441. assert((SrcEltTy->isFloatingPointTy() ||
  1442. isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
  1443. llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
  1444. if (SrcEltTy->isFloatingPointTy()) {
  1445. return Builder.CreateFCmpUNE(Src, Zero, "tobool");
  1446. } else {
  1447. return Builder.CreateICmpNE(Src, Zero, "tobool");
  1448. }
  1449. }
  1450. // We have the arithmetic types: real int/float.
  1451. Value *Res = nullptr;
  1452. if (isa<llvm::IntegerType>(SrcEltTy)) {
  1453. bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
  1454. if (isa<llvm::IntegerType>(DstEltTy))
  1455. Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
  1456. else if (InputSigned)
  1457. Res = Builder.CreateSIToFP(Src, DstTy, "conv");
  1458. else
  1459. Res = Builder.CreateUIToFP(Src, DstTy, "conv");
  1460. } else if (isa<llvm::IntegerType>(DstEltTy)) {
  1461. assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
  1462. if (DstEltType->isSignedIntegerOrEnumerationType())
  1463. Res = Builder.CreateFPToSI(Src, DstTy, "conv");
  1464. else
  1465. Res = Builder.CreateFPToUI(Src, DstTy, "conv");
  1466. } else {
  1467. assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
  1468. "Unknown real conversion");
  1469. if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
  1470. Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
  1471. else
  1472. Res = Builder.CreateFPExt(Src, DstTy, "conv");
  1473. }
  1474. return Res;
  1475. }
  1476. Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
  1477. if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
  1478. CGF.EmitIgnoredExpr(E->getBase());
  1479. return CGF.emitScalarConstant(Constant, E);
  1480. } else {
  1481. Expr::EvalResult Result;
  1482. if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
  1483. llvm::APSInt Value = Result.Val.getInt();
  1484. CGF.EmitIgnoredExpr(E->getBase());
  1485. return Builder.getInt(Value);
  1486. }
  1487. }
  1488. return EmitLoadOfLValue(E);
  1489. }
  1490. Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
  1491. TestAndClearIgnoreResultAssign();
  1492. // Emit subscript expressions in rvalue context's. For most cases, this just
  1493. // loads the lvalue formed by the subscript expr. However, we have to be
  1494. // careful, because the base of a vector subscript is occasionally an rvalue,
  1495. // so we can't get it as an lvalue.
  1496. if (!E->getBase()->getType()->isVectorType())
  1497. return EmitLoadOfLValue(E);
  1498. // Handle the vector case. The base must be a vector, the index must be an
  1499. // integer value.
  1500. Value *Base = Visit(E->getBase());
  1501. Value *Idx = Visit(E->getIdx());
  1502. QualType IdxTy = E->getIdx()->getType();
  1503. if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
  1504. CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
  1505. return Builder.CreateExtractElement(Base, Idx, "vecext");
  1506. }
  1507. static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
  1508. unsigned Off, llvm::Type *I32Ty) {
  1509. int MV = SVI->getMaskValue(Idx);
  1510. if (MV == -1)
  1511. return llvm::UndefValue::get(I32Ty);
  1512. return llvm::ConstantInt::get(I32Ty, Off+MV);
  1513. }
  1514. static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
  1515. if (C->getBitWidth() != 32) {
  1516. assert(llvm::ConstantInt::isValueValidForType(I32Ty,
  1517. C->getZExtValue()) &&
  1518. "Index operand too large for shufflevector mask!");
  1519. return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
  1520. }
  1521. return C;
  1522. }
  1523. Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
  1524. bool Ignore = TestAndClearIgnoreResultAssign();
  1525. (void)Ignore;
  1526. assert (Ignore == false && "init list ignored");
  1527. unsigned NumInitElements = E->getNumInits();
  1528. if (E->hadArrayRangeDesignator())
  1529. CGF.ErrorUnsupported(E, "GNU array range designator extension");
  1530. llvm::VectorType *VType =
  1531. dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
  1532. if (!VType) {
  1533. if (NumInitElements == 0) {
  1534. // C++11 value-initialization for the scalar.
  1535. return EmitNullValue(E->getType());
  1536. }
  1537. // We have a scalar in braces. Just use the first element.
  1538. return Visit(E->getInit(0));
  1539. }
  1540. unsigned ResElts = VType->getNumElements();
  1541. // Loop over initializers collecting the Value for each, and remembering
  1542. // whether the source was swizzle (ExtVectorElementExpr). This will allow
  1543. // us to fold the shuffle for the swizzle into the shuffle for the vector
  1544. // initializer, since LLVM optimizers generally do not want to touch
  1545. // shuffles.
  1546. unsigned CurIdx = 0;
  1547. bool VIsUndefShuffle = false;
  1548. llvm::Value *V = llvm::UndefValue::get(VType);
  1549. for (unsigned i = 0; i != NumInitElements; ++i) {
  1550. Expr *IE = E->getInit(i);
  1551. Value *Init = Visit(IE);
  1552. SmallVector<llvm::Constant*, 16> Args;
  1553. llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
  1554. // Handle scalar elements. If the scalar initializer is actually one
  1555. // element of a different vector of the same width, use shuffle instead of
  1556. // extract+insert.
  1557. if (!VVT) {
  1558. if (isa<ExtVectorElementExpr>(IE)) {
  1559. llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
  1560. if (EI->getVectorOperandType()->getNumElements() == ResElts) {
  1561. llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
  1562. Value *LHS = nullptr, *RHS = nullptr;
  1563. if (CurIdx == 0) {
  1564. // insert into undef -> shuffle (src, undef)
  1565. // shufflemask must use an i32
  1566. Args.push_back(getAsInt32(C, CGF.Int32Ty));
  1567. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1568. LHS = EI->getVectorOperand();
  1569. RHS = V;
  1570. VIsUndefShuffle = true;
  1571. } else if (VIsUndefShuffle) {
  1572. // insert into undefshuffle && size match -> shuffle (v, src)
  1573. llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
  1574. for (unsigned j = 0; j != CurIdx; ++j)
  1575. Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
  1576. Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
  1577. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1578. LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
  1579. RHS = EI->getVectorOperand();
  1580. VIsUndefShuffle = false;
  1581. }
  1582. if (!Args.empty()) {
  1583. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  1584. V = Builder.CreateShuffleVector(LHS, RHS, Mask);
  1585. ++CurIdx;
  1586. continue;
  1587. }
  1588. }
  1589. }
  1590. V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
  1591. "vecinit");
  1592. VIsUndefShuffle = false;
  1593. ++CurIdx;
  1594. continue;
  1595. }
  1596. unsigned InitElts = VVT->getNumElements();
  1597. // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
  1598. // input is the same width as the vector being constructed, generate an
  1599. // optimized shuffle of the swizzle input into the result.
  1600. unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
  1601. if (isa<ExtVectorElementExpr>(IE)) {
  1602. llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
  1603. Value *SVOp = SVI->getOperand(0);
  1604. llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
  1605. if (OpTy->getNumElements() == ResElts) {
  1606. for (unsigned j = 0; j != CurIdx; ++j) {
  1607. // If the current vector initializer is a shuffle with undef, merge
  1608. // this shuffle directly into it.
  1609. if (VIsUndefShuffle) {
  1610. Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
  1611. CGF.Int32Ty));
  1612. } else {
  1613. Args.push_back(Builder.getInt32(j));
  1614. }
  1615. }
  1616. for (unsigned j = 0, je = InitElts; j != je; ++j)
  1617. Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
  1618. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1619. if (VIsUndefShuffle)
  1620. V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
  1621. Init = SVOp;
  1622. }
  1623. }
  1624. // Extend init to result vector length, and then shuffle its contribution
  1625. // to the vector initializer into V.
  1626. if (Args.empty()) {
  1627. for (unsigned j = 0; j != InitElts; ++j)
  1628. Args.push_back(Builder.getInt32(j));
  1629. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1630. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  1631. Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
  1632. Mask, "vext");
  1633. Args.clear();
  1634. for (unsigned j = 0; j != CurIdx; ++j)
  1635. Args.push_back(Builder.getInt32(j));
  1636. for (unsigned j = 0; j != InitElts; ++j)
  1637. Args.push_back(Builder.getInt32(j+Offset));
  1638. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1639. }
  1640. // If V is undef, make sure it ends up on the RHS of the shuffle to aid
  1641. // merging subsequent shuffles into this one.
  1642. if (CurIdx == 0)
  1643. std::swap(V, Init);
  1644. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  1645. V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
  1646. VIsUndefShuffle = isa<llvm::UndefValue>(Init);
  1647. CurIdx += InitElts;
  1648. }
  1649. // FIXME: evaluate codegen vs. shuffling against constant null vector.
  1650. // Emit remaining default initializers.
  1651. llvm::Type *EltTy = VType->getElementType();
  1652. // Emit remaining default initializers
  1653. for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
  1654. Value *Idx = Builder.getInt32(CurIdx);
  1655. llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
  1656. V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
  1657. }
  1658. return V;
  1659. }
  1660. bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
  1661. const Expr *E = CE->getSubExpr();
  1662. if (CE->getCastKind() == CK_UncheckedDerivedToBase)
  1663. return false;
  1664. if (isa<CXXThisExpr>(E->IgnoreParens())) {
  1665. // We always assume that 'this' is never null.
  1666. return false;
  1667. }
  1668. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
  1669. // And that glvalue casts are never null.
  1670. if (ICE->getValueKind() != VK_RValue)
  1671. return false;
  1672. }
  1673. return true;
  1674. }
  1675. // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
  1676. // have to handle a more broad range of conversions than explicit casts, as they
  1677. // handle things like function to ptr-to-function decay etc.
  1678. Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
  1679. Expr *E = CE->getSubExpr();
  1680. QualType DestTy = CE->getType();
  1681. CastKind Kind = CE->getCastKind();
  1682. // These cases are generally not written to ignore the result of
  1683. // evaluating their sub-expressions, so we clear this now.
  1684. bool Ignored = TestAndClearIgnoreResultAssign();
  1685. // Since almost all cast kinds apply to scalars, this switch doesn't have
  1686. // a default case, so the compiler will warn on a missing case. The cases
  1687. // are in the same order as in the CastKind enum.
  1688. switch (Kind) {
  1689. case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
  1690. case CK_BuiltinFnToFnPtr:
  1691. llvm_unreachable("builtin functions are handled elsewhere");
  1692. case CK_LValueBitCast:
  1693. case CK_ObjCObjectLValueCast: {
  1694. Address Addr = EmitLValue(E).getAddress();
  1695. Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
  1696. LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
  1697. return EmitLoadOfLValue(LV, CE->getExprLoc());
  1698. }
  1699. case CK_LValueToRValueBitCast: {
  1700. LValue SourceLVal = CGF.EmitLValue(E);
  1701. Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(),
  1702. CGF.ConvertTypeForMem(DestTy));
  1703. LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
  1704. DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
  1705. return EmitLoadOfLValue(DestLV, CE->getExprLoc());
  1706. }
  1707. case CK_CPointerToObjCPointerCast:
  1708. case CK_BlockPointerToObjCPointerCast:
  1709. case CK_AnyPointerToBlockPointerCast:
  1710. case CK_BitCast: {
  1711. Value *Src = Visit(const_cast<Expr*>(E));
  1712. llvm::Type *SrcTy = Src->getType();
  1713. llvm::Type *DstTy = ConvertType(DestTy);
  1714. if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
  1715. SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
  1716. llvm_unreachable("wrong cast for pointers in different address spaces"
  1717. "(must be an address space cast)!");
  1718. }
  1719. if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  1720. if (auto PT = DestTy->getAs<PointerType>())
  1721. CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
  1722. /*MayBeNull=*/true,
  1723. CodeGenFunction::CFITCK_UnrelatedCast,
  1724. CE->getBeginLoc());
  1725. }
  1726. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1727. const QualType SrcType = E->getType();
  1728. if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
  1729. // Casting to pointer that could carry dynamic information (provided by
  1730. // invariant.group) requires launder.
  1731. Src = Builder.CreateLaunderInvariantGroup(Src);
  1732. } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
  1733. // Casting to pointer that does not carry dynamic information (provided
  1734. // by invariant.group) requires stripping it. Note that we don't do it
  1735. // if the source could not be dynamic type and destination could be
  1736. // dynamic because dynamic information is already laundered. It is
  1737. // because launder(strip(src)) == launder(src), so there is no need to
  1738. // add extra strip before launder.
  1739. Src = Builder.CreateStripInvariantGroup(Src);
  1740. }
  1741. }
  1742. // Update heapallocsite metadata when there is an explicit cast.
  1743. if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(Src))
  1744. if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE))
  1745. CGF.getDebugInfo()->
  1746. addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
  1747. return Builder.CreateBitCast(Src, DstTy);
  1748. }
  1749. case CK_AddressSpaceConversion: {
  1750. Expr::EvalResult Result;
  1751. if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
  1752. Result.Val.isNullPointer()) {
  1753. // If E has side effect, it is emitted even if its final result is a
  1754. // null pointer. In that case, a DCE pass should be able to
  1755. // eliminate the useless instructions emitted during translating E.
  1756. if (Result.HasSideEffects)
  1757. Visit(E);
  1758. return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
  1759. ConvertType(DestTy)), DestTy);
  1760. }
  1761. // Since target may map different address spaces in AST to the same address
  1762. // space, an address space conversion may end up as a bitcast.
  1763. return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
  1764. CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
  1765. DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
  1766. }
  1767. case CK_AtomicToNonAtomic:
  1768. case CK_NonAtomicToAtomic:
  1769. case CK_NoOp:
  1770. case CK_UserDefinedConversion:
  1771. return Visit(const_cast<Expr*>(E));
  1772. case CK_BaseToDerived: {
  1773. const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
  1774. assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
  1775. Address Base = CGF.EmitPointerWithAlignment(E);
  1776. Address Derived =
  1777. CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
  1778. CE->path_begin(), CE->path_end(),
  1779. CGF.ShouldNullCheckClassCastValue(CE));
  1780. // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
  1781. // performed and the object is not of the derived type.
  1782. if (CGF.sanitizePerformTypeCheck())
  1783. CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
  1784. Derived.getPointer(), DestTy->getPointeeType());
  1785. if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
  1786. CGF.EmitVTablePtrCheckForCast(
  1787. DestTy->getPointeeType(), Derived.getPointer(),
  1788. /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
  1789. CE->getBeginLoc());
  1790. return Derived.getPointer();
  1791. }
  1792. case CK_UncheckedDerivedToBase:
  1793. case CK_DerivedToBase: {
  1794. // The EmitPointerWithAlignment path does this fine; just discard
  1795. // the alignment.
  1796. return CGF.EmitPointerWithAlignment(CE).getPointer();
  1797. }
  1798. case CK_Dynamic: {
  1799. Address V = CGF.EmitPointerWithAlignment(E);
  1800. const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
  1801. return CGF.EmitDynamicCast(V, DCE);
  1802. }
  1803. case CK_ArrayToPointerDecay:
  1804. return CGF.EmitArrayToPointerDecay(E).getPointer();
  1805. case CK_FunctionToPointerDecay:
  1806. return EmitLValue(E).getPointer();
  1807. case CK_NullToPointer:
  1808. if (MustVisitNullValue(E))
  1809. CGF.EmitIgnoredExpr(E);
  1810. return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
  1811. DestTy);
  1812. case CK_NullToMemberPointer: {
  1813. if (MustVisitNullValue(E))
  1814. CGF.EmitIgnoredExpr(E);
  1815. const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
  1816. return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
  1817. }
  1818. case CK_ReinterpretMemberPointer:
  1819. case CK_BaseToDerivedMemberPointer:
  1820. case CK_DerivedToBaseMemberPointer: {
  1821. Value *Src = Visit(E);
  1822. // Note that the AST doesn't distinguish between checked and
  1823. // unchecked member pointer conversions, so we always have to
  1824. // implement checked conversions here. This is inefficient when
  1825. // actual control flow may be required in order to perform the
  1826. // check, which it is for data member pointers (but not member
  1827. // function pointers on Itanium and ARM).
  1828. return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
  1829. }
  1830. case CK_ARCProduceObject:
  1831. return CGF.EmitARCRetainScalarExpr(E);
  1832. case CK_ARCConsumeObject:
  1833. return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
  1834. case CK_ARCReclaimReturnedObject:
  1835. return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
  1836. case CK_ARCExtendBlockObject:
  1837. return CGF.EmitARCExtendBlockObject(E);
  1838. case CK_CopyAndAutoreleaseBlockObject:
  1839. return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
  1840. case CK_FloatingRealToComplex:
  1841. case CK_FloatingComplexCast:
  1842. case CK_IntegralRealToComplex:
  1843. case CK_IntegralComplexCast:
  1844. case CK_IntegralComplexToFloatingComplex:
  1845. case CK_FloatingComplexToIntegralComplex:
  1846. case CK_ConstructorConversion:
  1847. case CK_ToUnion:
  1848. llvm_unreachable("scalar cast to non-scalar value");
  1849. case CK_LValueToRValue:
  1850. assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
  1851. assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
  1852. return Visit(const_cast<Expr*>(E));
  1853. case CK_IntegralToPointer: {
  1854. Value *Src = Visit(const_cast<Expr*>(E));
  1855. // First, convert to the correct width so that we control the kind of
  1856. // extension.
  1857. auto DestLLVMTy = ConvertType(DestTy);
  1858. llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
  1859. bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
  1860. llvm::Value* IntResult =
  1861. Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
  1862. auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
  1863. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1864. // Going from integer to pointer that could be dynamic requires reloading
  1865. // dynamic information from invariant.group.
  1866. if (DestTy.mayBeDynamicClass())
  1867. IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
  1868. }
  1869. return IntToPtr;
  1870. }
  1871. case CK_PointerToIntegral: {
  1872. assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
  1873. auto *PtrExpr = Visit(E);
  1874. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1875. const QualType SrcType = E->getType();
  1876. // Casting to integer requires stripping dynamic information as it does
  1877. // not carries it.
  1878. if (SrcType.mayBeDynamicClass())
  1879. PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
  1880. }
  1881. return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
  1882. }
  1883. case CK_ToVoid: {
  1884. CGF.EmitIgnoredExpr(E);
  1885. return nullptr;
  1886. }
  1887. case CK_VectorSplat: {
  1888. llvm::Type *DstTy = ConvertType(DestTy);
  1889. Value *Elt = Visit(const_cast<Expr*>(E));
  1890. // Splat the element across to all elements
  1891. unsigned NumElements = DstTy->getVectorNumElements();
  1892. return Builder.CreateVectorSplat(NumElements, Elt, "splat");
  1893. }
  1894. case CK_FixedPointCast:
  1895. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1896. CE->getExprLoc());
  1897. case CK_FixedPointToBoolean:
  1898. assert(E->getType()->isFixedPointType() &&
  1899. "Expected src type to be fixed point type");
  1900. assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
  1901. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1902. CE->getExprLoc());
  1903. case CK_FixedPointToIntegral:
  1904. assert(E->getType()->isFixedPointType() &&
  1905. "Expected src type to be fixed point type");
  1906. assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
  1907. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1908. CE->getExprLoc());
  1909. case CK_IntegralToFixedPoint:
  1910. assert(E->getType()->isIntegerType() &&
  1911. "Expected src type to be an integer");
  1912. assert(DestTy->isFixedPointType() &&
  1913. "Expected dest type to be fixed point type");
  1914. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1915. CE->getExprLoc());
  1916. case CK_IntegralCast: {
  1917. ScalarConversionOpts Opts;
  1918. if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
  1919. if (!ICE->isPartOfExplicitCast())
  1920. Opts = ScalarConversionOpts(CGF.SanOpts);
  1921. }
  1922. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1923. CE->getExprLoc(), Opts);
  1924. }
  1925. case CK_IntegralToFloating:
  1926. case CK_FloatingToIntegral:
  1927. case CK_FloatingCast:
  1928. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1929. CE->getExprLoc());
  1930. case CK_BooleanToSignedIntegral: {
  1931. ScalarConversionOpts Opts;
  1932. Opts.TreatBooleanAsSigned = true;
  1933. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1934. CE->getExprLoc(), Opts);
  1935. }
  1936. case CK_IntegralToBoolean:
  1937. return EmitIntToBoolConversion(Visit(E));
  1938. case CK_PointerToBoolean:
  1939. return EmitPointerToBoolConversion(Visit(E), E->getType());
  1940. case CK_FloatingToBoolean:
  1941. return EmitFloatToBoolConversion(Visit(E));
  1942. case CK_MemberPointerToBoolean: {
  1943. llvm::Value *MemPtr = Visit(E);
  1944. const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
  1945. return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
  1946. }
  1947. case CK_FloatingComplexToReal:
  1948. case CK_IntegralComplexToReal:
  1949. return CGF.EmitComplexExpr(E, false, true).first;
  1950. case CK_FloatingComplexToBoolean:
  1951. case CK_IntegralComplexToBoolean: {
  1952. CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
  1953. // TODO: kill this function off, inline appropriate case here
  1954. return EmitComplexToScalarConversion(V, E->getType(), DestTy,
  1955. CE->getExprLoc());
  1956. }
  1957. case CK_ZeroToOCLOpaqueType: {
  1958. assert((DestTy->isEventT() || DestTy->isQueueT() ||
  1959. DestTy->isOCLIntelSubgroupAVCType()) &&
  1960. "CK_ZeroToOCLEvent cast on non-event type");
  1961. return llvm::Constant::getNullValue(ConvertType(DestTy));
  1962. }
  1963. case CK_IntToOCLSampler:
  1964. return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
  1965. } // end of switch
  1966. llvm_unreachable("unknown scalar cast");
  1967. }
  1968. Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  1969. CodeGenFunction::StmtExprEvaluation eval(CGF);
  1970. Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
  1971. !E->getType()->isVoidType());
  1972. if (!RetAlloca.isValid())
  1973. return nullptr;
  1974. return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
  1975. E->getExprLoc());
  1976. }
  1977. Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
  1978. CGF.enterFullExpression(E);
  1979. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1980. Value *V = Visit(E->getSubExpr());
  1981. // Defend against dominance problems caused by jumps out of expression
  1982. // evaluation through the shared cleanup block.
  1983. Scope.ForceCleanup({&V});
  1984. return V;
  1985. }
  1986. //===----------------------------------------------------------------------===//
  1987. // Unary Operators
  1988. //===----------------------------------------------------------------------===//
  1989. static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
  1990. llvm::Value *InVal, bool IsInc) {
  1991. BinOpInfo BinOp;
  1992. BinOp.LHS = InVal;
  1993. BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
  1994. BinOp.Ty = E->getType();
  1995. BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
  1996. // FIXME: once UnaryOperator carries FPFeatures, copy it here.
  1997. BinOp.E = E;
  1998. return BinOp;
  1999. }
  2000. llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
  2001. const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
  2002. llvm::Value *Amount =
  2003. llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
  2004. StringRef Name = IsInc ? "inc" : "dec";
  2005. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  2006. case LangOptions::SOB_Defined:
  2007. return Builder.CreateAdd(InVal, Amount, Name);
  2008. case LangOptions::SOB_Undefined:
  2009. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  2010. return Builder.CreateNSWAdd(InVal, Amount, Name);
  2011. LLVM_FALLTHROUGH;
  2012. case LangOptions::SOB_Trapping:
  2013. if (!E->canOverflow())
  2014. return Builder.CreateNSWAdd(InVal, Amount, Name);
  2015. return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
  2016. }
  2017. llvm_unreachable("Unknown SignedOverflowBehaviorTy");
  2018. }
  2019. llvm::Value *
  2020. ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  2021. bool isInc, bool isPre) {
  2022. QualType type = E->getSubExpr()->getType();
  2023. llvm::PHINode *atomicPHI = nullptr;
  2024. llvm::Value *value;
  2025. llvm::Value *input;
  2026. int amount = (isInc ? 1 : -1);
  2027. bool isSubtraction = !isInc;
  2028. if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
  2029. type = atomicTy->getValueType();
  2030. if (isInc && type->isBooleanType()) {
  2031. llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
  2032. if (isPre) {
  2033. Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified())
  2034. ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
  2035. return Builder.getTrue();
  2036. }
  2037. // For atomic bool increment, we just store true and return it for
  2038. // preincrement, do an atomic swap with true for postincrement
  2039. return Builder.CreateAtomicRMW(
  2040. llvm::AtomicRMWInst::Xchg, LV.getPointer(), True,
  2041. llvm::AtomicOrdering::SequentiallyConsistent);
  2042. }
  2043. // Special case for atomic increment / decrement on integers, emit
  2044. // atomicrmw instructions. We skip this if we want to be doing overflow
  2045. // checking, and fall into the slow path with the atomic cmpxchg loop.
  2046. if (!type->isBooleanType() && type->isIntegerType() &&
  2047. !(type->isUnsignedIntegerType() &&
  2048. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
  2049. CGF.getLangOpts().getSignedOverflowBehavior() !=
  2050. LangOptions::SOB_Trapping) {
  2051. llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
  2052. llvm::AtomicRMWInst::Sub;
  2053. llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
  2054. llvm::Instruction::Sub;
  2055. llvm::Value *amt = CGF.EmitToMemory(
  2056. llvm::ConstantInt::get(ConvertType(type), 1, true), type);
  2057. llvm::Value *old = Builder.CreateAtomicRMW(aop,
  2058. LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent);
  2059. return isPre ? Builder.CreateBinOp(op, old, amt) : old;
  2060. }
  2061. value = EmitLoadOfLValue(LV, E->getExprLoc());
  2062. input = value;
  2063. // For every other atomic operation, we need to emit a load-op-cmpxchg loop
  2064. llvm::BasicBlock *startBB = Builder.GetInsertBlock();
  2065. llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
  2066. value = CGF.EmitToMemory(value, type);
  2067. Builder.CreateBr(opBB);
  2068. Builder.SetInsertPoint(opBB);
  2069. atomicPHI = Builder.CreatePHI(value->getType(), 2);
  2070. atomicPHI->addIncoming(value, startBB);
  2071. value = atomicPHI;
  2072. } else {
  2073. value = EmitLoadOfLValue(LV, E->getExprLoc());
  2074. input = value;
  2075. }
  2076. // Special case of integer increment that we have to check first: bool++.
  2077. // Due to promotion rules, we get:
  2078. // bool++ -> bool = bool + 1
  2079. // -> bool = (int)bool + 1
  2080. // -> bool = ((int)bool + 1 != 0)
  2081. // An interesting aspect of this is that increment is always true.
  2082. // Decrement does not have this property.
  2083. if (isInc && type->isBooleanType()) {
  2084. value = Builder.getTrue();
  2085. // Most common case by far: integer increment.
  2086. } else if (type->isIntegerType()) {
  2087. // Note that signed integer inc/dec with width less than int can't
  2088. // overflow because of promotion rules; we're just eliding a few steps here.
  2089. if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
  2090. value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
  2091. } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
  2092. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
  2093. value =
  2094. EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
  2095. } else {
  2096. llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
  2097. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  2098. }
  2099. // Next most common: pointer increment.
  2100. } else if (const PointerType *ptr = type->getAs<PointerType>()) {
  2101. QualType type = ptr->getPointeeType();
  2102. // VLA types don't have constant size.
  2103. if (const VariableArrayType *vla
  2104. = CGF.getContext().getAsVariableArrayType(type)) {
  2105. llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
  2106. if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
  2107. if (CGF.getLangOpts().isSignedOverflowDefined())
  2108. value = Builder.CreateGEP(value, numElts, "vla.inc");
  2109. else
  2110. value = CGF.EmitCheckedInBoundsGEP(
  2111. value, numElts, /*SignedIndices=*/false, isSubtraction,
  2112. E->getExprLoc(), "vla.inc");
  2113. // Arithmetic on function pointers (!) is just +-1.
  2114. } else if (type->isFunctionType()) {
  2115. llvm::Value *amt = Builder.getInt32(amount);
  2116. value = CGF.EmitCastToVoidPtr(value);
  2117. if (CGF.getLangOpts().isSignedOverflowDefined())
  2118. value = Builder.CreateGEP(value, amt, "incdec.funcptr");
  2119. else
  2120. value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
  2121. isSubtraction, E->getExprLoc(),
  2122. "incdec.funcptr");
  2123. value = Builder.CreateBitCast(value, input->getType());
  2124. // For everything else, we can just do a simple increment.
  2125. } else {
  2126. llvm::Value *amt = Builder.getInt32(amount);
  2127. if (CGF.getLangOpts().isSignedOverflowDefined())
  2128. value = Builder.CreateGEP(value, amt, "incdec.ptr");
  2129. else
  2130. value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
  2131. isSubtraction, E->getExprLoc(),
  2132. "incdec.ptr");
  2133. }
  2134. // Vector increment/decrement.
  2135. } else if (type->isVectorType()) {
  2136. if (type->hasIntegerRepresentation()) {
  2137. llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
  2138. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  2139. } else {
  2140. value = Builder.CreateFAdd(
  2141. value,
  2142. llvm::ConstantFP::get(value->getType(), amount),
  2143. isInc ? "inc" : "dec");
  2144. }
  2145. // Floating point.
  2146. } else if (type->isRealFloatingType()) {
  2147. // Add the inc/dec to the real part.
  2148. llvm::Value *amt;
  2149. if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  2150. // Another special case: half FP increment should be done via float
  2151. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  2152. value = Builder.CreateCall(
  2153. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
  2154. CGF.CGM.FloatTy),
  2155. input, "incdec.conv");
  2156. } else {
  2157. value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
  2158. }
  2159. }
  2160. if (value->getType()->isFloatTy())
  2161. amt = llvm::ConstantFP::get(VMContext,
  2162. llvm::APFloat(static_cast<float>(amount)));
  2163. else if (value->getType()->isDoubleTy())
  2164. amt = llvm::ConstantFP::get(VMContext,
  2165. llvm::APFloat(static_cast<double>(amount)));
  2166. else {
  2167. // Remaining types are Half, LongDouble or __float128. Convert from float.
  2168. llvm::APFloat F(static_cast<float>(amount));
  2169. bool ignored;
  2170. const llvm::fltSemantics *FS;
  2171. // Don't use getFloatTypeSemantics because Half isn't
  2172. // necessarily represented using the "half" LLVM type.
  2173. if (value->getType()->isFP128Ty())
  2174. FS = &CGF.getTarget().getFloat128Format();
  2175. else if (value->getType()->isHalfTy())
  2176. FS = &CGF.getTarget().getHalfFormat();
  2177. else
  2178. FS = &CGF.getTarget().getLongDoubleFormat();
  2179. F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
  2180. amt = llvm::ConstantFP::get(VMContext, F);
  2181. }
  2182. value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
  2183. if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  2184. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  2185. value = Builder.CreateCall(
  2186. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
  2187. CGF.CGM.FloatTy),
  2188. value, "incdec.conv");
  2189. } else {
  2190. value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
  2191. }
  2192. }
  2193. // Objective-C pointer types.
  2194. } else {
  2195. const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
  2196. value = CGF.EmitCastToVoidPtr(value);
  2197. CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
  2198. if (!isInc) size = -size;
  2199. llvm::Value *sizeValue =
  2200. llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
  2201. if (CGF.getLangOpts().isSignedOverflowDefined())
  2202. value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
  2203. else
  2204. value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
  2205. /*SignedIndices=*/false, isSubtraction,
  2206. E->getExprLoc(), "incdec.objptr");
  2207. value = Builder.CreateBitCast(value, input->getType());
  2208. }
  2209. if (atomicPHI) {
  2210. llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
  2211. llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
  2212. auto Pair = CGF.EmitAtomicCompareExchange(
  2213. LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
  2214. llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
  2215. llvm::Value *success = Pair.second;
  2216. atomicPHI->addIncoming(old, curBlock);
  2217. Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
  2218. Builder.SetInsertPoint(contBB);
  2219. return isPre ? value : input;
  2220. }
  2221. // Store the updated result through the lvalue.
  2222. if (LV.isBitField())
  2223. CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
  2224. else
  2225. CGF.EmitStoreThroughLValue(RValue::get(value), LV);
  2226. // If this is a postinc, return the value read from memory, otherwise use the
  2227. // updated value.
  2228. return isPre ? value : input;
  2229. }
  2230. Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
  2231. TestAndClearIgnoreResultAssign();
  2232. // Emit unary minus with EmitSub so we handle overflow cases etc.
  2233. BinOpInfo BinOp;
  2234. BinOp.RHS = Visit(E->getSubExpr());
  2235. if (BinOp.RHS->getType()->isFPOrFPVectorTy())
  2236. BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
  2237. else
  2238. BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
  2239. BinOp.Ty = E->getType();
  2240. BinOp.Opcode = BO_Sub;
  2241. // FIXME: once UnaryOperator carries FPFeatures, copy it here.
  2242. BinOp.E = E;
  2243. return EmitSub(BinOp);
  2244. }
  2245. Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
  2246. TestAndClearIgnoreResultAssign();
  2247. Value *Op = Visit(E->getSubExpr());
  2248. return Builder.CreateNot(Op, "neg");
  2249. }
  2250. Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
  2251. // Perform vector logical not on comparison with zero vector.
  2252. if (E->getType()->isExtVectorType()) {
  2253. Value *Oper = Visit(E->getSubExpr());
  2254. Value *Zero = llvm::Constant::getNullValue(Oper->getType());
  2255. Value *Result;
  2256. if (Oper->getType()->isFPOrFPVectorTy())
  2257. Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
  2258. else
  2259. Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
  2260. return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
  2261. }
  2262. // Compare operand to zero.
  2263. Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
  2264. // Invert value.
  2265. // TODO: Could dynamically modify easy computations here. For example, if
  2266. // the operand is an icmp ne, turn into icmp eq.
  2267. BoolVal = Builder.CreateNot(BoolVal, "lnot");
  2268. // ZExt result to the expr type.
  2269. return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
  2270. }
  2271. Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
  2272. // Try folding the offsetof to a constant.
  2273. Expr::EvalResult EVResult;
  2274. if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
  2275. llvm::APSInt Value = EVResult.Val.getInt();
  2276. return Builder.getInt(Value);
  2277. }
  2278. // Loop over the components of the offsetof to compute the value.
  2279. unsigned n = E->getNumComponents();
  2280. llvm::Type* ResultType = ConvertType(E->getType());
  2281. llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
  2282. QualType CurrentType = E->getTypeSourceInfo()->getType();
  2283. for (unsigned i = 0; i != n; ++i) {
  2284. OffsetOfNode ON = E->getComponent(i);
  2285. llvm::Value *Offset = nullptr;
  2286. switch (ON.getKind()) {
  2287. case OffsetOfNode::Array: {
  2288. // Compute the index
  2289. Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
  2290. llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
  2291. bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
  2292. Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
  2293. // Save the element type
  2294. CurrentType =
  2295. CGF.getContext().getAsArrayType(CurrentType)->getElementType();
  2296. // Compute the element size
  2297. llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
  2298. CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
  2299. // Multiply out to compute the result
  2300. Offset = Builder.CreateMul(Idx, ElemSize);
  2301. break;
  2302. }
  2303. case OffsetOfNode::Field: {
  2304. FieldDecl *MemberDecl = ON.getField();
  2305. RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
  2306. const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
  2307. // Compute the index of the field in its parent.
  2308. unsigned i = 0;
  2309. // FIXME: It would be nice if we didn't have to loop here!
  2310. for (RecordDecl::field_iterator Field = RD->field_begin(),
  2311. FieldEnd = RD->field_end();
  2312. Field != FieldEnd; ++Field, ++i) {
  2313. if (*Field == MemberDecl)
  2314. break;
  2315. }
  2316. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  2317. // Compute the offset to the field
  2318. int64_t OffsetInt = RL.getFieldOffset(i) /
  2319. CGF.getContext().getCharWidth();
  2320. Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
  2321. // Save the element type.
  2322. CurrentType = MemberDecl->getType();
  2323. break;
  2324. }
  2325. case OffsetOfNode::Identifier:
  2326. llvm_unreachable("dependent __builtin_offsetof");
  2327. case OffsetOfNode::Base: {
  2328. if (ON.getBase()->isVirtual()) {
  2329. CGF.ErrorUnsupported(E, "virtual base in offsetof");
  2330. continue;
  2331. }
  2332. RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
  2333. const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
  2334. // Save the element type.
  2335. CurrentType = ON.getBase()->getType();
  2336. // Compute the offset to the base.
  2337. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  2338. CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
  2339. CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
  2340. Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
  2341. break;
  2342. }
  2343. }
  2344. Result = Builder.CreateAdd(Result, Offset);
  2345. }
  2346. return Result;
  2347. }
  2348. /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
  2349. /// argument of the sizeof expression as an integer.
  2350. Value *
  2351. ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
  2352. const UnaryExprOrTypeTraitExpr *E) {
  2353. QualType TypeToSize = E->getTypeOfArgument();
  2354. if (E->getKind() == UETT_SizeOf) {
  2355. if (const VariableArrayType *VAT =
  2356. CGF.getContext().getAsVariableArrayType(TypeToSize)) {
  2357. if (E->isArgumentType()) {
  2358. // sizeof(type) - make sure to emit the VLA size.
  2359. CGF.EmitVariablyModifiedType(TypeToSize);
  2360. } else {
  2361. // C99 6.5.3.4p2: If the argument is an expression of type
  2362. // VLA, it is evaluated.
  2363. CGF.EmitIgnoredExpr(E->getArgumentExpr());
  2364. }
  2365. auto VlaSize = CGF.getVLASize(VAT);
  2366. llvm::Value *size = VlaSize.NumElts;
  2367. // Scale the number of non-VLA elements by the non-VLA element size.
  2368. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
  2369. if (!eltSize.isOne())
  2370. size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
  2371. return size;
  2372. }
  2373. } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
  2374. auto Alignment =
  2375. CGF.getContext()
  2376. .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
  2377. E->getTypeOfArgument()->getPointeeType()))
  2378. .getQuantity();
  2379. return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
  2380. }
  2381. // If this isn't sizeof(vla), the result must be constant; use the constant
  2382. // folding logic so we don't have to duplicate it here.
  2383. return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
  2384. }
  2385. Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
  2386. Expr *Op = E->getSubExpr();
  2387. if (Op->getType()->isAnyComplexType()) {
  2388. // If it's an l-value, load through the appropriate subobject l-value.
  2389. // Note that we have to ask E because Op might be an l-value that
  2390. // this won't work for, e.g. an Obj-C property.
  2391. if (E->isGLValue())
  2392. return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
  2393. E->getExprLoc()).getScalarVal();
  2394. // Otherwise, calculate and project.
  2395. return CGF.EmitComplexExpr(Op, false, true).first;
  2396. }
  2397. return Visit(Op);
  2398. }
  2399. Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
  2400. Expr *Op = E->getSubExpr();
  2401. if (Op->getType()->isAnyComplexType()) {
  2402. // If it's an l-value, load through the appropriate subobject l-value.
  2403. // Note that we have to ask E because Op might be an l-value that
  2404. // this won't work for, e.g. an Obj-C property.
  2405. if (Op->isGLValue())
  2406. return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
  2407. E->getExprLoc()).getScalarVal();
  2408. // Otherwise, calculate and project.
  2409. return CGF.EmitComplexExpr(Op, true, false).second;
  2410. }
  2411. // __imag on a scalar returns zero. Emit the subexpr to ensure side
  2412. // effects are evaluated, but not the actual value.
  2413. if (Op->isGLValue())
  2414. CGF.EmitLValue(Op);
  2415. else
  2416. CGF.EmitScalarExpr(Op, true);
  2417. return llvm::Constant::getNullValue(ConvertType(E->getType()));
  2418. }
  2419. //===----------------------------------------------------------------------===//
  2420. // Binary Operators
  2421. //===----------------------------------------------------------------------===//
  2422. BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
  2423. TestAndClearIgnoreResultAssign();
  2424. BinOpInfo Result;
  2425. Result.LHS = Visit(E->getLHS());
  2426. Result.RHS = Visit(E->getRHS());
  2427. Result.Ty = E->getType();
  2428. Result.Opcode = E->getOpcode();
  2429. Result.FPFeatures = E->getFPFeatures();
  2430. Result.E = E;
  2431. return Result;
  2432. }
  2433. LValue ScalarExprEmitter::EmitCompoundAssignLValue(
  2434. const CompoundAssignOperator *E,
  2435. Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
  2436. Value *&Result) {
  2437. QualType LHSTy = E->getLHS()->getType();
  2438. BinOpInfo OpInfo;
  2439. if (E->getComputationResultType()->isAnyComplexType())
  2440. return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
  2441. // Emit the RHS first. __block variables need to have the rhs evaluated
  2442. // first, plus this should improve codegen a little.
  2443. OpInfo.RHS = Visit(E->getRHS());
  2444. OpInfo.Ty = E->getComputationResultType();
  2445. OpInfo.Opcode = E->getOpcode();
  2446. OpInfo.FPFeatures = E->getFPFeatures();
  2447. OpInfo.E = E;
  2448. // Load/convert the LHS.
  2449. LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  2450. llvm::PHINode *atomicPHI = nullptr;
  2451. if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
  2452. QualType type = atomicTy->getValueType();
  2453. if (!type->isBooleanType() && type->isIntegerType() &&
  2454. !(type->isUnsignedIntegerType() &&
  2455. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
  2456. CGF.getLangOpts().getSignedOverflowBehavior() !=
  2457. LangOptions::SOB_Trapping) {
  2458. llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
  2459. switch (OpInfo.Opcode) {
  2460. // We don't have atomicrmw operands for *, %, /, <<, >>
  2461. case BO_MulAssign: case BO_DivAssign:
  2462. case BO_RemAssign:
  2463. case BO_ShlAssign:
  2464. case BO_ShrAssign:
  2465. break;
  2466. case BO_AddAssign:
  2467. aop = llvm::AtomicRMWInst::Add;
  2468. break;
  2469. case BO_SubAssign:
  2470. aop = llvm::AtomicRMWInst::Sub;
  2471. break;
  2472. case BO_AndAssign:
  2473. aop = llvm::AtomicRMWInst::And;
  2474. break;
  2475. case BO_XorAssign:
  2476. aop = llvm::AtomicRMWInst::Xor;
  2477. break;
  2478. case BO_OrAssign:
  2479. aop = llvm::AtomicRMWInst::Or;
  2480. break;
  2481. default:
  2482. llvm_unreachable("Invalid compound assignment type");
  2483. }
  2484. if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
  2485. llvm::Value *amt = CGF.EmitToMemory(
  2486. EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
  2487. E->getExprLoc()),
  2488. LHSTy);
  2489. Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt,
  2490. llvm::AtomicOrdering::SequentiallyConsistent);
  2491. return LHSLV;
  2492. }
  2493. }
  2494. // FIXME: For floating point types, we should be saving and restoring the
  2495. // floating point environment in the loop.
  2496. llvm::BasicBlock *startBB = Builder.GetInsertBlock();
  2497. llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
  2498. OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
  2499. OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
  2500. Builder.CreateBr(opBB);
  2501. Builder.SetInsertPoint(opBB);
  2502. atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
  2503. atomicPHI->addIncoming(OpInfo.LHS, startBB);
  2504. OpInfo.LHS = atomicPHI;
  2505. }
  2506. else
  2507. OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
  2508. SourceLocation Loc = E->getExprLoc();
  2509. OpInfo.LHS =
  2510. EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
  2511. // Expand the binary operator.
  2512. Result = (this->*Func)(OpInfo);
  2513. // Convert the result back to the LHS type,
  2514. // potentially with Implicit Conversion sanitizer check.
  2515. Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
  2516. Loc, ScalarConversionOpts(CGF.SanOpts));
  2517. if (atomicPHI) {
  2518. llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
  2519. llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
  2520. auto Pair = CGF.EmitAtomicCompareExchange(
  2521. LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
  2522. llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
  2523. llvm::Value *success = Pair.second;
  2524. atomicPHI->addIncoming(old, curBlock);
  2525. Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
  2526. Builder.SetInsertPoint(contBB);
  2527. return LHSLV;
  2528. }
  2529. // Store the result value into the LHS lvalue. Bit-fields are handled
  2530. // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
  2531. // 'An assignment expression has the value of the left operand after the
  2532. // assignment...'.
  2533. if (LHSLV.isBitField())
  2534. CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
  2535. else
  2536. CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
  2537. return LHSLV;
  2538. }
  2539. Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
  2540. Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
  2541. bool Ignore = TestAndClearIgnoreResultAssign();
  2542. Value *RHS = nullptr;
  2543. LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
  2544. // If the result is clearly ignored, return now.
  2545. if (Ignore)
  2546. return nullptr;
  2547. // The result of an assignment in C is the assigned r-value.
  2548. if (!CGF.getLangOpts().CPlusPlus)
  2549. return RHS;
  2550. // If the lvalue is non-volatile, return the computed value of the assignment.
  2551. if (!LHS.isVolatileQualified())
  2552. return RHS;
  2553. // Otherwise, reload the value.
  2554. return EmitLoadOfLValue(LHS, E->getExprLoc());
  2555. }
  2556. void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
  2557. const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
  2558. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
  2559. if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
  2560. Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
  2561. SanitizerKind::IntegerDivideByZero));
  2562. }
  2563. const auto *BO = cast<BinaryOperator>(Ops.E);
  2564. if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
  2565. Ops.Ty->hasSignedIntegerRepresentation() &&
  2566. !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
  2567. Ops.mayHaveIntegerOverflow()) {
  2568. llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
  2569. llvm::Value *IntMin =
  2570. Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
  2571. llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
  2572. llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
  2573. llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
  2574. llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
  2575. Checks.push_back(
  2576. std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
  2577. }
  2578. if (Checks.size() > 0)
  2579. EmitBinOpCheck(Checks, Ops);
  2580. }
  2581. Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
  2582. {
  2583. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2584. if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
  2585. CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
  2586. Ops.Ty->isIntegerType() &&
  2587. (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
  2588. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2589. EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
  2590. } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
  2591. Ops.Ty->isRealFloatingType() &&
  2592. Ops.mayHaveFloatDivisionByZero()) {
  2593. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2594. llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
  2595. EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
  2596. Ops);
  2597. }
  2598. }
  2599. if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
  2600. llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
  2601. if (CGF.getLangOpts().OpenCL &&
  2602. !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
  2603. // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
  2604. // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
  2605. // build option allows an application to specify that single precision
  2606. // floating-point divide (x/y and 1/x) and sqrt used in the program
  2607. // source are correctly rounded.
  2608. llvm::Type *ValTy = Val->getType();
  2609. if (ValTy->isFloatTy() ||
  2610. (isa<llvm::VectorType>(ValTy) &&
  2611. cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
  2612. CGF.SetFPAccuracy(Val, 2.5);
  2613. }
  2614. return Val;
  2615. }
  2616. else if (Ops.Ty->hasUnsignedIntegerRepresentation())
  2617. return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
  2618. else
  2619. return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
  2620. }
  2621. Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
  2622. // Rem in C can't be a floating point type: C99 6.5.5p2.
  2623. if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
  2624. CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
  2625. Ops.Ty->isIntegerType() &&
  2626. (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
  2627. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2628. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2629. EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
  2630. }
  2631. if (Ops.Ty->hasUnsignedIntegerRepresentation())
  2632. return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
  2633. else
  2634. return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
  2635. }
  2636. Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
  2637. unsigned IID;
  2638. unsigned OpID = 0;
  2639. bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
  2640. switch (Ops.Opcode) {
  2641. case BO_Add:
  2642. case BO_AddAssign:
  2643. OpID = 1;
  2644. IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
  2645. llvm::Intrinsic::uadd_with_overflow;
  2646. break;
  2647. case BO_Sub:
  2648. case BO_SubAssign:
  2649. OpID = 2;
  2650. IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
  2651. llvm::Intrinsic::usub_with_overflow;
  2652. break;
  2653. case BO_Mul:
  2654. case BO_MulAssign:
  2655. OpID = 3;
  2656. IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
  2657. llvm::Intrinsic::umul_with_overflow;
  2658. break;
  2659. default:
  2660. llvm_unreachable("Unsupported operation for overflow detection");
  2661. }
  2662. OpID <<= 1;
  2663. if (isSigned)
  2664. OpID |= 1;
  2665. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2666. llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
  2667. llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
  2668. Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
  2669. Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
  2670. Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
  2671. // Handle overflow with llvm.trap if no custom handler has been specified.
  2672. const std::string *handlerName =
  2673. &CGF.getLangOpts().OverflowHandler;
  2674. if (handlerName->empty()) {
  2675. // If the signed-integer-overflow sanitizer is enabled, emit a call to its
  2676. // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
  2677. if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
  2678. llvm::Value *NotOverflow = Builder.CreateNot(overflow);
  2679. SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
  2680. : SanitizerKind::UnsignedIntegerOverflow;
  2681. EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
  2682. } else
  2683. CGF.EmitTrapCheck(Builder.CreateNot(overflow));
  2684. return result;
  2685. }
  2686. // Branch in case of overflow.
  2687. llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
  2688. llvm::BasicBlock *continueBB =
  2689. CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
  2690. llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
  2691. Builder.CreateCondBr(overflow, overflowBB, continueBB);
  2692. // If an overflow handler is set, then we want to call it and then use its
  2693. // result, if it returns.
  2694. Builder.SetInsertPoint(overflowBB);
  2695. // Get the overflow handler.
  2696. llvm::Type *Int8Ty = CGF.Int8Ty;
  2697. llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
  2698. llvm::FunctionType *handlerTy =
  2699. llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
  2700. llvm::FunctionCallee handler =
  2701. CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
  2702. // Sign extend the args to 64-bit, so that we can use the same handler for
  2703. // all types of overflow.
  2704. llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
  2705. llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
  2706. // Call the handler with the two arguments, the operation, and the size of
  2707. // the result.
  2708. llvm::Value *handlerArgs[] = {
  2709. lhs,
  2710. rhs,
  2711. Builder.getInt8(OpID),
  2712. Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
  2713. };
  2714. llvm::Value *handlerResult =
  2715. CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
  2716. // Truncate the result back to the desired size.
  2717. handlerResult = Builder.CreateTrunc(handlerResult, opTy);
  2718. Builder.CreateBr(continueBB);
  2719. Builder.SetInsertPoint(continueBB);
  2720. llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
  2721. phi->addIncoming(result, initialBB);
  2722. phi->addIncoming(handlerResult, overflowBB);
  2723. return phi;
  2724. }
  2725. /// Emit pointer + index arithmetic.
  2726. static Value *emitPointerArithmetic(CodeGenFunction &CGF,
  2727. const BinOpInfo &op,
  2728. bool isSubtraction) {
  2729. // Must have binary (not unary) expr here. Unary pointer
  2730. // increment/decrement doesn't use this path.
  2731. const BinaryOperator *expr = cast<BinaryOperator>(op.E);
  2732. Value *pointer = op.LHS;
  2733. Expr *pointerOperand = expr->getLHS();
  2734. Value *index = op.RHS;
  2735. Expr *indexOperand = expr->getRHS();
  2736. // In a subtraction, the LHS is always the pointer.
  2737. if (!isSubtraction && !pointer->getType()->isPointerTy()) {
  2738. std::swap(pointer, index);
  2739. std::swap(pointerOperand, indexOperand);
  2740. }
  2741. bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
  2742. unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
  2743. auto &DL = CGF.CGM.getDataLayout();
  2744. auto PtrTy = cast<llvm::PointerType>(pointer->getType());
  2745. // Some versions of glibc and gcc use idioms (particularly in their malloc
  2746. // routines) that add a pointer-sized integer (known to be a pointer value)
  2747. // to a null pointer in order to cast the value back to an integer or as
  2748. // part of a pointer alignment algorithm. This is undefined behavior, but
  2749. // we'd like to be able to compile programs that use it.
  2750. //
  2751. // Normally, we'd generate a GEP with a null-pointer base here in response
  2752. // to that code, but it's also UB to dereference a pointer created that
  2753. // way. Instead (as an acknowledged hack to tolerate the idiom) we will
  2754. // generate a direct cast of the integer value to a pointer.
  2755. //
  2756. // The idiom (p = nullptr + N) is not met if any of the following are true:
  2757. //
  2758. // The operation is subtraction.
  2759. // The index is not pointer-sized.
  2760. // The pointer type is not byte-sized.
  2761. //
  2762. if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
  2763. op.Opcode,
  2764. expr->getLHS(),
  2765. expr->getRHS()))
  2766. return CGF.Builder.CreateIntToPtr(index, pointer->getType());
  2767. if (width != DL.getTypeSizeInBits(PtrTy)) {
  2768. // Zero-extend or sign-extend the pointer value according to
  2769. // whether the index is signed or not.
  2770. index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned,
  2771. "idx.ext");
  2772. }
  2773. // If this is subtraction, negate the index.
  2774. if (isSubtraction)
  2775. index = CGF.Builder.CreateNeg(index, "idx.neg");
  2776. if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
  2777. CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
  2778. /*Accessed*/ false);
  2779. const PointerType *pointerType
  2780. = pointerOperand->getType()->getAs<PointerType>();
  2781. if (!pointerType) {
  2782. QualType objectType = pointerOperand->getType()
  2783. ->castAs<ObjCObjectPointerType>()
  2784. ->getPointeeType();
  2785. llvm::Value *objectSize
  2786. = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
  2787. index = CGF.Builder.CreateMul(index, objectSize);
  2788. Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
  2789. result = CGF.Builder.CreateGEP(result, index, "add.ptr");
  2790. return CGF.Builder.CreateBitCast(result, pointer->getType());
  2791. }
  2792. QualType elementType = pointerType->getPointeeType();
  2793. if (const VariableArrayType *vla
  2794. = CGF.getContext().getAsVariableArrayType(elementType)) {
  2795. // The element count here is the total number of non-VLA elements.
  2796. llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
  2797. // Effectively, the multiply by the VLA size is part of the GEP.
  2798. // GEP indexes are signed, and scaling an index isn't permitted to
  2799. // signed-overflow, so we use the same semantics for our explicit
  2800. // multiply. We suppress this if overflow is not undefined behavior.
  2801. if (CGF.getLangOpts().isSignedOverflowDefined()) {
  2802. index = CGF.Builder.CreateMul(index, numElements, "vla.index");
  2803. pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
  2804. } else {
  2805. index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
  2806. pointer =
  2807. CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
  2808. op.E->getExprLoc(), "add.ptr");
  2809. }
  2810. return pointer;
  2811. }
  2812. // Explicitly handle GNU void* and function pointer arithmetic extensions. The
  2813. // GNU void* casts amount to no-ops since our void* type is i8*, but this is
  2814. // future proof.
  2815. if (elementType->isVoidType() || elementType->isFunctionType()) {
  2816. Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
  2817. result = CGF.Builder.CreateGEP(result, index, "add.ptr");
  2818. return CGF.Builder.CreateBitCast(result, pointer->getType());
  2819. }
  2820. if (CGF.getLangOpts().isSignedOverflowDefined())
  2821. return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
  2822. return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
  2823. op.E->getExprLoc(), "add.ptr");
  2824. }
  2825. // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
  2826. // Addend. Use negMul and negAdd to negate the first operand of the Mul or
  2827. // the add operand respectively. This allows fmuladd to represent a*b-c, or
  2828. // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
  2829. // efficient operations.
  2830. static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
  2831. const CodeGenFunction &CGF, CGBuilderTy &Builder,
  2832. bool negMul, bool negAdd) {
  2833. assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
  2834. Value *MulOp0 = MulOp->getOperand(0);
  2835. Value *MulOp1 = MulOp->getOperand(1);
  2836. if (negMul) {
  2837. MulOp0 =
  2838. Builder.CreateFSub(
  2839. llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
  2840. "neg");
  2841. } else if (negAdd) {
  2842. Addend =
  2843. Builder.CreateFSub(
  2844. llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
  2845. "neg");
  2846. }
  2847. Value *FMulAdd = Builder.CreateCall(
  2848. CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
  2849. {MulOp0, MulOp1, Addend});
  2850. MulOp->eraseFromParent();
  2851. return FMulAdd;
  2852. }
  2853. // Check whether it would be legal to emit an fmuladd intrinsic call to
  2854. // represent op and if so, build the fmuladd.
  2855. //
  2856. // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
  2857. // Does NOT check the type of the operation - it's assumed that this function
  2858. // will be called from contexts where it's known that the type is contractable.
  2859. static Value* tryEmitFMulAdd(const BinOpInfo &op,
  2860. const CodeGenFunction &CGF, CGBuilderTy &Builder,
  2861. bool isSub=false) {
  2862. assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
  2863. op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
  2864. "Only fadd/fsub can be the root of an fmuladd.");
  2865. // Check whether this op is marked as fusable.
  2866. if (!op.FPFeatures.allowFPContractWithinStatement())
  2867. return nullptr;
  2868. // We have a potentially fusable op. Look for a mul on one of the operands.
  2869. // Also, make sure that the mul result isn't used directly. In that case,
  2870. // there's no point creating a muladd operation.
  2871. if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
  2872. if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
  2873. LHSBinOp->use_empty())
  2874. return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
  2875. }
  2876. if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
  2877. if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
  2878. RHSBinOp->use_empty())
  2879. return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
  2880. }
  2881. return nullptr;
  2882. }
  2883. Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
  2884. if (op.LHS->getType()->isPointerTy() ||
  2885. op.RHS->getType()->isPointerTy())
  2886. return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
  2887. if (op.Ty->isSignedIntegerOrEnumerationType()) {
  2888. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  2889. case LangOptions::SOB_Defined:
  2890. return Builder.CreateAdd(op.LHS, op.RHS, "add");
  2891. case LangOptions::SOB_Undefined:
  2892. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  2893. return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
  2894. LLVM_FALLTHROUGH;
  2895. case LangOptions::SOB_Trapping:
  2896. if (CanElideOverflowCheck(CGF.getContext(), op))
  2897. return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
  2898. return EmitOverflowCheckedBinOp(op);
  2899. }
  2900. }
  2901. if (op.Ty->isUnsignedIntegerType() &&
  2902. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  2903. !CanElideOverflowCheck(CGF.getContext(), op))
  2904. return EmitOverflowCheckedBinOp(op);
  2905. if (op.LHS->getType()->isFPOrFPVectorTy()) {
  2906. // Try to form an fmuladd.
  2907. if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
  2908. return FMulAdd;
  2909. Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
  2910. return propagateFMFlags(V, op);
  2911. }
  2912. if (op.isFixedPointBinOp())
  2913. return EmitFixedPointBinOp(op);
  2914. return Builder.CreateAdd(op.LHS, op.RHS, "add");
  2915. }
  2916. /// The resulting value must be calculated with exact precision, so the operands
  2917. /// may not be the same type.
  2918. Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
  2919. using llvm::APSInt;
  2920. using llvm::ConstantInt;
  2921. const auto *BinOp = cast<BinaryOperator>(op.E);
  2922. // The result is a fixed point type and at least one of the operands is fixed
  2923. // point while the other is either fixed point or an int. This resulting type
  2924. // should be determined by Sema::handleFixedPointConversions().
  2925. QualType ResultTy = op.Ty;
  2926. QualType LHSTy = BinOp->getLHS()->getType();
  2927. QualType RHSTy = BinOp->getRHS()->getType();
  2928. ASTContext &Ctx = CGF.getContext();
  2929. Value *LHS = op.LHS;
  2930. Value *RHS = op.RHS;
  2931. auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
  2932. auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
  2933. auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
  2934. auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
  2935. // Convert the operands to the full precision type.
  2936. Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
  2937. BinOp->getExprLoc());
  2938. Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
  2939. BinOp->getExprLoc());
  2940. // Perform the actual addition.
  2941. Value *Result;
  2942. switch (BinOp->getOpcode()) {
  2943. case BO_Add: {
  2944. if (ResultFixedSema.isSaturated()) {
  2945. llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
  2946. ? llvm::Intrinsic::sadd_sat
  2947. : llvm::Intrinsic::uadd_sat;
  2948. Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
  2949. } else {
  2950. Result = Builder.CreateAdd(FullLHS, FullRHS);
  2951. }
  2952. break;
  2953. }
  2954. case BO_Sub: {
  2955. if (ResultFixedSema.isSaturated()) {
  2956. llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
  2957. ? llvm::Intrinsic::ssub_sat
  2958. : llvm::Intrinsic::usub_sat;
  2959. Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
  2960. } else {
  2961. Result = Builder.CreateSub(FullLHS, FullRHS);
  2962. }
  2963. break;
  2964. }
  2965. case BO_LT:
  2966. return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
  2967. : Builder.CreateICmpULT(FullLHS, FullRHS);
  2968. case BO_GT:
  2969. return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
  2970. : Builder.CreateICmpUGT(FullLHS, FullRHS);
  2971. case BO_LE:
  2972. return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
  2973. : Builder.CreateICmpULE(FullLHS, FullRHS);
  2974. case BO_GE:
  2975. return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
  2976. : Builder.CreateICmpUGE(FullLHS, FullRHS);
  2977. case BO_EQ:
  2978. // For equality operations, we assume any padding bits on unsigned types are
  2979. // zero'd out. They could be overwritten through non-saturating operations
  2980. // that cause overflow, but this leads to undefined behavior.
  2981. return Builder.CreateICmpEQ(FullLHS, FullRHS);
  2982. case BO_NE:
  2983. return Builder.CreateICmpNE(FullLHS, FullRHS);
  2984. case BO_Mul:
  2985. case BO_Div:
  2986. case BO_Shl:
  2987. case BO_Shr:
  2988. case BO_Cmp:
  2989. case BO_LAnd:
  2990. case BO_LOr:
  2991. case BO_MulAssign:
  2992. case BO_DivAssign:
  2993. case BO_AddAssign:
  2994. case BO_SubAssign:
  2995. case BO_ShlAssign:
  2996. case BO_ShrAssign:
  2997. llvm_unreachable("Found unimplemented fixed point binary operation");
  2998. case BO_PtrMemD:
  2999. case BO_PtrMemI:
  3000. case BO_Rem:
  3001. case BO_Xor:
  3002. case BO_And:
  3003. case BO_Or:
  3004. case BO_Assign:
  3005. case BO_RemAssign:
  3006. case BO_AndAssign:
  3007. case BO_XorAssign:
  3008. case BO_OrAssign:
  3009. case BO_Comma:
  3010. llvm_unreachable("Found unsupported binary operation for fixed point types.");
  3011. }
  3012. // Convert to the result type.
  3013. return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
  3014. BinOp->getExprLoc());
  3015. }
  3016. Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
  3017. // The LHS is always a pointer if either side is.
  3018. if (!op.LHS->getType()->isPointerTy()) {
  3019. if (op.Ty->isSignedIntegerOrEnumerationType()) {
  3020. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  3021. case LangOptions::SOB_Defined:
  3022. return Builder.CreateSub(op.LHS, op.RHS, "sub");
  3023. case LangOptions::SOB_Undefined:
  3024. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  3025. return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
  3026. LLVM_FALLTHROUGH;
  3027. case LangOptions::SOB_Trapping:
  3028. if (CanElideOverflowCheck(CGF.getContext(), op))
  3029. return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
  3030. return EmitOverflowCheckedBinOp(op);
  3031. }
  3032. }
  3033. if (op.Ty->isUnsignedIntegerType() &&
  3034. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  3035. !CanElideOverflowCheck(CGF.getContext(), op))
  3036. return EmitOverflowCheckedBinOp(op);
  3037. if (op.LHS->getType()->isFPOrFPVectorTy()) {
  3038. // Try to form an fmuladd.
  3039. if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
  3040. return FMulAdd;
  3041. Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
  3042. return propagateFMFlags(V, op);
  3043. }
  3044. if (op.isFixedPointBinOp())
  3045. return EmitFixedPointBinOp(op);
  3046. return Builder.CreateSub(op.LHS, op.RHS, "sub");
  3047. }
  3048. // If the RHS is not a pointer, then we have normal pointer
  3049. // arithmetic.
  3050. if (!op.RHS->getType()->isPointerTy())
  3051. return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
  3052. // Otherwise, this is a pointer subtraction.
  3053. // Do the raw subtraction part.
  3054. llvm::Value *LHS
  3055. = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
  3056. llvm::Value *RHS
  3057. = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
  3058. Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
  3059. // Okay, figure out the element size.
  3060. const BinaryOperator *expr = cast<BinaryOperator>(op.E);
  3061. QualType elementType = expr->getLHS()->getType()->getPointeeType();
  3062. llvm::Value *divisor = nullptr;
  3063. // For a variable-length array, this is going to be non-constant.
  3064. if (const VariableArrayType *vla
  3065. = CGF.getContext().getAsVariableArrayType(elementType)) {
  3066. auto VlaSize = CGF.getVLASize(vla);
  3067. elementType = VlaSize.Type;
  3068. divisor = VlaSize.NumElts;
  3069. // Scale the number of non-VLA elements by the non-VLA element size.
  3070. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
  3071. if (!eltSize.isOne())
  3072. divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
  3073. // For everything elese, we can just compute it, safe in the
  3074. // assumption that Sema won't let anything through that we can't
  3075. // safely compute the size of.
  3076. } else {
  3077. CharUnits elementSize;
  3078. // Handle GCC extension for pointer arithmetic on void* and
  3079. // function pointer types.
  3080. if (elementType->isVoidType() || elementType->isFunctionType())
  3081. elementSize = CharUnits::One();
  3082. else
  3083. elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  3084. // Don't even emit the divide for element size of 1.
  3085. if (elementSize.isOne())
  3086. return diffInChars;
  3087. divisor = CGF.CGM.getSize(elementSize);
  3088. }
  3089. // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
  3090. // pointer difference in C is only defined in the case where both operands
  3091. // are pointing to elements of an array.
  3092. return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
  3093. }
  3094. Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
  3095. llvm::IntegerType *Ty;
  3096. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
  3097. Ty = cast<llvm::IntegerType>(VT->getElementType());
  3098. else
  3099. Ty = cast<llvm::IntegerType>(LHS->getType());
  3100. return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
  3101. }
  3102. Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
  3103. // LLVM requires the LHS and RHS to be the same type: promote or truncate the
  3104. // RHS to the same size as the LHS.
  3105. Value *RHS = Ops.RHS;
  3106. if (Ops.LHS->getType() != RHS->getType())
  3107. RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
  3108. bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
  3109. Ops.Ty->hasSignedIntegerRepresentation() &&
  3110. !CGF.getLangOpts().isSignedOverflowDefined() &&
  3111. !CGF.getLangOpts().CPlusPlus2a;
  3112. bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
  3113. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  3114. if (CGF.getLangOpts().OpenCL)
  3115. RHS =
  3116. Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
  3117. else if ((SanitizeBase || SanitizeExponent) &&
  3118. isa<llvm::IntegerType>(Ops.LHS->getType())) {
  3119. CodeGenFunction::SanitizerScope SanScope(&CGF);
  3120. SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
  3121. llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
  3122. llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
  3123. if (SanitizeExponent) {
  3124. Checks.push_back(
  3125. std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
  3126. }
  3127. if (SanitizeBase) {
  3128. // Check whether we are shifting any non-zero bits off the top of the
  3129. // integer. We only emit this check if exponent is valid - otherwise
  3130. // instructions below will have undefined behavior themselves.
  3131. llvm::BasicBlock *Orig = Builder.GetInsertBlock();
  3132. llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
  3133. llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
  3134. Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
  3135. llvm::Value *PromotedWidthMinusOne =
  3136. (RHS == Ops.RHS) ? WidthMinusOne
  3137. : GetWidthMinusOneValue(Ops.LHS, RHS);
  3138. CGF.EmitBlock(CheckShiftBase);
  3139. llvm::Value *BitsShiftedOff = Builder.CreateLShr(
  3140. Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
  3141. /*NUW*/ true, /*NSW*/ true),
  3142. "shl.check");
  3143. if (CGF.getLangOpts().CPlusPlus) {
  3144. // In C99, we are not permitted to shift a 1 bit into the sign bit.
  3145. // Under C++11's rules, shifting a 1 bit into the sign bit is
  3146. // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
  3147. // define signed left shifts, so we use the C99 and C++11 rules there).
  3148. llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
  3149. BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
  3150. }
  3151. llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
  3152. llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
  3153. CGF.EmitBlock(Cont);
  3154. llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
  3155. BaseCheck->addIncoming(Builder.getTrue(), Orig);
  3156. BaseCheck->addIncoming(ValidBase, CheckShiftBase);
  3157. Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
  3158. }
  3159. assert(!Checks.empty());
  3160. EmitBinOpCheck(Checks, Ops);
  3161. }
  3162. return Builder.CreateShl(Ops.LHS, RHS, "shl");
  3163. }
  3164. Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
  3165. // LLVM requires the LHS and RHS to be the same type: promote or truncate the
  3166. // RHS to the same size as the LHS.
  3167. Value *RHS = Ops.RHS;
  3168. if (Ops.LHS->getType() != RHS->getType())
  3169. RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
  3170. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  3171. if (CGF.getLangOpts().OpenCL)
  3172. RHS =
  3173. Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
  3174. else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
  3175. isa<llvm::IntegerType>(Ops.LHS->getType())) {
  3176. CodeGenFunction::SanitizerScope SanScope(&CGF);
  3177. llvm::Value *Valid =
  3178. Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
  3179. EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
  3180. }
  3181. if (Ops.Ty->hasUnsignedIntegerRepresentation())
  3182. return Builder.CreateLShr(Ops.LHS, RHS, "shr");
  3183. return Builder.CreateAShr(Ops.LHS, RHS, "shr");
  3184. }
  3185. enum IntrinsicType { VCMPEQ, VCMPGT };
  3186. // return corresponding comparison intrinsic for given vector type
  3187. static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
  3188. BuiltinType::Kind ElemKind) {
  3189. switch (ElemKind) {
  3190. default: llvm_unreachable("unexpected element type");
  3191. case BuiltinType::Char_U:
  3192. case BuiltinType::UChar:
  3193. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
  3194. llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
  3195. case BuiltinType::Char_S:
  3196. case BuiltinType::SChar:
  3197. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
  3198. llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
  3199. case BuiltinType::UShort:
  3200. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
  3201. llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
  3202. case BuiltinType::Short:
  3203. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
  3204. llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
  3205. case BuiltinType::UInt:
  3206. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
  3207. llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
  3208. case BuiltinType::Int:
  3209. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
  3210. llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
  3211. case BuiltinType::ULong:
  3212. case BuiltinType::ULongLong:
  3213. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
  3214. llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
  3215. case BuiltinType::Long:
  3216. case BuiltinType::LongLong:
  3217. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
  3218. llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
  3219. case BuiltinType::Float:
  3220. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
  3221. llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
  3222. case BuiltinType::Double:
  3223. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
  3224. llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
  3225. }
  3226. }
  3227. Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
  3228. llvm::CmpInst::Predicate UICmpOpc,
  3229. llvm::CmpInst::Predicate SICmpOpc,
  3230. llvm::CmpInst::Predicate FCmpOpc) {
  3231. TestAndClearIgnoreResultAssign();
  3232. Value *Result;
  3233. QualType LHSTy = E->getLHS()->getType();
  3234. QualType RHSTy = E->getRHS()->getType();
  3235. if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
  3236. assert(E->getOpcode() == BO_EQ ||
  3237. E->getOpcode() == BO_NE);
  3238. Value *LHS = CGF.EmitScalarExpr(E->getLHS());
  3239. Value *RHS = CGF.EmitScalarExpr(E->getRHS());
  3240. Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
  3241. CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
  3242. } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
  3243. BinOpInfo BOInfo = EmitBinOps(E);
  3244. Value *LHS = BOInfo.LHS;
  3245. Value *RHS = BOInfo.RHS;
  3246. // If AltiVec, the comparison results in a numeric type, so we use
  3247. // intrinsics comparing vectors and giving 0 or 1 as a result
  3248. if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
  3249. // constants for mapping CR6 register bits to predicate result
  3250. enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
  3251. llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
  3252. // in several cases vector arguments order will be reversed
  3253. Value *FirstVecArg = LHS,
  3254. *SecondVecArg = RHS;
  3255. QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
  3256. const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
  3257. BuiltinType::Kind ElementKind = BTy->getKind();
  3258. switch(E->getOpcode()) {
  3259. default: llvm_unreachable("is not a comparison operation");
  3260. case BO_EQ:
  3261. CR6 = CR6_LT;
  3262. ID = GetIntrinsic(VCMPEQ, ElementKind);
  3263. break;
  3264. case BO_NE:
  3265. CR6 = CR6_EQ;
  3266. ID = GetIntrinsic(VCMPEQ, ElementKind);
  3267. break;
  3268. case BO_LT:
  3269. CR6 = CR6_LT;
  3270. ID = GetIntrinsic(VCMPGT, ElementKind);
  3271. std::swap(FirstVecArg, SecondVecArg);
  3272. break;
  3273. case BO_GT:
  3274. CR6 = CR6_LT;
  3275. ID = GetIntrinsic(VCMPGT, ElementKind);
  3276. break;
  3277. case BO_LE:
  3278. if (ElementKind == BuiltinType::Float) {
  3279. CR6 = CR6_LT;
  3280. ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
  3281. std::swap(FirstVecArg, SecondVecArg);
  3282. }
  3283. else {
  3284. CR6 = CR6_EQ;
  3285. ID = GetIntrinsic(VCMPGT, ElementKind);
  3286. }
  3287. break;
  3288. case BO_GE:
  3289. if (ElementKind == BuiltinType::Float) {
  3290. CR6 = CR6_LT;
  3291. ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
  3292. }
  3293. else {
  3294. CR6 = CR6_EQ;
  3295. ID = GetIntrinsic(VCMPGT, ElementKind);
  3296. std::swap(FirstVecArg, SecondVecArg);
  3297. }
  3298. break;
  3299. }
  3300. Value *CR6Param = Builder.getInt32(CR6);
  3301. llvm::Function *F = CGF.CGM.getIntrinsic(ID);
  3302. Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
  3303. // The result type of intrinsic may not be same as E->getType().
  3304. // If E->getType() is not BoolTy, EmitScalarConversion will do the
  3305. // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
  3306. // do nothing, if ResultTy is not i1 at the same time, it will cause
  3307. // crash later.
  3308. llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
  3309. if (ResultTy->getBitWidth() > 1 &&
  3310. E->getType() == CGF.getContext().BoolTy)
  3311. Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
  3312. return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
  3313. E->getExprLoc());
  3314. }
  3315. if (BOInfo.isFixedPointBinOp()) {
  3316. Result = EmitFixedPointBinOp(BOInfo);
  3317. } else if (LHS->getType()->isFPOrFPVectorTy()) {
  3318. Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
  3319. } else if (LHSTy->hasSignedIntegerRepresentation()) {
  3320. Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
  3321. } else {
  3322. // Unsigned integers and pointers.
  3323. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
  3324. !isa<llvm::ConstantPointerNull>(LHS) &&
  3325. !isa<llvm::ConstantPointerNull>(RHS)) {
  3326. // Dynamic information is required to be stripped for comparisons,
  3327. // because it could leak the dynamic information. Based on comparisons
  3328. // of pointers to dynamic objects, the optimizer can replace one pointer
  3329. // with another, which might be incorrect in presence of invariant
  3330. // groups. Comparison with null is safe because null does not carry any
  3331. // dynamic information.
  3332. if (LHSTy.mayBeDynamicClass())
  3333. LHS = Builder.CreateStripInvariantGroup(LHS);
  3334. if (RHSTy.mayBeDynamicClass())
  3335. RHS = Builder.CreateStripInvariantGroup(RHS);
  3336. }
  3337. Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
  3338. }
  3339. // If this is a vector comparison, sign extend the result to the appropriate
  3340. // vector integer type and return it (don't convert to bool).
  3341. if (LHSTy->isVectorType())
  3342. return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
  3343. } else {
  3344. // Complex Comparison: can only be an equality comparison.
  3345. CodeGenFunction::ComplexPairTy LHS, RHS;
  3346. QualType CETy;
  3347. if (auto *CTy = LHSTy->getAs<ComplexType>()) {
  3348. LHS = CGF.EmitComplexExpr(E->getLHS());
  3349. CETy = CTy->getElementType();
  3350. } else {
  3351. LHS.first = Visit(E->getLHS());
  3352. LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
  3353. CETy = LHSTy;
  3354. }
  3355. if (auto *CTy = RHSTy->getAs<ComplexType>()) {
  3356. RHS = CGF.EmitComplexExpr(E->getRHS());
  3357. assert(CGF.getContext().hasSameUnqualifiedType(CETy,
  3358. CTy->getElementType()) &&
  3359. "The element types must always match.");
  3360. (void)CTy;
  3361. } else {
  3362. RHS.first = Visit(E->getRHS());
  3363. RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
  3364. assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
  3365. "The element types must always match.");
  3366. }
  3367. Value *ResultR, *ResultI;
  3368. if (CETy->isRealFloatingType()) {
  3369. ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
  3370. ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
  3371. } else {
  3372. // Complex comparisons can only be equality comparisons. As such, signed
  3373. // and unsigned opcodes are the same.
  3374. ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
  3375. ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
  3376. }
  3377. if (E->getOpcode() == BO_EQ) {
  3378. Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
  3379. } else {
  3380. assert(E->getOpcode() == BO_NE &&
  3381. "Complex comparison other than == or != ?");
  3382. Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
  3383. }
  3384. }
  3385. return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
  3386. E->getExprLoc());
  3387. }
  3388. Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  3389. bool Ignore = TestAndClearIgnoreResultAssign();
  3390. Value *RHS;
  3391. LValue LHS;
  3392. switch (E->getLHS()->getType().getObjCLifetime()) {
  3393. case Qualifiers::OCL_Strong:
  3394. std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
  3395. break;
  3396. case Qualifiers::OCL_Autoreleasing:
  3397. std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
  3398. break;
  3399. case Qualifiers::OCL_ExplicitNone:
  3400. std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
  3401. break;
  3402. case Qualifiers::OCL_Weak:
  3403. RHS = Visit(E->getRHS());
  3404. LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  3405. RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
  3406. break;
  3407. case Qualifiers::OCL_None:
  3408. // __block variables need to have the rhs evaluated first, plus
  3409. // this should improve codegen just a little.
  3410. RHS = Visit(E->getRHS());
  3411. LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  3412. // Store the value into the LHS. Bit-fields are handled specially
  3413. // because the result is altered by the store, i.e., [C99 6.5.16p1]
  3414. // 'An assignment expression has the value of the left operand after
  3415. // the assignment...'.
  3416. if (LHS.isBitField()) {
  3417. CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
  3418. } else {
  3419. CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
  3420. CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
  3421. }
  3422. }
  3423. // If the result is clearly ignored, return now.
  3424. if (Ignore)
  3425. return nullptr;
  3426. // The result of an assignment in C is the assigned r-value.
  3427. if (!CGF.getLangOpts().CPlusPlus)
  3428. return RHS;
  3429. // If the lvalue is non-volatile, return the computed value of the assignment.
  3430. if (!LHS.isVolatileQualified())
  3431. return RHS;
  3432. // Otherwise, reload the value.
  3433. return EmitLoadOfLValue(LHS, E->getExprLoc());
  3434. }
  3435. Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
  3436. // Perform vector logical and on comparisons with zero vectors.
  3437. if (E->getType()->isVectorType()) {
  3438. CGF.incrementProfileCounter(E);
  3439. Value *LHS = Visit(E->getLHS());
  3440. Value *RHS = Visit(E->getRHS());
  3441. Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
  3442. if (LHS->getType()->isFPOrFPVectorTy()) {
  3443. LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
  3444. RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
  3445. } else {
  3446. LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
  3447. RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
  3448. }
  3449. Value *And = Builder.CreateAnd(LHS, RHS);
  3450. return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
  3451. }
  3452. llvm::Type *ResTy = ConvertType(E->getType());
  3453. // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
  3454. // If we have 1 && X, just emit X without inserting the control flow.
  3455. bool LHSCondVal;
  3456. if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
  3457. if (LHSCondVal) { // If we have 1 && X, just emit X.
  3458. CGF.incrementProfileCounter(E);
  3459. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3460. // ZExt result to int or bool.
  3461. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
  3462. }
  3463. // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
  3464. if (!CGF.ContainsLabel(E->getRHS()))
  3465. return llvm::Constant::getNullValue(ResTy);
  3466. }
  3467. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
  3468. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
  3469. CodeGenFunction::ConditionalEvaluation eval(CGF);
  3470. // Branch on the LHS first. If it is false, go to the failure (cont) block.
  3471. CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
  3472. CGF.getProfileCount(E->getRHS()));
  3473. // Any edges into the ContBlock are now from an (indeterminate number of)
  3474. // edges from this first condition. All of these values will be false. Start
  3475. // setting up the PHI node in the Cont Block for this.
  3476. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
  3477. "", ContBlock);
  3478. for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
  3479. PI != PE; ++PI)
  3480. PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
  3481. eval.begin(CGF);
  3482. CGF.EmitBlock(RHSBlock);
  3483. CGF.incrementProfileCounter(E);
  3484. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3485. eval.end(CGF);
  3486. // Reaquire the RHS block, as there may be subblocks inserted.
  3487. RHSBlock = Builder.GetInsertBlock();
  3488. // Emit an unconditional branch from this block to ContBlock.
  3489. {
  3490. // There is no need to emit line number for unconditional branch.
  3491. auto NL = ApplyDebugLocation::CreateEmpty(CGF);
  3492. CGF.EmitBlock(ContBlock);
  3493. }
  3494. // Insert an entry into the phi node for the edge with the value of RHSCond.
  3495. PN->addIncoming(RHSCond, RHSBlock);
  3496. // Artificial location to preserve the scope information
  3497. {
  3498. auto NL = ApplyDebugLocation::CreateArtificial(CGF);
  3499. PN->setDebugLoc(Builder.getCurrentDebugLocation());
  3500. }
  3501. // ZExt result to int.
  3502. return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
  3503. }
  3504. Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
  3505. // Perform vector logical or on comparisons with zero vectors.
  3506. if (E->getType()->isVectorType()) {
  3507. CGF.incrementProfileCounter(E);
  3508. Value *LHS = Visit(E->getLHS());
  3509. Value *RHS = Visit(E->getRHS());
  3510. Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
  3511. if (LHS->getType()->isFPOrFPVectorTy()) {
  3512. LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
  3513. RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
  3514. } else {
  3515. LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
  3516. RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
  3517. }
  3518. Value *Or = Builder.CreateOr(LHS, RHS);
  3519. return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
  3520. }
  3521. llvm::Type *ResTy = ConvertType(E->getType());
  3522. // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
  3523. // If we have 0 || X, just emit X without inserting the control flow.
  3524. bool LHSCondVal;
  3525. if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
  3526. if (!LHSCondVal) { // If we have 0 || X, just emit X.
  3527. CGF.incrementProfileCounter(E);
  3528. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3529. // ZExt result to int or bool.
  3530. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
  3531. }
  3532. // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
  3533. if (!CGF.ContainsLabel(E->getRHS()))
  3534. return llvm::ConstantInt::get(ResTy, 1);
  3535. }
  3536. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
  3537. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
  3538. CodeGenFunction::ConditionalEvaluation eval(CGF);
  3539. // Branch on the LHS first. If it is true, go to the success (cont) block.
  3540. CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
  3541. CGF.getCurrentProfileCount() -
  3542. CGF.getProfileCount(E->getRHS()));
  3543. // Any edges into the ContBlock are now from an (indeterminate number of)
  3544. // edges from this first condition. All of these values will be true. Start
  3545. // setting up the PHI node in the Cont Block for this.
  3546. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
  3547. "", ContBlock);
  3548. for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
  3549. PI != PE; ++PI)
  3550. PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
  3551. eval.begin(CGF);
  3552. // Emit the RHS condition as a bool value.
  3553. CGF.EmitBlock(RHSBlock);
  3554. CGF.incrementProfileCounter(E);
  3555. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3556. eval.end(CGF);
  3557. // Reaquire the RHS block, as there may be subblocks inserted.
  3558. RHSBlock = Builder.GetInsertBlock();
  3559. // Emit an unconditional branch from this block to ContBlock. Insert an entry
  3560. // into the phi node for the edge with the value of RHSCond.
  3561. CGF.EmitBlock(ContBlock);
  3562. PN->addIncoming(RHSCond, RHSBlock);
  3563. // ZExt result to int.
  3564. return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
  3565. }
  3566. Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
  3567. CGF.EmitIgnoredExpr(E->getLHS());
  3568. CGF.EnsureInsertPoint();
  3569. return Visit(E->getRHS());
  3570. }
  3571. //===----------------------------------------------------------------------===//
  3572. // Other Operators
  3573. //===----------------------------------------------------------------------===//
  3574. /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
  3575. /// expression is cheap enough and side-effect-free enough to evaluate
  3576. /// unconditionally instead of conditionally. This is used to convert control
  3577. /// flow into selects in some cases.
  3578. static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
  3579. CodeGenFunction &CGF) {
  3580. // Anything that is an integer or floating point constant is fine.
  3581. return E->IgnoreParens()->isEvaluatable(CGF.getContext());
  3582. // Even non-volatile automatic variables can't be evaluated unconditionally.
  3583. // Referencing a thread_local may cause non-trivial initialization work to
  3584. // occur. If we're inside a lambda and one of the variables is from the scope
  3585. // outside the lambda, that function may have returned already. Reading its
  3586. // locals is a bad idea. Also, these reads may introduce races there didn't
  3587. // exist in the source-level program.
  3588. }
  3589. Value *ScalarExprEmitter::
  3590. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  3591. TestAndClearIgnoreResultAssign();
  3592. // Bind the common expression if necessary.
  3593. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  3594. Expr *condExpr = E->getCond();
  3595. Expr *lhsExpr = E->getTrueExpr();
  3596. Expr *rhsExpr = E->getFalseExpr();
  3597. // If the condition constant folds and can be elided, try to avoid emitting
  3598. // the condition and the dead arm.
  3599. bool CondExprBool;
  3600. if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  3601. Expr *live = lhsExpr, *dead = rhsExpr;
  3602. if (!CondExprBool) std::swap(live, dead);
  3603. // If the dead side doesn't have labels we need, just emit the Live part.
  3604. if (!CGF.ContainsLabel(dead)) {
  3605. if (CondExprBool)
  3606. CGF.incrementProfileCounter(E);
  3607. Value *Result = Visit(live);
  3608. // If the live part is a throw expression, it acts like it has a void
  3609. // type, so evaluating it returns a null Value*. However, a conditional
  3610. // with non-void type must return a non-null Value*.
  3611. if (!Result && !E->getType()->isVoidType())
  3612. Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  3613. return Result;
  3614. }
  3615. }
  3616. // OpenCL: If the condition is a vector, we can treat this condition like
  3617. // the select function.
  3618. if (CGF.getLangOpts().OpenCL
  3619. && condExpr->getType()->isVectorType()) {
  3620. CGF.incrementProfileCounter(E);
  3621. llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
  3622. llvm::Value *LHS = Visit(lhsExpr);
  3623. llvm::Value *RHS = Visit(rhsExpr);
  3624. llvm::Type *condType = ConvertType(condExpr->getType());
  3625. llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
  3626. unsigned numElem = vecTy->getNumElements();
  3627. llvm::Type *elemType = vecTy->getElementType();
  3628. llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
  3629. llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
  3630. llvm::Value *tmp = Builder.CreateSExt(TestMSB,
  3631. llvm::VectorType::get(elemType,
  3632. numElem),
  3633. "sext");
  3634. llvm::Value *tmp2 = Builder.CreateNot(tmp);
  3635. // Cast float to int to perform ANDs if necessary.
  3636. llvm::Value *RHSTmp = RHS;
  3637. llvm::Value *LHSTmp = LHS;
  3638. bool wasCast = false;
  3639. llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
  3640. if (rhsVTy->getElementType()->isFloatingPointTy()) {
  3641. RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
  3642. LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
  3643. wasCast = true;
  3644. }
  3645. llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
  3646. llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
  3647. llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
  3648. if (wasCast)
  3649. tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
  3650. return tmp5;
  3651. }
  3652. // If this is a really simple expression (like x ? 4 : 5), emit this as a
  3653. // select instead of as control flow. We can only do this if it is cheap and
  3654. // safe to evaluate the LHS and RHS unconditionally.
  3655. if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
  3656. isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
  3657. llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
  3658. llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
  3659. CGF.incrementProfileCounter(E, StepV);
  3660. llvm::Value *LHS = Visit(lhsExpr);
  3661. llvm::Value *RHS = Visit(rhsExpr);
  3662. if (!LHS) {
  3663. // If the conditional has void type, make sure we return a null Value*.
  3664. assert(!RHS && "LHS and RHS types must match");
  3665. return nullptr;
  3666. }
  3667. return Builder.CreateSelect(CondV, LHS, RHS, "cond");
  3668. }
  3669. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  3670. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  3671. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  3672. CodeGenFunction::ConditionalEvaluation eval(CGF);
  3673. CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
  3674. CGF.getProfileCount(lhsExpr));
  3675. CGF.EmitBlock(LHSBlock);
  3676. CGF.incrementProfileCounter(E);
  3677. eval.begin(CGF);
  3678. Value *LHS = Visit(lhsExpr);
  3679. eval.end(CGF);
  3680. LHSBlock = Builder.GetInsertBlock();
  3681. Builder.CreateBr(ContBlock);
  3682. CGF.EmitBlock(RHSBlock);
  3683. eval.begin(CGF);
  3684. Value *RHS = Visit(rhsExpr);
  3685. eval.end(CGF);
  3686. RHSBlock = Builder.GetInsertBlock();
  3687. CGF.EmitBlock(ContBlock);
  3688. // If the LHS or RHS is a throw expression, it will be legitimately null.
  3689. if (!LHS)
  3690. return RHS;
  3691. if (!RHS)
  3692. return LHS;
  3693. // Create a PHI node for the real part.
  3694. llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
  3695. PN->addIncoming(LHS, LHSBlock);
  3696. PN->addIncoming(RHS, RHSBlock);
  3697. return PN;
  3698. }
  3699. Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
  3700. return Visit(E->getChosenSubExpr());
  3701. }
  3702. Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
  3703. QualType Ty = VE->getType();
  3704. if (Ty->isVariablyModifiedType())
  3705. CGF.EmitVariablyModifiedType(Ty);
  3706. Address ArgValue = Address::invalid();
  3707. Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
  3708. llvm::Type *ArgTy = ConvertType(VE->getType());
  3709. // If EmitVAArg fails, emit an error.
  3710. if (!ArgPtr.isValid()) {
  3711. CGF.ErrorUnsupported(VE, "va_arg expression");
  3712. return llvm::UndefValue::get(ArgTy);
  3713. }
  3714. // FIXME Volatility.
  3715. llvm::Value *Val = Builder.CreateLoad(ArgPtr);
  3716. // If EmitVAArg promoted the type, we must truncate it.
  3717. if (ArgTy != Val->getType()) {
  3718. if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
  3719. Val = Builder.CreateIntToPtr(Val, ArgTy);
  3720. else
  3721. Val = Builder.CreateTrunc(Val, ArgTy);
  3722. }
  3723. return Val;
  3724. }
  3725. Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
  3726. return CGF.EmitBlockLiteral(block);
  3727. }
  3728. // Convert a vec3 to vec4, or vice versa.
  3729. static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
  3730. Value *Src, unsigned NumElementsDst) {
  3731. llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
  3732. SmallVector<llvm::Constant*, 4> Args;
  3733. Args.push_back(Builder.getInt32(0));
  3734. Args.push_back(Builder.getInt32(1));
  3735. Args.push_back(Builder.getInt32(2));
  3736. if (NumElementsDst == 4)
  3737. Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
  3738. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  3739. return Builder.CreateShuffleVector(Src, UnV, Mask);
  3740. }
  3741. // Create cast instructions for converting LLVM value \p Src to LLVM type \p
  3742. // DstTy. \p Src has the same size as \p DstTy. Both are single value types
  3743. // but could be scalar or vectors of different lengths, and either can be
  3744. // pointer.
  3745. // There are 4 cases:
  3746. // 1. non-pointer -> non-pointer : needs 1 bitcast
  3747. // 2. pointer -> pointer : needs 1 bitcast or addrspacecast
  3748. // 3. pointer -> non-pointer
  3749. // a) pointer -> intptr_t : needs 1 ptrtoint
  3750. // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
  3751. // 4. non-pointer -> pointer
  3752. // a) intptr_t -> pointer : needs 1 inttoptr
  3753. // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
  3754. // Note: for cases 3b and 4b two casts are required since LLVM casts do not
  3755. // allow casting directly between pointer types and non-integer non-pointer
  3756. // types.
  3757. static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
  3758. const llvm::DataLayout &DL,
  3759. Value *Src, llvm::Type *DstTy,
  3760. StringRef Name = "") {
  3761. auto SrcTy = Src->getType();
  3762. // Case 1.
  3763. if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
  3764. return Builder.CreateBitCast(Src, DstTy, Name);
  3765. // Case 2.
  3766. if (SrcTy->isPointerTy() && DstTy->isPointerTy())
  3767. return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
  3768. // Case 3.
  3769. if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
  3770. // Case 3b.
  3771. if (!DstTy->isIntegerTy())
  3772. Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
  3773. // Cases 3a and 3b.
  3774. return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
  3775. }
  3776. // Case 4b.
  3777. if (!SrcTy->isIntegerTy())
  3778. Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
  3779. // Cases 4a and 4b.
  3780. return Builder.CreateIntToPtr(Src, DstTy, Name);
  3781. }
  3782. Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
  3783. Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
  3784. llvm::Type *DstTy = ConvertType(E->getType());
  3785. llvm::Type *SrcTy = Src->getType();
  3786. unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
  3787. cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
  3788. unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
  3789. cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
  3790. // Going from vec3 to non-vec3 is a special case and requires a shuffle
  3791. // vector to get a vec4, then a bitcast if the target type is different.
  3792. if (NumElementsSrc == 3 && NumElementsDst != 3) {
  3793. Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
  3794. if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
  3795. Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
  3796. DstTy);
  3797. }
  3798. Src->setName("astype");
  3799. return Src;
  3800. }
  3801. // Going from non-vec3 to vec3 is a special case and requires a bitcast
  3802. // to vec4 if the original type is not vec4, then a shuffle vector to
  3803. // get a vec3.
  3804. if (NumElementsSrc != 3 && NumElementsDst == 3) {
  3805. if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
  3806. auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
  3807. Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
  3808. Vec4Ty);
  3809. }
  3810. Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
  3811. Src->setName("astype");
  3812. return Src;
  3813. }
  3814. return Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
  3815. Src, DstTy, "astype");
  3816. }
  3817. Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
  3818. return CGF.EmitAtomicExpr(E).getScalarVal();
  3819. }
  3820. //===----------------------------------------------------------------------===//
  3821. // Entry Point into this File
  3822. //===----------------------------------------------------------------------===//
  3823. /// Emit the computation of the specified expression of scalar type, ignoring
  3824. /// the result.
  3825. Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
  3826. assert(E && hasScalarEvaluationKind(E->getType()) &&
  3827. "Invalid scalar expression to emit");
  3828. return ScalarExprEmitter(*this, IgnoreResultAssign)
  3829. .Visit(const_cast<Expr *>(E));
  3830. }
  3831. /// Emit a conversion from the specified type to the specified destination type,
  3832. /// both of which are LLVM scalar types.
  3833. Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
  3834. QualType DstTy,
  3835. SourceLocation Loc) {
  3836. assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
  3837. "Invalid scalar expression to emit");
  3838. return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
  3839. }
  3840. /// Emit a conversion from the specified complex type to the specified
  3841. /// destination type, where the destination type is an LLVM scalar type.
  3842. Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
  3843. QualType SrcTy,
  3844. QualType DstTy,
  3845. SourceLocation Loc) {
  3846. assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
  3847. "Invalid complex -> scalar conversion");
  3848. return ScalarExprEmitter(*this)
  3849. .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
  3850. }
  3851. llvm::Value *CodeGenFunction::
  3852. EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  3853. bool isInc, bool isPre) {
  3854. return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
  3855. }
  3856. LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
  3857. // object->isa or (*object).isa
  3858. // Generate code as for: *(Class*)object
  3859. Expr *BaseExpr = E->getBase();
  3860. Address Addr = Address::invalid();
  3861. if (BaseExpr->isRValue()) {
  3862. Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
  3863. } else {
  3864. Addr = EmitLValue(BaseExpr).getAddress();
  3865. }
  3866. // Cast the address to Class*.
  3867. Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
  3868. return MakeAddrLValue(Addr, E->getType());
  3869. }
  3870. LValue CodeGenFunction::EmitCompoundAssignmentLValue(
  3871. const CompoundAssignOperator *E) {
  3872. ScalarExprEmitter Scalar(*this);
  3873. Value *Result = nullptr;
  3874. switch (E->getOpcode()) {
  3875. #define COMPOUND_OP(Op) \
  3876. case BO_##Op##Assign: \
  3877. return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
  3878. Result)
  3879. COMPOUND_OP(Mul);
  3880. COMPOUND_OP(Div);
  3881. COMPOUND_OP(Rem);
  3882. COMPOUND_OP(Add);
  3883. COMPOUND_OP(Sub);
  3884. COMPOUND_OP(Shl);
  3885. COMPOUND_OP(Shr);
  3886. COMPOUND_OP(And);
  3887. COMPOUND_OP(Xor);
  3888. COMPOUND_OP(Or);
  3889. #undef COMPOUND_OP
  3890. case BO_PtrMemD:
  3891. case BO_PtrMemI:
  3892. case BO_Mul:
  3893. case BO_Div:
  3894. case BO_Rem:
  3895. case BO_Add:
  3896. case BO_Sub:
  3897. case BO_Shl:
  3898. case BO_Shr:
  3899. case BO_LT:
  3900. case BO_GT:
  3901. case BO_LE:
  3902. case BO_GE:
  3903. case BO_EQ:
  3904. case BO_NE:
  3905. case BO_Cmp:
  3906. case BO_And:
  3907. case BO_Xor:
  3908. case BO_Or:
  3909. case BO_LAnd:
  3910. case BO_LOr:
  3911. case BO_Assign:
  3912. case BO_Comma:
  3913. llvm_unreachable("Not valid compound assignment operators");
  3914. }
  3915. llvm_unreachable("Unhandled compound assignment operator");
  3916. }
  3917. struct GEPOffsetAndOverflow {
  3918. // The total (signed) byte offset for the GEP.
  3919. llvm::Value *TotalOffset;
  3920. // The offset overflow flag - true if the total offset overflows.
  3921. llvm::Value *OffsetOverflows;
  3922. };
  3923. /// Evaluate given GEPVal, which must be an inbounds GEP,
  3924. /// and compute the total offset it applies from it's base pointer BasePtr.
  3925. /// Returns offset in bytes and a boolean flag whether an overflow happened
  3926. /// during evaluation.
  3927. static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
  3928. llvm::LLVMContext &VMContext,
  3929. CodeGenModule &CGM,
  3930. CGBuilderTy Builder) {
  3931. auto *GEP = cast<llvm::GEPOperator>(GEPVal);
  3932. assert(GEP->isInBounds() && "Expected inbounds GEP");
  3933. const auto &DL = CGM.getDataLayout();
  3934. auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
  3935. // Grab references to the signed add/mul overflow intrinsics for intptr_t.
  3936. auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
  3937. auto *SAddIntrinsic =
  3938. CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
  3939. auto *SMulIntrinsic =
  3940. CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
  3941. // The total (signed) byte offset for the GEP.
  3942. llvm::Value *TotalOffset = nullptr;
  3943. // The offset overflow flag - true if the total offset overflows.
  3944. llvm::Value *OffsetOverflows = Builder.getFalse();
  3945. /// Return the result of the given binary operation.
  3946. auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
  3947. llvm::Value *RHS) -> llvm::Value * {
  3948. assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
  3949. // If the operands are constants, return a constant result.
  3950. if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
  3951. if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
  3952. llvm::APInt N;
  3953. bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
  3954. /*Signed=*/true, N);
  3955. if (HasOverflow)
  3956. OffsetOverflows = Builder.getTrue();
  3957. return llvm::ConstantInt::get(VMContext, N);
  3958. }
  3959. }
  3960. // Otherwise, compute the result with checked arithmetic.
  3961. auto *ResultAndOverflow = Builder.CreateCall(
  3962. (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
  3963. OffsetOverflows = Builder.CreateOr(
  3964. Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
  3965. return Builder.CreateExtractValue(ResultAndOverflow, 0);
  3966. };
  3967. // Determine the total byte offset by looking at each GEP operand.
  3968. for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
  3969. GTI != GTE; ++GTI) {
  3970. llvm::Value *LocalOffset;
  3971. auto *Index = GTI.getOperand();
  3972. // Compute the local offset contributed by this indexing step:
  3973. if (auto *STy = GTI.getStructTypeOrNull()) {
  3974. // For struct indexing, the local offset is the byte position of the
  3975. // specified field.
  3976. unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
  3977. LocalOffset = llvm::ConstantInt::get(
  3978. IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
  3979. } else {
  3980. // Otherwise this is array-like indexing. The local offset is the index
  3981. // multiplied by the element size.
  3982. auto *ElementSize = llvm::ConstantInt::get(
  3983. IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
  3984. auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
  3985. LocalOffset = eval(BO_Mul, ElementSize, IndexS);
  3986. }
  3987. // If this is the first offset, set it as the total offset. Otherwise, add
  3988. // the local offset into the running total.
  3989. if (!TotalOffset || TotalOffset == Zero)
  3990. TotalOffset = LocalOffset;
  3991. else
  3992. TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
  3993. }
  3994. return {TotalOffset, OffsetOverflows};
  3995. }
  3996. Value *
  3997. CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
  3998. bool SignedIndices, bool IsSubtraction,
  3999. SourceLocation Loc, const Twine &Name) {
  4000. Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
  4001. // If the pointer overflow sanitizer isn't enabled, do nothing.
  4002. if (!SanOpts.has(SanitizerKind::PointerOverflow))
  4003. return GEPVal;
  4004. // If the GEP has already been reduced to a constant, leave it be.
  4005. if (isa<llvm::Constant>(GEPVal))
  4006. return GEPVal;
  4007. // Only check for overflows in the default address space.
  4008. if (GEPVal->getType()->getPointerAddressSpace())
  4009. return GEPVal;
  4010. SanitizerScope SanScope(this);
  4011. GEPOffsetAndOverflow EvaluatedGEP =
  4012. EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
  4013. auto *GEP = cast<llvm::GEPOperator>(GEPVal);
  4014. const auto &DL = CGM.getDataLayout();
  4015. auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
  4016. auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
  4017. // Common case: if the total offset is zero, don't emit a check.
  4018. if (EvaluatedGEP.TotalOffset == Zero)
  4019. return GEPVal;
  4020. // Now that we've computed the total offset, add it to the base pointer (with
  4021. // wrapping semantics).
  4022. auto *IntPtr = Builder.CreatePtrToInt(GEP->getPointerOperand(), IntPtrTy);
  4023. auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
  4024. llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 1> Checks;
  4025. // The GEP is valid if:
  4026. // 1) The total offset doesn't overflow, and
  4027. // 2) The sign of the difference between the computed address and the base
  4028. // pointer matches the sign of the total offset.
  4029. llvm::Value *ValidGEP;
  4030. auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
  4031. if (SignedIndices) {
  4032. // GEP is computed as `unsigned base + signed offset`, therefore:
  4033. // * If offset was positive, then the computed pointer can not be
  4034. // [unsigned] less than the base pointer, unless it overflowed.
  4035. // * If offset was negative, then the computed pointer can not be
  4036. // [unsigned] greater than the bas pointere, unless it overflowed.
  4037. auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
  4038. auto *PosOrZeroOffset =
  4039. Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
  4040. llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
  4041. ValidGEP = Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
  4042. } else if (!IsSubtraction) {
  4043. // GEP is computed as `unsigned base + unsigned offset`, therefore the
  4044. // computed pointer can not be [unsigned] less than base pointer,
  4045. // unless there was an overflow.
  4046. // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
  4047. ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
  4048. } else {
  4049. // GEP is computed as `unsigned base - unsigned offset`, therefore the
  4050. // computed pointer can not be [unsigned] greater than base pointer,
  4051. // unless there was an overflow.
  4052. // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
  4053. ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
  4054. }
  4055. ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
  4056. Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
  4057. assert(!Checks.empty() && "Should have produced some checks.");
  4058. llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
  4059. // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
  4060. llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
  4061. EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
  4062. return GEPVal;
  4063. }