CGExprScalar.cpp 175 KB

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