CodeGenFunction.h 209 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903
  1. //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is the internal per-function state used for llvm translation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  13. #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  14. #include "CGBuilder.h"
  15. #include "CGDebugInfo.h"
  16. #include "CGLoopInfo.h"
  17. #include "CGValue.h"
  18. #include "CodeGenModule.h"
  19. #include "CodeGenPGO.h"
  20. #include "EHScopeStack.h"
  21. #include "VarBypassDetector.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/CurrentSourceLocExprScope.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprObjC.h"
  26. #include "clang/AST/ExprOpenMP.h"
  27. #include "clang/AST/StmtOpenMP.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/Basic/ABI.h"
  30. #include "clang/Basic/CapturedStmt.h"
  31. #include "clang/Basic/CodeGenOptions.h"
  32. #include "clang/Basic/OpenMPKinds.h"
  33. #include "clang/Basic/TargetInfo.h"
  34. #include "llvm/ADT/ArrayRef.h"
  35. #include "llvm/ADT/DenseMap.h"
  36. #include "llvm/ADT/MapVector.h"
  37. #include "llvm/ADT/SmallVector.h"
  38. #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
  39. #include "llvm/IR/ValueHandle.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Transforms/Utils/SanitizerStats.h"
  42. namespace llvm {
  43. class BasicBlock;
  44. class LLVMContext;
  45. class MDNode;
  46. class SwitchInst;
  47. class Twine;
  48. class Value;
  49. class CanonicalLoopInfo;
  50. }
  51. namespace clang {
  52. class ASTContext;
  53. class CXXDestructorDecl;
  54. class CXXForRangeStmt;
  55. class CXXTryStmt;
  56. class Decl;
  57. class LabelDecl;
  58. class FunctionDecl;
  59. class FunctionProtoType;
  60. class LabelStmt;
  61. class ObjCContainerDecl;
  62. class ObjCInterfaceDecl;
  63. class ObjCIvarDecl;
  64. class ObjCMethodDecl;
  65. class ObjCImplementationDecl;
  66. class ObjCPropertyImplDecl;
  67. class TargetInfo;
  68. class VarDecl;
  69. class ObjCForCollectionStmt;
  70. class ObjCAtTryStmt;
  71. class ObjCAtThrowStmt;
  72. class ObjCAtSynchronizedStmt;
  73. class ObjCAutoreleasePoolStmt;
  74. class OMPUseDevicePtrClause;
  75. class OMPUseDeviceAddrClause;
  76. class SVETypeFlags;
  77. class OMPExecutableDirective;
  78. namespace analyze_os_log {
  79. class OSLogBufferLayout;
  80. }
  81. namespace CodeGen {
  82. class CodeGenTypes;
  83. class CGCallee;
  84. class CGFunctionInfo;
  85. class CGBlockInfo;
  86. class CGCXXABI;
  87. class BlockByrefHelpers;
  88. class BlockByrefInfo;
  89. class BlockFieldFlags;
  90. class RegionCodeGenTy;
  91. class TargetCodeGenInfo;
  92. struct OMPTaskDataTy;
  93. struct CGCoroData;
  94. /// The kind of evaluation to perform on values of a particular
  95. /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
  96. /// CGExprAgg?
  97. ///
  98. /// TODO: should vectors maybe be split out into their own thing?
  99. enum TypeEvaluationKind {
  100. TEK_Scalar,
  101. TEK_Complex,
  102. TEK_Aggregate
  103. };
  104. #define LIST_SANITIZER_CHECKS \
  105. SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
  106. SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
  107. SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
  108. SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
  109. SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
  110. SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
  111. SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 1) \
  112. SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \
  113. SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
  114. SANITIZER_CHECK(InvalidObjCCast, invalid_objc_cast, 0) \
  115. SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
  116. SANITIZER_CHECK(MissingReturn, missing_return, 0) \
  117. SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
  118. SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
  119. SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
  120. SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
  121. SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
  122. SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
  123. SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
  124. SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
  125. SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
  126. SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
  127. SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
  128. SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \
  129. SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
  130. enum SanitizerHandler {
  131. #define SANITIZER_CHECK(Enum, Name, Version) Enum,
  132. LIST_SANITIZER_CHECKS
  133. #undef SANITIZER_CHECK
  134. };
  135. /// Helper class with most of the code for saving a value for a
  136. /// conditional expression cleanup.
  137. struct DominatingLLVMValue {
  138. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  139. /// Answer whether the given value needs extra work to be saved.
  140. static bool needsSaving(llvm::Value *value) {
  141. // If it's not an instruction, we don't need to save.
  142. if (!isa<llvm::Instruction>(value)) return false;
  143. // If it's an instruction in the entry block, we don't need to save.
  144. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  145. return (block != &block->getParent()->getEntryBlock());
  146. }
  147. static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
  148. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
  149. };
  150. /// A partial specialization of DominatingValue for llvm::Values that
  151. /// might be llvm::Instructions.
  152. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  153. typedef T *type;
  154. static type restore(CodeGenFunction &CGF, saved_type value) {
  155. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  156. }
  157. };
  158. /// A specialization of DominatingValue for Address.
  159. template <> struct DominatingValue<Address> {
  160. typedef Address type;
  161. struct saved_type {
  162. DominatingLLVMValue::saved_type SavedValue;
  163. llvm::Type *ElementType;
  164. CharUnits Alignment;
  165. };
  166. static bool needsSaving(type value) {
  167. return DominatingLLVMValue::needsSaving(value.getPointer());
  168. }
  169. static saved_type save(CodeGenFunction &CGF, type value) {
  170. return { DominatingLLVMValue::save(CGF, value.getPointer()),
  171. value.getElementType(), value.getAlignment() };
  172. }
  173. static type restore(CodeGenFunction &CGF, saved_type value) {
  174. return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
  175. value.ElementType, value.Alignment);
  176. }
  177. };
  178. /// A specialization of DominatingValue for RValue.
  179. template <> struct DominatingValue<RValue> {
  180. typedef RValue type;
  181. class saved_type {
  182. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  183. AggregateAddress, ComplexAddress };
  184. llvm::Value *Value;
  185. unsigned K : 3;
  186. unsigned Align : 29;
  187. saved_type(llvm::Value *v, Kind k, unsigned a = 0)
  188. : Value(v), K(k), Align(a) {}
  189. public:
  190. static bool needsSaving(RValue value);
  191. static saved_type save(CodeGenFunction &CGF, RValue value);
  192. RValue restore(CodeGenFunction &CGF);
  193. // implementations in CGCleanup.cpp
  194. };
  195. static bool needsSaving(type value) {
  196. return saved_type::needsSaving(value);
  197. }
  198. static saved_type save(CodeGenFunction &CGF, type value) {
  199. return saved_type::save(CGF, value);
  200. }
  201. static type restore(CodeGenFunction &CGF, saved_type value) {
  202. return value.restore(CGF);
  203. }
  204. };
  205. /// CodeGenFunction - This class organizes the per-function state that is used
  206. /// while generating LLVM code.
  207. class CodeGenFunction : public CodeGenTypeCache {
  208. CodeGenFunction(const CodeGenFunction &) = delete;
  209. void operator=(const CodeGenFunction &) = delete;
  210. friend class CGCXXABI;
  211. public:
  212. /// A jump destination is an abstract label, branching to which may
  213. /// require a jump out through normal cleanups.
  214. struct JumpDest {
  215. JumpDest() : Block(nullptr), Index(0) {}
  216. JumpDest(llvm::BasicBlock *Block, EHScopeStack::stable_iterator Depth,
  217. unsigned Index)
  218. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  219. bool isValid() const { return Block != nullptr; }
  220. llvm::BasicBlock *getBlock() const { return Block; }
  221. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  222. unsigned getDestIndex() const { return Index; }
  223. // This should be used cautiously.
  224. void setScopeDepth(EHScopeStack::stable_iterator depth) {
  225. ScopeDepth = depth;
  226. }
  227. private:
  228. llvm::BasicBlock *Block;
  229. EHScopeStack::stable_iterator ScopeDepth;
  230. unsigned Index;
  231. };
  232. CodeGenModule &CGM; // Per-module state.
  233. const TargetInfo &Target;
  234. // For EH/SEH outlined funclets, this field points to parent's CGF
  235. CodeGenFunction *ParentCGF = nullptr;
  236. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  237. LoopInfoStack LoopStack;
  238. CGBuilderTy Builder;
  239. // Stores variables for which we can't generate correct lifetime markers
  240. // because of jumps.
  241. VarBypassDetector Bypasses;
  242. /// List of recently emitted OMPCanonicalLoops.
  243. ///
  244. /// Since OMPCanonicalLoops are nested inside other statements (in particular
  245. /// CapturedStmt generated by OMPExecutableDirective and non-perfectly nested
  246. /// loops), we cannot directly call OMPEmitOMPCanonicalLoop and receive its
  247. /// llvm::CanonicalLoopInfo. Instead, we call EmitStmt and any
  248. /// OMPEmitOMPCanonicalLoop called by it will add its CanonicalLoopInfo to
  249. /// this stack when done. Entering a new loop requires clearing this list; it
  250. /// either means we start parsing a new loop nest (in which case the previous
  251. /// loop nest goes out of scope) or a second loop in the same level in which
  252. /// case it would be ambiguous into which of the two (or more) loops the loop
  253. /// nest would extend.
  254. SmallVector<llvm::CanonicalLoopInfo *, 4> OMPLoopNestStack;
  255. /// Number of nested loop to be consumed by the last surrounding
  256. /// loop-associated directive.
  257. int ExpectedOMPLoopDepth = 0;
  258. // CodeGen lambda for loops and support for ordered clause
  259. typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
  260. JumpDest)>
  261. CodeGenLoopTy;
  262. typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
  263. const unsigned, const bool)>
  264. CodeGenOrderedTy;
  265. // Codegen lambda for loop bounds in worksharing loop constructs
  266. typedef llvm::function_ref<std::pair<LValue, LValue>(
  267. CodeGenFunction &, const OMPExecutableDirective &S)>
  268. CodeGenLoopBoundsTy;
  269. // Codegen lambda for loop bounds in dispatch-based loop implementation
  270. typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
  271. CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
  272. Address UB)>
  273. CodeGenDispatchBoundsTy;
  274. /// CGBuilder insert helper. This function is called after an
  275. /// instruction is created using Builder.
  276. void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
  277. llvm::BasicBlock *BB,
  278. llvm::BasicBlock::iterator InsertPt) const;
  279. /// CurFuncDecl - Holds the Decl for the current outermost
  280. /// non-closure context.
  281. const Decl *CurFuncDecl;
  282. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  283. const Decl *CurCodeDecl;
  284. const CGFunctionInfo *CurFnInfo;
  285. QualType FnRetTy;
  286. llvm::Function *CurFn = nullptr;
  287. /// Save Parameter Decl for coroutine.
  288. llvm::SmallVector<const ParmVarDecl *, 4> FnArgs;
  289. // Holds coroutine data if the current function is a coroutine. We use a
  290. // wrapper to manage its lifetime, so that we don't have to define CGCoroData
  291. // in this header.
  292. struct CGCoroInfo {
  293. std::unique_ptr<CGCoroData> Data;
  294. CGCoroInfo();
  295. ~CGCoroInfo();
  296. };
  297. CGCoroInfo CurCoro;
  298. bool isCoroutine() const {
  299. return CurCoro.Data != nullptr;
  300. }
  301. /// CurGD - The GlobalDecl for the current function being compiled.
  302. GlobalDecl CurGD;
  303. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  304. /// cleanups associated with the parameters.
  305. EHScopeStack::stable_iterator PrologueCleanupDepth;
  306. /// ReturnBlock - Unified return block.
  307. JumpDest ReturnBlock;
  308. /// ReturnValue - The temporary alloca to hold the return
  309. /// value. This is invalid iff the function has no return value.
  310. Address ReturnValue = Address::invalid();
  311. /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
  312. /// This is invalid if sret is not in use.
  313. Address ReturnValuePointer = Address::invalid();
  314. /// If a return statement is being visited, this holds the return statment's
  315. /// result expression.
  316. const Expr *RetExpr = nullptr;
  317. /// Return true if a label was seen in the current scope.
  318. bool hasLabelBeenSeenInCurrentScope() const {
  319. if (CurLexicalScope)
  320. return CurLexicalScope->hasLabels();
  321. return !LabelMap.empty();
  322. }
  323. /// AllocaInsertPoint - This is an instruction in the entry block before which
  324. /// we prefer to insert allocas.
  325. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  326. private:
  327. /// PostAllocaInsertPt - This is a place in the prologue where code can be
  328. /// inserted that will be dominated by all the static allocas. This helps
  329. /// achieve two things:
  330. /// 1. Contiguity of all static allocas (within the prologue) is maintained.
  331. /// 2. All other prologue code (which are dominated by static allocas) do
  332. /// appear in the source order immediately after all static allocas.
  333. ///
  334. /// PostAllocaInsertPt will be lazily created when it is *really* required.
  335. llvm::AssertingVH<llvm::Instruction> PostAllocaInsertPt = nullptr;
  336. public:
  337. /// Return PostAllocaInsertPt. If it is not yet created, then insert it
  338. /// immediately after AllocaInsertPt.
  339. llvm::Instruction *getPostAllocaInsertPoint() {
  340. if (!PostAllocaInsertPt) {
  341. assert(AllocaInsertPt &&
  342. "Expected static alloca insertion point at function prologue");
  343. assert(AllocaInsertPt->getParent()->isEntryBlock() &&
  344. "EBB should be entry block of the current code gen function");
  345. PostAllocaInsertPt = AllocaInsertPt->clone();
  346. PostAllocaInsertPt->setName("postallocapt");
  347. PostAllocaInsertPt->insertAfter(AllocaInsertPt);
  348. }
  349. return PostAllocaInsertPt;
  350. }
  351. /// API for captured statement code generation.
  352. class CGCapturedStmtInfo {
  353. public:
  354. explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
  355. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
  356. explicit CGCapturedStmtInfo(const CapturedStmt &S,
  357. CapturedRegionKind K = CR_Default)
  358. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
  359. RecordDecl::field_iterator Field =
  360. S.getCapturedRecordDecl()->field_begin();
  361. for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
  362. E = S.capture_end();
  363. I != E; ++I, ++Field) {
  364. if (I->capturesThis())
  365. CXXThisFieldDecl = *Field;
  366. else if (I->capturesVariable())
  367. CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
  368. else if (I->capturesVariableByCopy())
  369. CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
  370. }
  371. }
  372. virtual ~CGCapturedStmtInfo();
  373. CapturedRegionKind getKind() const { return Kind; }
  374. virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
  375. // Retrieve the value of the context parameter.
  376. virtual llvm::Value *getContextValue() const { return ThisValue; }
  377. /// Lookup the captured field decl for a variable.
  378. virtual const FieldDecl *lookup(const VarDecl *VD) const {
  379. return CaptureFields.lookup(VD->getCanonicalDecl());
  380. }
  381. bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
  382. virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
  383. static bool classof(const CGCapturedStmtInfo *) {
  384. return true;
  385. }
  386. /// Emit the captured statement body.
  387. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
  388. CGF.incrementProfileCounter(S);
  389. CGF.EmitStmt(S);
  390. }
  391. /// Get the name of the capture helper.
  392. virtual StringRef getHelperName() const { return "__captured_stmt"; }
  393. /// Get the CaptureFields
  394. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> getCaptureFields() {
  395. return CaptureFields;
  396. }
  397. private:
  398. /// The kind of captured statement being generated.
  399. CapturedRegionKind Kind;
  400. /// Keep the map between VarDecl and FieldDecl.
  401. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
  402. /// The base address of the captured record, passed in as the first
  403. /// argument of the parallel region function.
  404. llvm::Value *ThisValue;
  405. /// Captured 'this' type.
  406. FieldDecl *CXXThisFieldDecl;
  407. };
  408. CGCapturedStmtInfo *CapturedStmtInfo = nullptr;
  409. /// RAII for correct setting/restoring of CapturedStmtInfo.
  410. class CGCapturedStmtRAII {
  411. private:
  412. CodeGenFunction &CGF;
  413. CGCapturedStmtInfo *PrevCapturedStmtInfo;
  414. public:
  415. CGCapturedStmtRAII(CodeGenFunction &CGF,
  416. CGCapturedStmtInfo *NewCapturedStmtInfo)
  417. : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
  418. CGF.CapturedStmtInfo = NewCapturedStmtInfo;
  419. }
  420. ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
  421. };
  422. /// An abstract representation of regular/ObjC call/message targets.
  423. class AbstractCallee {
  424. /// The function declaration of the callee.
  425. const Decl *CalleeDecl;
  426. public:
  427. AbstractCallee() : CalleeDecl(nullptr) {}
  428. AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
  429. AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
  430. bool hasFunctionDecl() const {
  431. return isa_and_nonnull<FunctionDecl>(CalleeDecl);
  432. }
  433. const Decl *getDecl() const { return CalleeDecl; }
  434. unsigned getNumParams() const {
  435. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
  436. return FD->getNumParams();
  437. return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
  438. }
  439. const ParmVarDecl *getParamDecl(unsigned I) const {
  440. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
  441. return FD->getParamDecl(I);
  442. return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
  443. }
  444. };
  445. /// Sanitizers enabled for this function.
  446. SanitizerSet SanOpts;
  447. /// True if CodeGen currently emits code implementing sanitizer checks.
  448. bool IsSanitizerScope = false;
  449. /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
  450. class SanitizerScope {
  451. CodeGenFunction *CGF;
  452. public:
  453. SanitizerScope(CodeGenFunction *CGF);
  454. ~SanitizerScope();
  455. };
  456. /// In C++, whether we are code generating a thunk. This controls whether we
  457. /// should emit cleanups.
  458. bool CurFuncIsThunk = false;
  459. /// In ARC, whether we should autorelease the return value.
  460. bool AutoreleaseResult = false;
  461. /// Whether we processed a Microsoft-style asm block during CodeGen. These can
  462. /// potentially set the return value.
  463. bool SawAsmBlock = false;
  464. const NamedDecl *CurSEHParent = nullptr;
  465. /// True if the current function is an outlined SEH helper. This can be a
  466. /// finally block or filter expression.
  467. bool IsOutlinedSEHHelper = false;
  468. /// True if CodeGen currently emits code inside presereved access index
  469. /// region.
  470. bool IsInPreservedAIRegion = false;
  471. /// True if the current statement has nomerge attribute.
  472. bool InNoMergeAttributedStmt = false;
  473. // The CallExpr within the current statement that the musttail attribute
  474. // applies to. nullptr if there is no 'musttail' on the current statement.
  475. const CallExpr *MustTailCall = nullptr;
  476. /// Returns true if a function must make progress, which means the
  477. /// mustprogress attribute can be added.
  478. bool checkIfFunctionMustProgress() {
  479. if (CGM.getCodeGenOpts().getFiniteLoops() ==
  480. CodeGenOptions::FiniteLoopsKind::Never)
  481. return false;
  482. // C++11 and later guarantees that a thread eventually will do one of the
  483. // following (6.9.2.3.1 in C++11):
  484. // - terminate,
  485. // - make a call to a library I/O function,
  486. // - perform an access through a volatile glvalue, or
  487. // - perform a synchronization operation or an atomic operation.
  488. //
  489. // Hence each function is 'mustprogress' in C++11 or later.
  490. return getLangOpts().CPlusPlus11;
  491. }
  492. /// Returns true if a loop must make progress, which means the mustprogress
  493. /// attribute can be added. \p HasConstantCond indicates whether the branch
  494. /// condition is a known constant.
  495. bool checkIfLoopMustProgress(bool HasConstantCond) {
  496. if (CGM.getCodeGenOpts().getFiniteLoops() ==
  497. CodeGenOptions::FiniteLoopsKind::Always)
  498. return true;
  499. if (CGM.getCodeGenOpts().getFiniteLoops() ==
  500. CodeGenOptions::FiniteLoopsKind::Never)
  501. return false;
  502. // If the containing function must make progress, loops also must make
  503. // progress (as in C++11 and later).
  504. if (checkIfFunctionMustProgress())
  505. return true;
  506. // Now apply rules for plain C (see 6.8.5.6 in C11).
  507. // Loops with constant conditions do not have to make progress in any C
  508. // version.
  509. if (HasConstantCond)
  510. return false;
  511. // Loops with non-constant conditions must make progress in C11 and later.
  512. return getLangOpts().C11;
  513. }
  514. const CodeGen::CGBlockInfo *BlockInfo = nullptr;
  515. llvm::Value *BlockPointer = nullptr;
  516. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  517. FieldDecl *LambdaThisCaptureField = nullptr;
  518. /// A mapping from NRVO variables to the flags used to indicate
  519. /// when the NRVO has been applied to this variable.
  520. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  521. EHScopeStack EHStack;
  522. llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
  523. llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
  524. llvm::Instruction *CurrentFuncletPad = nullptr;
  525. class CallLifetimeEnd final : public EHScopeStack::Cleanup {
  526. bool isRedundantBeforeReturn() override { return true; }
  527. llvm::Value *Addr;
  528. llvm::Value *Size;
  529. public:
  530. CallLifetimeEnd(Address addr, llvm::Value *size)
  531. : Addr(addr.getPointer()), Size(size) {}
  532. void Emit(CodeGenFunction &CGF, Flags flags) override {
  533. CGF.EmitLifetimeEnd(Size, Addr);
  534. }
  535. };
  536. /// Header for data within LifetimeExtendedCleanupStack.
  537. struct LifetimeExtendedCleanupHeader {
  538. /// The size of the following cleanup object.
  539. unsigned Size;
  540. /// The kind of cleanup to push: a value from the CleanupKind enumeration.
  541. unsigned Kind : 31;
  542. /// Whether this is a conditional cleanup.
  543. unsigned IsConditional : 1;
  544. size_t getSize() const { return Size; }
  545. CleanupKind getKind() const { return (CleanupKind)Kind; }
  546. bool isConditional() const { return IsConditional; }
  547. };
  548. /// i32s containing the indexes of the cleanup destinations.
  549. Address NormalCleanupDest = Address::invalid();
  550. unsigned NextCleanupDestIndex = 1;
  551. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  552. llvm::BasicBlock *EHResumeBlock = nullptr;
  553. /// The exception slot. All landing pads write the current exception pointer
  554. /// into this alloca.
  555. llvm::Value *ExceptionSlot = nullptr;
  556. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  557. /// write the current selector value into this alloca.
  558. llvm::AllocaInst *EHSelectorSlot = nullptr;
  559. /// A stack of exception code slots. Entering an __except block pushes a slot
  560. /// on the stack and leaving pops one. The __exception_code() intrinsic loads
  561. /// a value from the top of the stack.
  562. SmallVector<Address, 1> SEHCodeSlotStack;
  563. /// Value returned by __exception_info intrinsic.
  564. llvm::Value *SEHInfo = nullptr;
  565. /// Emits a landing pad for the current EH stack.
  566. llvm::BasicBlock *EmitLandingPad();
  567. llvm::BasicBlock *getInvokeDestImpl();
  568. /// Parent loop-based directive for scan directive.
  569. const OMPExecutableDirective *OMPParentLoopDirectiveForScan = nullptr;
  570. llvm::BasicBlock *OMPBeforeScanBlock = nullptr;
  571. llvm::BasicBlock *OMPAfterScanBlock = nullptr;
  572. llvm::BasicBlock *OMPScanExitBlock = nullptr;
  573. llvm::BasicBlock *OMPScanDispatch = nullptr;
  574. bool OMPFirstScanLoop = false;
  575. /// Manages parent directive for scan directives.
  576. class ParentLoopDirectiveForScanRegion {
  577. CodeGenFunction &CGF;
  578. const OMPExecutableDirective *ParentLoopDirectiveForScan;
  579. public:
  580. ParentLoopDirectiveForScanRegion(
  581. CodeGenFunction &CGF,
  582. const OMPExecutableDirective &ParentLoopDirectiveForScan)
  583. : CGF(CGF),
  584. ParentLoopDirectiveForScan(CGF.OMPParentLoopDirectiveForScan) {
  585. CGF.OMPParentLoopDirectiveForScan = &ParentLoopDirectiveForScan;
  586. }
  587. ~ParentLoopDirectiveForScanRegion() {
  588. CGF.OMPParentLoopDirectiveForScan = ParentLoopDirectiveForScan;
  589. }
  590. };
  591. template <class T>
  592. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  593. return DominatingValue<T>::save(*this, value);
  594. }
  595. class CGFPOptionsRAII {
  596. public:
  597. CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures);
  598. CGFPOptionsRAII(CodeGenFunction &CGF, const Expr *E);
  599. ~CGFPOptionsRAII();
  600. private:
  601. void ConstructorHelper(FPOptions FPFeatures);
  602. CodeGenFunction &CGF;
  603. FPOptions OldFPFeatures;
  604. llvm::fp::ExceptionBehavior OldExcept;
  605. llvm::RoundingMode OldRounding;
  606. Optional<CGBuilderTy::FastMathFlagGuard> FMFGuard;
  607. };
  608. FPOptions CurFPFeatures;
  609. public:
  610. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  611. /// rethrows.
  612. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  613. /// A class controlling the emission of a finally block.
  614. class FinallyInfo {
  615. /// Where the catchall's edge through the cleanup should go.
  616. JumpDest RethrowDest;
  617. /// A function to call to enter the catch.
  618. llvm::FunctionCallee BeginCatchFn;
  619. /// An i1 variable indicating whether or not the @finally is
  620. /// running for an exception.
  621. llvm::AllocaInst *ForEHVar;
  622. /// An i8* variable into which the exception pointer to rethrow
  623. /// has been saved.
  624. llvm::AllocaInst *SavedExnVar;
  625. public:
  626. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  627. llvm::FunctionCallee beginCatchFn,
  628. llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn);
  629. void exit(CodeGenFunction &CGF);
  630. };
  631. /// Returns true inside SEH __try blocks.
  632. bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
  633. /// Returns true while emitting a cleanuppad.
  634. bool isCleanupPadScope() const {
  635. return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
  636. }
  637. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  638. /// current full-expression. Safe against the possibility that
  639. /// we're currently inside a conditionally-evaluated expression.
  640. template <class T, class... As>
  641. void pushFullExprCleanup(CleanupKind kind, As... A) {
  642. // If we're not in a conditional branch, or if none of the
  643. // arguments requires saving, then use the unconditional cleanup.
  644. if (!isInConditionalBranch())
  645. return EHStack.pushCleanup<T>(kind, A...);
  646. // Stash values in a tuple so we can guarantee the order of saves.
  647. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  648. SavedTuple Saved{saveValueInCond(A)...};
  649. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  650. EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
  651. initFullExprCleanup();
  652. }
  653. /// Queue a cleanup to be pushed after finishing the current full-expression,
  654. /// potentially with an active flag.
  655. template <class T, class... As>
  656. void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
  657. if (!isInConditionalBranch())
  658. return pushCleanupAfterFullExprWithActiveFlag<T>(Kind, Address::invalid(),
  659. A...);
  660. Address ActiveFlag = createCleanupActiveFlag();
  661. assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
  662. "cleanup active flag should never need saving");
  663. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  664. SavedTuple Saved{saveValueInCond(A)...};
  665. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  666. pushCleanupAfterFullExprWithActiveFlag<CleanupType>(Kind, ActiveFlag, Saved);
  667. }
  668. template <class T, class... As>
  669. void pushCleanupAfterFullExprWithActiveFlag(CleanupKind Kind,
  670. Address ActiveFlag, As... A) {
  671. LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
  672. ActiveFlag.isValid()};
  673. size_t OldSize = LifetimeExtendedCleanupStack.size();
  674. LifetimeExtendedCleanupStack.resize(
  675. LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
  676. (Header.IsConditional ? sizeof(ActiveFlag) : 0));
  677. static_assert(sizeof(Header) % alignof(T) == 0,
  678. "Cleanup will be allocated on misaligned address");
  679. char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
  680. new (Buffer) LifetimeExtendedCleanupHeader(Header);
  681. new (Buffer + sizeof(Header)) T(A...);
  682. if (Header.IsConditional)
  683. new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
  684. }
  685. /// Set up the last cleanup that was pushed as a conditional
  686. /// full-expression cleanup.
  687. void initFullExprCleanup() {
  688. initFullExprCleanupWithFlag(createCleanupActiveFlag());
  689. }
  690. void initFullExprCleanupWithFlag(Address ActiveFlag);
  691. Address createCleanupActiveFlag();
  692. /// PushDestructorCleanup - Push a cleanup to call the
  693. /// complete-object destructor of an object of the given type at the
  694. /// given address. Does nothing if T is not a C++ class type with a
  695. /// non-trivial destructor.
  696. void PushDestructorCleanup(QualType T, Address Addr);
  697. /// PushDestructorCleanup - Push a cleanup to call the
  698. /// complete-object variant of the given destructor on the object at
  699. /// the given address.
  700. void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T,
  701. Address Addr);
  702. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  703. /// process all branch fixups.
  704. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  705. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  706. /// The block cannot be reactivated. Pops it if it's the top of the
  707. /// stack.
  708. ///
  709. /// \param DominatingIP - An instruction which is known to
  710. /// dominate the current IP (if set) and which lies along
  711. /// all paths of execution between the current IP and the
  712. /// the point at which the cleanup comes into scope.
  713. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  714. llvm::Instruction *DominatingIP);
  715. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  716. /// Cannot be used to resurrect a deactivated cleanup.
  717. ///
  718. /// \param DominatingIP - An instruction which is known to
  719. /// dominate the current IP (if set) and which lies along
  720. /// all paths of execution between the current IP and the
  721. /// the point at which the cleanup comes into scope.
  722. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  723. llvm::Instruction *DominatingIP);
  724. /// Enters a new scope for capturing cleanups, all of which
  725. /// will be executed once the scope is exited.
  726. class RunCleanupsScope {
  727. EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
  728. size_t LifetimeExtendedCleanupStackSize;
  729. bool OldDidCallStackSave;
  730. protected:
  731. bool PerformCleanup;
  732. private:
  733. RunCleanupsScope(const RunCleanupsScope &) = delete;
  734. void operator=(const RunCleanupsScope &) = delete;
  735. protected:
  736. CodeGenFunction& CGF;
  737. public:
  738. /// Enter a new cleanup scope.
  739. explicit RunCleanupsScope(CodeGenFunction &CGF)
  740. : PerformCleanup(true), CGF(CGF)
  741. {
  742. CleanupStackDepth = CGF.EHStack.stable_begin();
  743. LifetimeExtendedCleanupStackSize =
  744. CGF.LifetimeExtendedCleanupStack.size();
  745. OldDidCallStackSave = CGF.DidCallStackSave;
  746. CGF.DidCallStackSave = false;
  747. OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
  748. CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
  749. }
  750. /// Exit this cleanup scope, emitting any accumulated cleanups.
  751. ~RunCleanupsScope() {
  752. if (PerformCleanup)
  753. ForceCleanup();
  754. }
  755. /// Determine whether this scope requires any cleanups.
  756. bool requiresCleanups() const {
  757. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  758. }
  759. /// Force the emission of cleanups now, instead of waiting
  760. /// until this object is destroyed.
  761. /// \param ValuesToReload - A list of values that need to be available at
  762. /// the insertion point after cleanup emission. If cleanup emission created
  763. /// a shared cleanup block, these value pointers will be rewritten.
  764. /// Otherwise, they not will be modified.
  765. void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
  766. assert(PerformCleanup && "Already forced cleanup");
  767. CGF.DidCallStackSave = OldDidCallStackSave;
  768. CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
  769. ValuesToReload);
  770. PerformCleanup = false;
  771. CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
  772. }
  773. };
  774. // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
  775. EHScopeStack::stable_iterator CurrentCleanupScopeDepth =
  776. EHScopeStack::stable_end();
  777. class LexicalScope : public RunCleanupsScope {
  778. SourceRange Range;
  779. SmallVector<const LabelDecl*, 4> Labels;
  780. LexicalScope *ParentScope;
  781. LexicalScope(const LexicalScope &) = delete;
  782. void operator=(const LexicalScope &) = delete;
  783. public:
  784. /// Enter a new cleanup scope.
  785. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  786. : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
  787. CGF.CurLexicalScope = this;
  788. if (CGDebugInfo *DI = CGF.getDebugInfo())
  789. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  790. }
  791. void addLabel(const LabelDecl *label) {
  792. assert(PerformCleanup && "adding label to dead scope?");
  793. Labels.push_back(label);
  794. }
  795. /// Exit this cleanup scope, emitting any accumulated
  796. /// cleanups.
  797. ~LexicalScope() {
  798. if (CGDebugInfo *DI = CGF.getDebugInfo())
  799. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  800. // If we should perform a cleanup, force them now. Note that
  801. // this ends the cleanup scope before rescoping any labels.
  802. if (PerformCleanup) {
  803. ApplyDebugLocation DL(CGF, Range.getEnd());
  804. ForceCleanup();
  805. }
  806. }
  807. /// Force the emission of cleanups now, instead of waiting
  808. /// until this object is destroyed.
  809. void ForceCleanup() {
  810. CGF.CurLexicalScope = ParentScope;
  811. RunCleanupsScope::ForceCleanup();
  812. if (!Labels.empty())
  813. rescopeLabels();
  814. }
  815. bool hasLabels() const {
  816. return !Labels.empty();
  817. }
  818. void rescopeLabels();
  819. };
  820. typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
  821. /// The class used to assign some variables some temporarily addresses.
  822. class OMPMapVars {
  823. DeclMapTy SavedLocals;
  824. DeclMapTy SavedTempAddresses;
  825. OMPMapVars(const OMPMapVars &) = delete;
  826. void operator=(const OMPMapVars &) = delete;
  827. public:
  828. explicit OMPMapVars() = default;
  829. ~OMPMapVars() {
  830. assert(SavedLocals.empty() && "Did not restored original addresses.");
  831. };
  832. /// Sets the address of the variable \p LocalVD to be \p TempAddr in
  833. /// function \p CGF.
  834. /// \return true if at least one variable was set already, false otherwise.
  835. bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
  836. Address TempAddr) {
  837. LocalVD = LocalVD->getCanonicalDecl();
  838. // Only save it once.
  839. if (SavedLocals.count(LocalVD)) return false;
  840. // Copy the existing local entry to SavedLocals.
  841. auto it = CGF.LocalDeclMap.find(LocalVD);
  842. if (it != CGF.LocalDeclMap.end())
  843. SavedLocals.try_emplace(LocalVD, it->second);
  844. else
  845. SavedLocals.try_emplace(LocalVD, Address::invalid());
  846. // Generate the private entry.
  847. QualType VarTy = LocalVD->getType();
  848. if (VarTy->isReferenceType()) {
  849. Address Temp = CGF.CreateMemTemp(VarTy);
  850. CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
  851. TempAddr = Temp;
  852. }
  853. SavedTempAddresses.try_emplace(LocalVD, TempAddr);
  854. return true;
  855. }
  856. /// Applies new addresses to the list of the variables.
  857. /// \return true if at least one variable is using new address, false
  858. /// otherwise.
  859. bool apply(CodeGenFunction &CGF) {
  860. copyInto(SavedTempAddresses, CGF.LocalDeclMap);
  861. SavedTempAddresses.clear();
  862. return !SavedLocals.empty();
  863. }
  864. /// Restores original addresses of the variables.
  865. void restore(CodeGenFunction &CGF) {
  866. if (!SavedLocals.empty()) {
  867. copyInto(SavedLocals, CGF.LocalDeclMap);
  868. SavedLocals.clear();
  869. }
  870. }
  871. private:
  872. /// Copy all the entries in the source map over the corresponding
  873. /// entries in the destination, which must exist.
  874. static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
  875. for (auto &Pair : Src) {
  876. if (!Pair.second.isValid()) {
  877. Dest.erase(Pair.first);
  878. continue;
  879. }
  880. auto I = Dest.find(Pair.first);
  881. if (I != Dest.end())
  882. I->second = Pair.second;
  883. else
  884. Dest.insert(Pair);
  885. }
  886. }
  887. };
  888. /// The scope used to remap some variables as private in the OpenMP loop body
  889. /// (or other captured region emitted without outlining), and to restore old
  890. /// vars back on exit.
  891. class OMPPrivateScope : public RunCleanupsScope {
  892. OMPMapVars MappedVars;
  893. OMPPrivateScope(const OMPPrivateScope &) = delete;
  894. void operator=(const OMPPrivateScope &) = delete;
  895. public:
  896. /// Enter a new OpenMP private scope.
  897. explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  898. /// Registers \p LocalVD variable as a private and apply \p PrivateGen
  899. /// function for it to generate corresponding private variable. \p
  900. /// PrivateGen returns an address of the generated private variable.
  901. /// \return true if the variable is registered as private, false if it has
  902. /// been privatized already.
  903. bool addPrivate(const VarDecl *LocalVD,
  904. const llvm::function_ref<Address()> PrivateGen) {
  905. assert(PerformCleanup && "adding private to dead scope");
  906. return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen());
  907. }
  908. /// Privatizes local variables previously registered as private.
  909. /// Registration is separate from the actual privatization to allow
  910. /// initializers use values of the original variables, not the private one.
  911. /// This is important, for example, if the private variable is a class
  912. /// variable initialized by a constructor that references other private
  913. /// variables. But at initialization original variables must be used, not
  914. /// private copies.
  915. /// \return true if at least one variable was privatized, false otherwise.
  916. bool Privatize() { return MappedVars.apply(CGF); }
  917. void ForceCleanup() {
  918. RunCleanupsScope::ForceCleanup();
  919. MappedVars.restore(CGF);
  920. }
  921. /// Exit scope - all the mapped variables are restored.
  922. ~OMPPrivateScope() {
  923. if (PerformCleanup)
  924. ForceCleanup();
  925. }
  926. /// Checks if the global variable is captured in current function.
  927. bool isGlobalVarCaptured(const VarDecl *VD) const {
  928. VD = VD->getCanonicalDecl();
  929. return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
  930. }
  931. };
  932. /// Save/restore original map of previously emitted local vars in case when we
  933. /// need to duplicate emission of the same code several times in the same
  934. /// function for OpenMP code.
  935. class OMPLocalDeclMapRAII {
  936. CodeGenFunction &CGF;
  937. DeclMapTy SavedMap;
  938. public:
  939. OMPLocalDeclMapRAII(CodeGenFunction &CGF)
  940. : CGF(CGF), SavedMap(CGF.LocalDeclMap) {}
  941. ~OMPLocalDeclMapRAII() { SavedMap.swap(CGF.LocalDeclMap); }
  942. };
  943. /// Takes the old cleanup stack size and emits the cleanup blocks
  944. /// that have been added.
  945. void
  946. PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  947. std::initializer_list<llvm::Value **> ValuesToReload = {});
  948. /// Takes the old cleanup stack size and emits the cleanup blocks
  949. /// that have been added, then adds all lifetime-extended cleanups from
  950. /// the given position to the stack.
  951. void
  952. PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  953. size_t OldLifetimeExtendedStackSize,
  954. std::initializer_list<llvm::Value **> ValuesToReload = {});
  955. void ResolveBranchFixups(llvm::BasicBlock *Target);
  956. /// The given basic block lies in the current EH scope, but may be a
  957. /// target of a potentially scope-crossing jump; get a stable handle
  958. /// to which we can perform this jump later.
  959. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  960. return JumpDest(Target,
  961. EHStack.getInnermostNormalCleanup(),
  962. NextCleanupDestIndex++);
  963. }
  964. /// The given basic block lies in the current EH scope, but may be a
  965. /// target of a potentially scope-crossing jump; get a stable handle
  966. /// to which we can perform this jump later.
  967. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  968. return getJumpDestInCurrentScope(createBasicBlock(Name));
  969. }
  970. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  971. /// block through the normal cleanup handling code (if any) and then
  972. /// on to \arg Dest.
  973. void EmitBranchThroughCleanup(JumpDest Dest);
  974. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  975. /// specified destination obviously has no cleanups to run. 'false' is always
  976. /// a conservatively correct answer for this method.
  977. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  978. /// popCatchScope - Pops the catch scope at the top of the EHScope
  979. /// stack, emitting any required code (other than the catch handlers
  980. /// themselves).
  981. void popCatchScope();
  982. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  983. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  984. llvm::BasicBlock *
  985. getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope);
  986. /// An object to manage conditionally-evaluated expressions.
  987. class ConditionalEvaluation {
  988. llvm::BasicBlock *StartBB;
  989. public:
  990. ConditionalEvaluation(CodeGenFunction &CGF)
  991. : StartBB(CGF.Builder.GetInsertBlock()) {}
  992. void begin(CodeGenFunction &CGF) {
  993. assert(CGF.OutermostConditional != this);
  994. if (!CGF.OutermostConditional)
  995. CGF.OutermostConditional = this;
  996. }
  997. void end(CodeGenFunction &CGF) {
  998. assert(CGF.OutermostConditional != nullptr);
  999. if (CGF.OutermostConditional == this)
  1000. CGF.OutermostConditional = nullptr;
  1001. }
  1002. /// Returns a block which will be executed prior to each
  1003. /// evaluation of the conditional code.
  1004. llvm::BasicBlock *getStartingBlock() const {
  1005. return StartBB;
  1006. }
  1007. };
  1008. /// isInConditionalBranch - Return true if we're currently emitting
  1009. /// one branch or the other of a conditional expression.
  1010. bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
  1011. void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
  1012. assert(isInConditionalBranch());
  1013. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  1014. auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
  1015. store->setAlignment(addr.getAlignment().getAsAlign());
  1016. }
  1017. /// An RAII object to record that we're evaluating a statement
  1018. /// expression.
  1019. class StmtExprEvaluation {
  1020. CodeGenFunction &CGF;
  1021. /// We have to save the outermost conditional: cleanups in a
  1022. /// statement expression aren't conditional just because the
  1023. /// StmtExpr is.
  1024. ConditionalEvaluation *SavedOutermostConditional;
  1025. public:
  1026. StmtExprEvaluation(CodeGenFunction &CGF)
  1027. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  1028. CGF.OutermostConditional = nullptr;
  1029. }
  1030. ~StmtExprEvaluation() {
  1031. CGF.OutermostConditional = SavedOutermostConditional;
  1032. CGF.EnsureInsertPoint();
  1033. }
  1034. };
  1035. /// An object which temporarily prevents a value from being
  1036. /// destroyed by aggressive peephole optimizations that assume that
  1037. /// all uses of a value have been realized in the IR.
  1038. class PeepholeProtection {
  1039. llvm::Instruction *Inst;
  1040. friend class CodeGenFunction;
  1041. public:
  1042. PeepholeProtection() : Inst(nullptr) {}
  1043. };
  1044. /// A non-RAII class containing all the information about a bound
  1045. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  1046. /// this which makes individual mappings very simple; using this
  1047. /// class directly is useful when you have a variable number of
  1048. /// opaque values or don't want the RAII functionality for some
  1049. /// reason.
  1050. class OpaqueValueMappingData {
  1051. const OpaqueValueExpr *OpaqueValue;
  1052. bool BoundLValue;
  1053. CodeGenFunction::PeepholeProtection Protection;
  1054. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  1055. bool boundLValue)
  1056. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  1057. public:
  1058. OpaqueValueMappingData() : OpaqueValue(nullptr) {}
  1059. static bool shouldBindAsLValue(const Expr *expr) {
  1060. // gl-values should be bound as l-values for obvious reasons.
  1061. // Records should be bound as l-values because IR generation
  1062. // always keeps them in memory. Expressions of function type
  1063. // act exactly like l-values but are formally required to be
  1064. // r-values in C.
  1065. return expr->isGLValue() ||
  1066. expr->getType()->isFunctionType() ||
  1067. hasAggregateEvaluationKind(expr->getType());
  1068. }
  1069. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  1070. const OpaqueValueExpr *ov,
  1071. const Expr *e) {
  1072. if (shouldBindAsLValue(ov))
  1073. return bind(CGF, ov, CGF.EmitLValue(e));
  1074. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  1075. }
  1076. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  1077. const OpaqueValueExpr *ov,
  1078. const LValue &lv) {
  1079. assert(shouldBindAsLValue(ov));
  1080. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  1081. return OpaqueValueMappingData(ov, true);
  1082. }
  1083. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  1084. const OpaqueValueExpr *ov,
  1085. const RValue &rv) {
  1086. assert(!shouldBindAsLValue(ov));
  1087. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  1088. OpaqueValueMappingData data(ov, false);
  1089. // Work around an extremely aggressive peephole optimization in
  1090. // EmitScalarConversion which assumes that all other uses of a
  1091. // value are extant.
  1092. data.Protection = CGF.protectFromPeepholes(rv);
  1093. return data;
  1094. }
  1095. bool isValid() const { return OpaqueValue != nullptr; }
  1096. void clear() { OpaqueValue = nullptr; }
  1097. void unbind(CodeGenFunction &CGF) {
  1098. assert(OpaqueValue && "no data to unbind!");
  1099. if (BoundLValue) {
  1100. CGF.OpaqueLValues.erase(OpaqueValue);
  1101. } else {
  1102. CGF.OpaqueRValues.erase(OpaqueValue);
  1103. CGF.unprotectFromPeepholes(Protection);
  1104. }
  1105. }
  1106. };
  1107. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  1108. class OpaqueValueMapping {
  1109. CodeGenFunction &CGF;
  1110. OpaqueValueMappingData Data;
  1111. public:
  1112. static bool shouldBindAsLValue(const Expr *expr) {
  1113. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  1114. }
  1115. /// Build the opaque value mapping for the given conditional
  1116. /// operator if it's the GNU ?: extension. This is a common
  1117. /// enough pattern that the convenience operator is really
  1118. /// helpful.
  1119. ///
  1120. OpaqueValueMapping(CodeGenFunction &CGF,
  1121. const AbstractConditionalOperator *op) : CGF(CGF) {
  1122. if (isa<ConditionalOperator>(op))
  1123. // Leave Data empty.
  1124. return;
  1125. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  1126. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  1127. e->getCommon());
  1128. }
  1129. /// Build the opaque value mapping for an OpaqueValueExpr whose source
  1130. /// expression is set to the expression the OVE represents.
  1131. OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
  1132. : CGF(CGF) {
  1133. if (OV) {
  1134. assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
  1135. "for OVE with no source expression");
  1136. Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
  1137. }
  1138. }
  1139. OpaqueValueMapping(CodeGenFunction &CGF,
  1140. const OpaqueValueExpr *opaqueValue,
  1141. LValue lvalue)
  1142. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  1143. }
  1144. OpaqueValueMapping(CodeGenFunction &CGF,
  1145. const OpaqueValueExpr *opaqueValue,
  1146. RValue rvalue)
  1147. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  1148. }
  1149. void pop() {
  1150. Data.unbind(CGF);
  1151. Data.clear();
  1152. }
  1153. ~OpaqueValueMapping() {
  1154. if (Data.isValid()) Data.unbind(CGF);
  1155. }
  1156. };
  1157. private:
  1158. CGDebugInfo *DebugInfo;
  1159. /// Used to create unique names for artificial VLA size debug info variables.
  1160. unsigned VLAExprCounter = 0;
  1161. bool DisableDebugInfo = false;
  1162. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  1163. /// calling llvm.stacksave for multiple VLAs in the same scope.
  1164. bool DidCallStackSave = false;
  1165. /// IndirectBranch - The first time an indirect goto is seen we create a block
  1166. /// with an indirect branch. Every time we see the address of a label taken,
  1167. /// we add the label to the indirect goto. Every subsequent indirect goto is
  1168. /// codegen'd as a jump to the IndirectBranch's basic block.
  1169. llvm::IndirectBrInst *IndirectBranch = nullptr;
  1170. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  1171. /// decls.
  1172. DeclMapTy LocalDeclMap;
  1173. // Keep track of the cleanups for callee-destructed parameters pushed to the
  1174. // cleanup stack so that they can be deactivated later.
  1175. llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
  1176. CalleeDestructedParamCleanups;
  1177. /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
  1178. /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
  1179. /// parameter.
  1180. llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
  1181. SizeArguments;
  1182. /// Track escaped local variables with auto storage. Used during SEH
  1183. /// outlining to produce a call to llvm.localescape.
  1184. llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
  1185. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  1186. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  1187. // BreakContinueStack - This keeps track of where break and continue
  1188. // statements should jump to.
  1189. struct BreakContinue {
  1190. BreakContinue(JumpDest Break, JumpDest Continue)
  1191. : BreakBlock(Break), ContinueBlock(Continue) {}
  1192. JumpDest BreakBlock;
  1193. JumpDest ContinueBlock;
  1194. };
  1195. SmallVector<BreakContinue, 8> BreakContinueStack;
  1196. /// Handles cancellation exit points in OpenMP-related constructs.
  1197. class OpenMPCancelExitStack {
  1198. /// Tracks cancellation exit point and join point for cancel-related exit
  1199. /// and normal exit.
  1200. struct CancelExit {
  1201. CancelExit() = default;
  1202. CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
  1203. JumpDest ContBlock)
  1204. : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
  1205. OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown;
  1206. /// true if the exit block has been emitted already by the special
  1207. /// emitExit() call, false if the default codegen is used.
  1208. bool HasBeenEmitted = false;
  1209. JumpDest ExitBlock;
  1210. JumpDest ContBlock;
  1211. };
  1212. SmallVector<CancelExit, 8> Stack;
  1213. public:
  1214. OpenMPCancelExitStack() : Stack(1) {}
  1215. ~OpenMPCancelExitStack() = default;
  1216. /// Fetches the exit block for the current OpenMP construct.
  1217. JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
  1218. /// Emits exit block with special codegen procedure specific for the related
  1219. /// OpenMP construct + emits code for normal construct cleanup.
  1220. void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
  1221. const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
  1222. if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
  1223. assert(CGF.getOMPCancelDestination(Kind).isValid());
  1224. assert(CGF.HaveInsertPoint());
  1225. assert(!Stack.back().HasBeenEmitted);
  1226. auto IP = CGF.Builder.saveAndClearIP();
  1227. CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
  1228. CodeGen(CGF);
  1229. CGF.EmitBranch(Stack.back().ContBlock.getBlock());
  1230. CGF.Builder.restoreIP(IP);
  1231. Stack.back().HasBeenEmitted = true;
  1232. }
  1233. CodeGen(CGF);
  1234. }
  1235. /// Enter the cancel supporting \a Kind construct.
  1236. /// \param Kind OpenMP directive that supports cancel constructs.
  1237. /// \param HasCancel true, if the construct has inner cancel directive,
  1238. /// false otherwise.
  1239. void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
  1240. Stack.push_back({Kind,
  1241. HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
  1242. : JumpDest(),
  1243. HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
  1244. : JumpDest()});
  1245. }
  1246. /// Emits default exit point for the cancel construct (if the special one
  1247. /// has not be used) + join point for cancel/normal exits.
  1248. void exit(CodeGenFunction &CGF) {
  1249. if (getExitBlock().isValid()) {
  1250. assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
  1251. bool HaveIP = CGF.HaveInsertPoint();
  1252. if (!Stack.back().HasBeenEmitted) {
  1253. if (HaveIP)
  1254. CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
  1255. CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
  1256. CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
  1257. }
  1258. CGF.EmitBlock(Stack.back().ContBlock.getBlock());
  1259. if (!HaveIP) {
  1260. CGF.Builder.CreateUnreachable();
  1261. CGF.Builder.ClearInsertionPoint();
  1262. }
  1263. }
  1264. Stack.pop_back();
  1265. }
  1266. };
  1267. OpenMPCancelExitStack OMPCancelStack;
  1268. /// Lower the Likelihood knowledge about the \p Cond via llvm.expect intrin.
  1269. llvm::Value *emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
  1270. Stmt::Likelihood LH);
  1271. CodeGenPGO PGO;
  1272. /// Calculate branch weights appropriate for PGO data
  1273. llvm::MDNode *createProfileWeights(uint64_t TrueCount,
  1274. uint64_t FalseCount) const;
  1275. llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights) const;
  1276. llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
  1277. uint64_t LoopCount) const;
  1278. public:
  1279. /// Increment the profiler's counter for the given statement by \p StepV.
  1280. /// If \p StepV is null, the default increment is 1.
  1281. void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
  1282. if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
  1283. !CurFn->hasFnAttribute(llvm::Attribute::NoProfile))
  1284. PGO.emitCounterIncrement(Builder, S, StepV);
  1285. PGO.setCurrentStmt(S);
  1286. }
  1287. /// Get the profiler's count for the given statement.
  1288. uint64_t getProfileCount(const Stmt *S) {
  1289. Optional<uint64_t> Count = PGO.getStmtCount(S);
  1290. if (!Count.hasValue())
  1291. return 0;
  1292. return *Count;
  1293. }
  1294. /// Set the profiler's current count.
  1295. void setCurrentProfileCount(uint64_t Count) {
  1296. PGO.setCurrentRegionCount(Count);
  1297. }
  1298. /// Get the profiler's current count. This is generally the count for the most
  1299. /// recently incremented counter.
  1300. uint64_t getCurrentProfileCount() {
  1301. return PGO.getCurrentRegionCount();
  1302. }
  1303. private:
  1304. /// SwitchInsn - This is nearest current switch instruction. It is null if
  1305. /// current context is not in a switch.
  1306. llvm::SwitchInst *SwitchInsn = nullptr;
  1307. /// The branch weights of SwitchInsn when doing instrumentation based PGO.
  1308. SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
  1309. /// The likelihood attributes of the SwitchCase.
  1310. SmallVector<Stmt::Likelihood, 16> *SwitchLikelihood = nullptr;
  1311. /// CaseRangeBlock - This block holds if condition check for last case
  1312. /// statement range in current switch instruction.
  1313. llvm::BasicBlock *CaseRangeBlock = nullptr;
  1314. /// OpaqueLValues - Keeps track of the current set of opaque value
  1315. /// expressions.
  1316. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  1317. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  1318. // VLASizeMap - This keeps track of the associated size for each VLA type.
  1319. // We track this by the size expression rather than the type itself because
  1320. // in certain situations, like a const qualifier applied to an VLA typedef,
  1321. // multiple VLA types can share the same size expression.
  1322. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  1323. // enter/leave scopes.
  1324. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  1325. /// A block containing a single 'unreachable' instruction. Created
  1326. /// lazily by getUnreachableBlock().
  1327. llvm::BasicBlock *UnreachableBlock = nullptr;
  1328. /// Counts of the number return expressions in the function.
  1329. unsigned NumReturnExprs = 0;
  1330. /// Count the number of simple (constant) return expressions in the function.
  1331. unsigned NumSimpleReturnExprs = 0;
  1332. /// The last regular (non-return) debug location (breakpoint) in the function.
  1333. SourceLocation LastStopPoint;
  1334. public:
  1335. /// Source location information about the default argument or member
  1336. /// initializer expression we're evaluating, if any.
  1337. CurrentSourceLocExprScope CurSourceLocExprScope;
  1338. using SourceLocExprScopeGuard =
  1339. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  1340. /// A scope within which we are constructing the fields of an object which
  1341. /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
  1342. /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
  1343. class FieldConstructionScope {
  1344. public:
  1345. FieldConstructionScope(CodeGenFunction &CGF, Address This)
  1346. : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
  1347. CGF.CXXDefaultInitExprThis = This;
  1348. }
  1349. ~FieldConstructionScope() {
  1350. CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
  1351. }
  1352. private:
  1353. CodeGenFunction &CGF;
  1354. Address OldCXXDefaultInitExprThis;
  1355. };
  1356. /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
  1357. /// is overridden to be the object under construction.
  1358. class CXXDefaultInitExprScope {
  1359. public:
  1360. CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E)
  1361. : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
  1362. OldCXXThisAlignment(CGF.CXXThisAlignment),
  1363. SourceLocScope(E, CGF.CurSourceLocExprScope) {
  1364. CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
  1365. CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
  1366. }
  1367. ~CXXDefaultInitExprScope() {
  1368. CGF.CXXThisValue = OldCXXThisValue;
  1369. CGF.CXXThisAlignment = OldCXXThisAlignment;
  1370. }
  1371. public:
  1372. CodeGenFunction &CGF;
  1373. llvm::Value *OldCXXThisValue;
  1374. CharUnits OldCXXThisAlignment;
  1375. SourceLocExprScopeGuard SourceLocScope;
  1376. };
  1377. struct CXXDefaultArgExprScope : SourceLocExprScopeGuard {
  1378. CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E)
  1379. : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {}
  1380. };
  1381. /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
  1382. /// current loop index is overridden.
  1383. class ArrayInitLoopExprScope {
  1384. public:
  1385. ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
  1386. : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
  1387. CGF.ArrayInitIndex = Index;
  1388. }
  1389. ~ArrayInitLoopExprScope() {
  1390. CGF.ArrayInitIndex = OldArrayInitIndex;
  1391. }
  1392. private:
  1393. CodeGenFunction &CGF;
  1394. llvm::Value *OldArrayInitIndex;
  1395. };
  1396. class InlinedInheritingConstructorScope {
  1397. public:
  1398. InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
  1399. : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
  1400. OldCurCodeDecl(CGF.CurCodeDecl),
  1401. OldCXXABIThisDecl(CGF.CXXABIThisDecl),
  1402. OldCXXABIThisValue(CGF.CXXABIThisValue),
  1403. OldCXXThisValue(CGF.CXXThisValue),
  1404. OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
  1405. OldCXXThisAlignment(CGF.CXXThisAlignment),
  1406. OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
  1407. OldCXXInheritedCtorInitExprArgs(
  1408. std::move(CGF.CXXInheritedCtorInitExprArgs)) {
  1409. CGF.CurGD = GD;
  1410. CGF.CurFuncDecl = CGF.CurCodeDecl =
  1411. cast<CXXConstructorDecl>(GD.getDecl());
  1412. CGF.CXXABIThisDecl = nullptr;
  1413. CGF.CXXABIThisValue = nullptr;
  1414. CGF.CXXThisValue = nullptr;
  1415. CGF.CXXABIThisAlignment = CharUnits();
  1416. CGF.CXXThisAlignment = CharUnits();
  1417. CGF.ReturnValue = Address::invalid();
  1418. CGF.FnRetTy = QualType();
  1419. CGF.CXXInheritedCtorInitExprArgs.clear();
  1420. }
  1421. ~InlinedInheritingConstructorScope() {
  1422. CGF.CurGD = OldCurGD;
  1423. CGF.CurFuncDecl = OldCurFuncDecl;
  1424. CGF.CurCodeDecl = OldCurCodeDecl;
  1425. CGF.CXXABIThisDecl = OldCXXABIThisDecl;
  1426. CGF.CXXABIThisValue = OldCXXABIThisValue;
  1427. CGF.CXXThisValue = OldCXXThisValue;
  1428. CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
  1429. CGF.CXXThisAlignment = OldCXXThisAlignment;
  1430. CGF.ReturnValue = OldReturnValue;
  1431. CGF.FnRetTy = OldFnRetTy;
  1432. CGF.CXXInheritedCtorInitExprArgs =
  1433. std::move(OldCXXInheritedCtorInitExprArgs);
  1434. }
  1435. private:
  1436. CodeGenFunction &CGF;
  1437. GlobalDecl OldCurGD;
  1438. const Decl *OldCurFuncDecl;
  1439. const Decl *OldCurCodeDecl;
  1440. ImplicitParamDecl *OldCXXABIThisDecl;
  1441. llvm::Value *OldCXXABIThisValue;
  1442. llvm::Value *OldCXXThisValue;
  1443. CharUnits OldCXXABIThisAlignment;
  1444. CharUnits OldCXXThisAlignment;
  1445. Address OldReturnValue;
  1446. QualType OldFnRetTy;
  1447. CallArgList OldCXXInheritedCtorInitExprArgs;
  1448. };
  1449. // Helper class for the OpenMP IR Builder. Allows reusability of code used for
  1450. // region body, and finalization codegen callbacks. This will class will also
  1451. // contain privatization functions used by the privatization call backs
  1452. //
  1453. // TODO: this is temporary class for things that are being moved out of
  1454. // CGOpenMPRuntime, new versions of current CodeGenFunction methods, or
  1455. // utility function for use with the OMPBuilder. Once that move to use the
  1456. // OMPBuilder is done, everything here will either become part of CodeGenFunc.
  1457. // directly, or a new helper class that will contain functions used by both
  1458. // this and the OMPBuilder
  1459. struct OMPBuilderCBHelpers {
  1460. OMPBuilderCBHelpers() = delete;
  1461. OMPBuilderCBHelpers(const OMPBuilderCBHelpers &) = delete;
  1462. OMPBuilderCBHelpers &operator=(const OMPBuilderCBHelpers &) = delete;
  1463. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  1464. /// Cleanup action for allocate support.
  1465. class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup {
  1466. private:
  1467. llvm::CallInst *RTLFnCI;
  1468. public:
  1469. OMPAllocateCleanupTy(llvm::CallInst *RLFnCI) : RTLFnCI(RLFnCI) {
  1470. RLFnCI->removeFromParent();
  1471. }
  1472. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  1473. if (!CGF.HaveInsertPoint())
  1474. return;
  1475. CGF.Builder.Insert(RTLFnCI);
  1476. }
  1477. };
  1478. /// Returns address of the threadprivate variable for the current
  1479. /// thread. This Also create any necessary OMP runtime calls.
  1480. ///
  1481. /// \param VD VarDecl for Threadprivate variable.
  1482. /// \param VDAddr Address of the Vardecl
  1483. /// \param Loc The location where the barrier directive was encountered
  1484. static Address getAddrOfThreadPrivate(CodeGenFunction &CGF,
  1485. const VarDecl *VD, Address VDAddr,
  1486. SourceLocation Loc);
  1487. /// Gets the OpenMP-specific address of the local variable /p VD.
  1488. static Address getAddressOfLocalVariable(CodeGenFunction &CGF,
  1489. const VarDecl *VD);
  1490. /// Get the platform-specific name separator.
  1491. /// \param Parts different parts of the final name that needs separation
  1492. /// \param FirstSeparator First separator used between the initial two
  1493. /// parts of the name.
  1494. /// \param Separator separator used between all of the rest consecutinve
  1495. /// parts of the name
  1496. static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
  1497. StringRef FirstSeparator = ".",
  1498. StringRef Separator = ".");
  1499. /// Emit the Finalization for an OMP region
  1500. /// \param CGF The Codegen function this belongs to
  1501. /// \param IP Insertion point for generating the finalization code.
  1502. static void FinalizeOMPRegion(CodeGenFunction &CGF, InsertPointTy IP) {
  1503. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  1504. assert(IP.getBlock()->end() != IP.getPoint() &&
  1505. "OpenMP IR Builder should cause terminated block!");
  1506. llvm::BasicBlock *IPBB = IP.getBlock();
  1507. llvm::BasicBlock *DestBB = IPBB->getUniqueSuccessor();
  1508. assert(DestBB && "Finalization block should have one successor!");
  1509. // erase and replace with cleanup branch.
  1510. IPBB->getTerminator()->eraseFromParent();
  1511. CGF.Builder.SetInsertPoint(IPBB);
  1512. CodeGenFunction::JumpDest Dest = CGF.getJumpDestInCurrentScope(DestBB);
  1513. CGF.EmitBranchThroughCleanup(Dest);
  1514. }
  1515. /// Emit the body of an OMP region
  1516. /// \param CGF The Codegen function this belongs to
  1517. /// \param RegionBodyStmt The body statement for the OpenMP region being
  1518. /// generated
  1519. /// \param CodeGenIP Insertion point for generating the body code.
  1520. /// \param FiniBB The finalization basic block
  1521. static void EmitOMPRegionBody(CodeGenFunction &CGF,
  1522. const Stmt *RegionBodyStmt,
  1523. InsertPointTy CodeGenIP,
  1524. llvm::BasicBlock &FiniBB) {
  1525. llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
  1526. if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator())
  1527. CodeGenIPBBTI->eraseFromParent();
  1528. CGF.Builder.SetInsertPoint(CodeGenIPBB);
  1529. CGF.EmitStmt(RegionBodyStmt);
  1530. if (CGF.Builder.saveIP().isSet())
  1531. CGF.Builder.CreateBr(&FiniBB);
  1532. }
  1533. static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP,
  1534. llvm::BasicBlock &FiniBB, llvm::Function *Fn,
  1535. ArrayRef<llvm::Value *> Args) {
  1536. llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
  1537. if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator())
  1538. CodeGenIPBBTI->eraseFromParent();
  1539. CGF.Builder.SetInsertPoint(CodeGenIPBB);
  1540. if (Fn->doesNotThrow())
  1541. CGF.EmitNounwindRuntimeCall(Fn, Args);
  1542. else
  1543. CGF.EmitRuntimeCall(Fn, Args);
  1544. if (CGF.Builder.saveIP().isSet())
  1545. CGF.Builder.CreateBr(&FiniBB);
  1546. }
  1547. /// RAII for preserving necessary info during Outlined region body codegen.
  1548. class OutlinedRegionBodyRAII {
  1549. llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
  1550. CodeGenFunction::JumpDest OldReturnBlock;
  1551. CGBuilderTy::InsertPoint IP;
  1552. CodeGenFunction &CGF;
  1553. public:
  1554. OutlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP,
  1555. llvm::BasicBlock &RetBB)
  1556. : CGF(cgf) {
  1557. assert(AllocaIP.isSet() &&
  1558. "Must specify Insertion point for allocas of outlined function");
  1559. OldAllocaIP = CGF.AllocaInsertPt;
  1560. CGF.AllocaInsertPt = &*AllocaIP.getPoint();
  1561. IP = CGF.Builder.saveIP();
  1562. OldReturnBlock = CGF.ReturnBlock;
  1563. CGF.ReturnBlock = CGF.getJumpDestInCurrentScope(&RetBB);
  1564. }
  1565. ~OutlinedRegionBodyRAII() {
  1566. CGF.AllocaInsertPt = OldAllocaIP;
  1567. CGF.ReturnBlock = OldReturnBlock;
  1568. CGF.Builder.restoreIP(IP);
  1569. }
  1570. };
  1571. /// RAII for preserving necessary info during inlined region body codegen.
  1572. class InlinedRegionBodyRAII {
  1573. llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
  1574. CodeGenFunction &CGF;
  1575. public:
  1576. InlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP,
  1577. llvm::BasicBlock &FiniBB)
  1578. : CGF(cgf) {
  1579. // Alloca insertion block should be in the entry block of the containing
  1580. // function so it expects an empty AllocaIP in which case will reuse the
  1581. // old alloca insertion point, or a new AllocaIP in the same block as
  1582. // the old one
  1583. assert((!AllocaIP.isSet() ||
  1584. CGF.AllocaInsertPt->getParent() == AllocaIP.getBlock()) &&
  1585. "Insertion point should be in the entry block of containing "
  1586. "function!");
  1587. OldAllocaIP = CGF.AllocaInsertPt;
  1588. if (AllocaIP.isSet())
  1589. CGF.AllocaInsertPt = &*AllocaIP.getPoint();
  1590. // TODO: Remove the call, after making sure the counter is not used by
  1591. // the EHStack.
  1592. // Since this is an inlined region, it should not modify the
  1593. // ReturnBlock, and should reuse the one for the enclosing outlined
  1594. // region. So, the JumpDest being return by the function is discarded
  1595. (void)CGF.getJumpDestInCurrentScope(&FiniBB);
  1596. }
  1597. ~InlinedRegionBodyRAII() { CGF.AllocaInsertPt = OldAllocaIP; }
  1598. };
  1599. };
  1600. private:
  1601. /// CXXThisDecl - When generating code for a C++ member function,
  1602. /// this will hold the implicit 'this' declaration.
  1603. ImplicitParamDecl *CXXABIThisDecl = nullptr;
  1604. llvm::Value *CXXABIThisValue = nullptr;
  1605. llvm::Value *CXXThisValue = nullptr;
  1606. CharUnits CXXABIThisAlignment;
  1607. CharUnits CXXThisAlignment;
  1608. /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
  1609. /// this expression.
  1610. Address CXXDefaultInitExprThis = Address::invalid();
  1611. /// The current array initialization index when evaluating an
  1612. /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
  1613. llvm::Value *ArrayInitIndex = nullptr;
  1614. /// The values of function arguments to use when evaluating
  1615. /// CXXInheritedCtorInitExprs within this context.
  1616. CallArgList CXXInheritedCtorInitExprArgs;
  1617. /// CXXStructorImplicitParamDecl - When generating code for a constructor or
  1618. /// destructor, this will hold the implicit argument (e.g. VTT).
  1619. ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
  1620. llvm::Value *CXXStructorImplicitParamValue = nullptr;
  1621. /// OutermostConditional - Points to the outermost active
  1622. /// conditional control. This is used so that we know if a
  1623. /// temporary should be destroyed conditionally.
  1624. ConditionalEvaluation *OutermostConditional = nullptr;
  1625. /// The current lexical scope.
  1626. LexicalScope *CurLexicalScope = nullptr;
  1627. /// The current source location that should be used for exception
  1628. /// handling code.
  1629. SourceLocation CurEHLocation;
  1630. /// BlockByrefInfos - For each __block variable, contains
  1631. /// information about the layout of the variable.
  1632. llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
  1633. /// Used by -fsanitize=nullability-return to determine whether the return
  1634. /// value can be checked.
  1635. llvm::Value *RetValNullabilityPrecondition = nullptr;
  1636. /// Check if -fsanitize=nullability-return instrumentation is required for
  1637. /// this function.
  1638. bool requiresReturnValueNullabilityCheck() const {
  1639. return RetValNullabilityPrecondition;
  1640. }
  1641. /// Used to store precise source locations for return statements by the
  1642. /// runtime return value checks.
  1643. Address ReturnLocation = Address::invalid();
  1644. /// Check if the return value of this function requires sanitization.
  1645. bool requiresReturnValueCheck() const;
  1646. llvm::BasicBlock *TerminateLandingPad = nullptr;
  1647. llvm::BasicBlock *TerminateHandler = nullptr;
  1648. llvm::SmallVector<llvm::BasicBlock *, 2> TrapBBs;
  1649. /// Terminate funclets keyed by parent funclet pad.
  1650. llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
  1651. /// Largest vector width used in ths function. Will be used to create a
  1652. /// function attribute.
  1653. unsigned LargestVectorWidth = 0;
  1654. /// True if we need emit the life-time markers. This is initially set in
  1655. /// the constructor, but could be overwritten to true if this is a coroutine.
  1656. bool ShouldEmitLifetimeMarkers;
  1657. /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
  1658. /// the function metadata.
  1659. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  1660. llvm::Function *Fn);
  1661. public:
  1662. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  1663. ~CodeGenFunction();
  1664. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  1665. ASTContext &getContext() const { return CGM.getContext(); }
  1666. CGDebugInfo *getDebugInfo() {
  1667. if (DisableDebugInfo)
  1668. return nullptr;
  1669. return DebugInfo;
  1670. }
  1671. void disableDebugInfo() { DisableDebugInfo = true; }
  1672. void enableDebugInfo() { DisableDebugInfo = false; }
  1673. bool shouldUseFusedARCCalls() {
  1674. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  1675. }
  1676. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  1677. /// Returns a pointer to the function's exception object and selector slot,
  1678. /// which is assigned in every landing pad.
  1679. Address getExceptionSlot();
  1680. Address getEHSelectorSlot();
  1681. /// Returns the contents of the function's exception object and selector
  1682. /// slots.
  1683. llvm::Value *getExceptionFromSlot();
  1684. llvm::Value *getSelectorFromSlot();
  1685. Address getNormalCleanupDestSlot();
  1686. llvm::BasicBlock *getUnreachableBlock() {
  1687. if (!UnreachableBlock) {
  1688. UnreachableBlock = createBasicBlock("unreachable");
  1689. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  1690. }
  1691. return UnreachableBlock;
  1692. }
  1693. llvm::BasicBlock *getInvokeDest() {
  1694. if (!EHStack.requiresLandingPad()) return nullptr;
  1695. return getInvokeDestImpl();
  1696. }
  1697. bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
  1698. const TargetInfo &getTarget() const { return Target; }
  1699. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  1700. const TargetCodeGenInfo &getTargetHooks() const {
  1701. return CGM.getTargetCodeGenInfo();
  1702. }
  1703. //===--------------------------------------------------------------------===//
  1704. // Cleanups
  1705. //===--------------------------------------------------------------------===//
  1706. typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
  1707. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1708. Address arrayEndPointer,
  1709. QualType elementType,
  1710. CharUnits elementAlignment,
  1711. Destroyer *destroyer);
  1712. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1713. llvm::Value *arrayEnd,
  1714. QualType elementType,
  1715. CharUnits elementAlignment,
  1716. Destroyer *destroyer);
  1717. void pushDestroy(QualType::DestructionKind dtorKind,
  1718. Address addr, QualType type);
  1719. void pushEHDestroy(QualType::DestructionKind dtorKind,
  1720. Address addr, QualType type);
  1721. void pushDestroy(CleanupKind kind, Address addr, QualType type,
  1722. Destroyer *destroyer, bool useEHCleanupForArray);
  1723. void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
  1724. QualType type, Destroyer *destroyer,
  1725. bool useEHCleanupForArray);
  1726. void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
  1727. llvm::Value *CompletePtr,
  1728. QualType ElementType);
  1729. void pushStackRestore(CleanupKind kind, Address SPMem);
  1730. void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
  1731. bool useEHCleanupForArray);
  1732. llvm::Function *generateDestroyHelper(Address addr, QualType type,
  1733. Destroyer *destroyer,
  1734. bool useEHCleanupForArray,
  1735. const VarDecl *VD);
  1736. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  1737. QualType elementType, CharUnits elementAlign,
  1738. Destroyer *destroyer,
  1739. bool checkZeroLength, bool useEHCleanup);
  1740. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  1741. /// Determines whether an EH cleanup is required to destroy a type
  1742. /// with the given destruction kind.
  1743. bool needsEHCleanup(QualType::DestructionKind kind) {
  1744. switch (kind) {
  1745. case QualType::DK_none:
  1746. return false;
  1747. case QualType::DK_cxx_destructor:
  1748. case QualType::DK_objc_weak_lifetime:
  1749. case QualType::DK_nontrivial_c_struct:
  1750. return getLangOpts().Exceptions;
  1751. case QualType::DK_objc_strong_lifetime:
  1752. return getLangOpts().Exceptions &&
  1753. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1754. }
  1755. llvm_unreachable("bad destruction kind");
  1756. }
  1757. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1758. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1759. }
  1760. //===--------------------------------------------------------------------===//
  1761. // Objective-C
  1762. //===--------------------------------------------------------------------===//
  1763. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1764. void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
  1765. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1766. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1767. const ObjCPropertyImplDecl *PID);
  1768. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1769. const ObjCPropertyImplDecl *propImpl,
  1770. const ObjCMethodDecl *GetterMothodDecl,
  1771. llvm::Constant *AtomicHelperFn);
  1772. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1773. ObjCMethodDecl *MD, bool ctor);
  1774. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1775. /// for the given property.
  1776. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1777. const ObjCPropertyImplDecl *PID);
  1778. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1779. const ObjCPropertyImplDecl *propImpl,
  1780. llvm::Constant *AtomicHelperFn);
  1781. //===--------------------------------------------------------------------===//
  1782. // Block Bits
  1783. //===--------------------------------------------------------------------===//
  1784. /// Emit block literal.
  1785. /// \return an LLVM value which is a pointer to a struct which contains
  1786. /// information about the block, including the block invoke function, the
  1787. /// captured variables, etc.
  1788. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1789. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1790. const CGBlockInfo &Info,
  1791. const DeclMapTy &ldm,
  1792. bool IsLambdaConversionToBlock,
  1793. bool BuildGlobalBlock);
  1794. /// Check if \p T is a C++ class that has a destructor that can throw.
  1795. static bool cxxDestructorCanThrow(QualType T);
  1796. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1797. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1798. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1799. const ObjCPropertyImplDecl *PID);
  1800. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1801. const ObjCPropertyImplDecl *PID);
  1802. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1803. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
  1804. bool CanThrow);
  1805. class AutoVarEmission;
  1806. void emitByrefStructureInit(const AutoVarEmission &emission);
  1807. /// Enter a cleanup to destroy a __block variable. Note that this
  1808. /// cleanup should be a no-op if the variable hasn't left the stack
  1809. /// yet; if a cleanup is required for the variable itself, that needs
  1810. /// to be done externally.
  1811. ///
  1812. /// \param Kind Cleanup kind.
  1813. ///
  1814. /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
  1815. /// structure that will be passed to _Block_object_dispose. When
  1816. /// \p LoadBlockVarAddr is true, the address of the field of the block
  1817. /// structure that holds the address of the __block structure.
  1818. ///
  1819. /// \param Flags The flag that will be passed to _Block_object_dispose.
  1820. ///
  1821. /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
  1822. /// \p Addr to get the address of the __block structure.
  1823. void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags,
  1824. bool LoadBlockVarAddr, bool CanThrow);
  1825. void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
  1826. llvm::Value *ptr);
  1827. Address LoadBlockStruct();
  1828. Address GetAddrOfBlockDecl(const VarDecl *var);
  1829. /// BuildBlockByrefAddress - Computes the location of the
  1830. /// data in a variable which is declared as __block.
  1831. Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
  1832. bool followForward = true);
  1833. Address emitBlockByrefAddress(Address baseAddr,
  1834. const BlockByrefInfo &info,
  1835. bool followForward,
  1836. const llvm::Twine &name);
  1837. const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
  1838. QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
  1839. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1840. const CGFunctionInfo &FnInfo);
  1841. /// Annotate the function with an attribute that disables TSan checking at
  1842. /// runtime.
  1843. void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
  1844. /// Emit code for the start of a function.
  1845. /// \param Loc The location to be associated with the function.
  1846. /// \param StartLoc The location of the function body.
  1847. void StartFunction(GlobalDecl GD,
  1848. QualType RetTy,
  1849. llvm::Function *Fn,
  1850. const CGFunctionInfo &FnInfo,
  1851. const FunctionArgList &Args,
  1852. SourceLocation Loc = SourceLocation(),
  1853. SourceLocation StartLoc = SourceLocation());
  1854. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
  1855. void EmitConstructorBody(FunctionArgList &Args);
  1856. void EmitDestructorBody(FunctionArgList &Args);
  1857. void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
  1858. void EmitFunctionBody(const Stmt *Body);
  1859. void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
  1860. void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
  1861. CallArgList &CallArgs);
  1862. void EmitLambdaBlockInvokeBody();
  1863. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1864. void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
  1865. void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) {
  1866. EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
  1867. }
  1868. void EmitAsanPrologueOrEpilogue(bool Prologue);
  1869. /// Emit the unified return block, trying to avoid its emission when
  1870. /// possible.
  1871. /// \return The debug location of the user written return statement if the
  1872. /// return block is is avoided.
  1873. llvm::DebugLoc EmitReturnBlock();
  1874. /// FinishFunction - Complete IR generation of the current function. It is
  1875. /// legal to call this function even if there is no current insertion point.
  1876. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1877. void StartThunk(llvm::Function *Fn, GlobalDecl GD,
  1878. const CGFunctionInfo &FnInfo, bool IsUnprototyped);
  1879. void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
  1880. const ThunkInfo *Thunk, bool IsUnprototyped);
  1881. void FinishThunk();
  1882. /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
  1883. void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
  1884. llvm::FunctionCallee Callee);
  1885. /// Generate a thunk for the given method.
  1886. void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1887. GlobalDecl GD, const ThunkInfo &Thunk,
  1888. bool IsUnprototyped);
  1889. llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
  1890. const CGFunctionInfo &FnInfo,
  1891. GlobalDecl GD, const ThunkInfo &Thunk);
  1892. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1893. FunctionArgList &Args);
  1894. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
  1895. /// Struct with all information about dynamic [sub]class needed to set vptr.
  1896. struct VPtr {
  1897. BaseSubobject Base;
  1898. const CXXRecordDecl *NearestVBase;
  1899. CharUnits OffsetFromNearestVBase;
  1900. const CXXRecordDecl *VTableClass;
  1901. };
  1902. /// Initialize the vtable pointer of the given subobject.
  1903. void InitializeVTablePointer(const VPtr &vptr);
  1904. typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
  1905. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1906. VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
  1907. void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
  1908. CharUnits OffsetFromNearestVBase,
  1909. bool BaseIsNonVirtualPrimaryBase,
  1910. const CXXRecordDecl *VTableClass,
  1911. VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
  1912. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1913. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1914. /// to by This.
  1915. llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
  1916. const CXXRecordDecl *VTableClass);
  1917. enum CFITypeCheckKind {
  1918. CFITCK_VCall,
  1919. CFITCK_NVCall,
  1920. CFITCK_DerivedCast,
  1921. CFITCK_UnrelatedCast,
  1922. CFITCK_ICall,
  1923. CFITCK_NVMFCall,
  1924. CFITCK_VMFCall,
  1925. };
  1926. /// Derived is the presumed address of an object of type T after a
  1927. /// cast. If T is a polymorphic class type, emit a check that the virtual
  1928. /// table for Derived belongs to a class derived from T.
  1929. void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
  1930. bool MayBeNull, CFITypeCheckKind TCK,
  1931. SourceLocation Loc);
  1932. /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
  1933. /// If vptr CFI is enabled, emit a check that VTable is valid.
  1934. void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
  1935. CFITypeCheckKind TCK, SourceLocation Loc);
  1936. /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
  1937. /// RD using llvm.type.test.
  1938. void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
  1939. CFITypeCheckKind TCK, SourceLocation Loc);
  1940. /// If whole-program virtual table optimization is enabled, emit an assumption
  1941. /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
  1942. /// enabled, emit a check that VTable is a member of RD's type identifier.
  1943. void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
  1944. llvm::Value *VTable, SourceLocation Loc);
  1945. /// Returns whether we should perform a type checked load when loading a
  1946. /// virtual function for virtual calls to members of RD. This is generally
  1947. /// true when both vcall CFI and whole-program-vtables are enabled.
  1948. bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
  1949. /// Emit a type checked load from the given vtable.
  1950. llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
  1951. uint64_t VTableByteOffset);
  1952. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1953. /// given phase of destruction for a destructor. The end result
  1954. /// should call destructors on members and base classes in reverse
  1955. /// order of their construction.
  1956. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1957. /// ShouldInstrumentFunction - Return true if the current function should be
  1958. /// instrumented with __cyg_profile_func_* calls
  1959. bool ShouldInstrumentFunction();
  1960. /// ShouldSkipSanitizerInstrumentation - Return true if the current function
  1961. /// should not be instrumented with sanitizers.
  1962. bool ShouldSkipSanitizerInstrumentation();
  1963. /// ShouldXRayInstrument - Return true if the current function should be
  1964. /// instrumented with XRay nop sleds.
  1965. bool ShouldXRayInstrumentFunction() const;
  1966. /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
  1967. /// XRay custom event handling calls.
  1968. bool AlwaysEmitXRayCustomEvents() const;
  1969. /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
  1970. /// XRay typed event handling calls.
  1971. bool AlwaysEmitXRayTypedEvents() const;
  1972. /// Encode an address into a form suitable for use in a function prologue.
  1973. llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F,
  1974. llvm::Constant *Addr);
  1975. /// Decode an address used in a function prologue, encoded by \c
  1976. /// EncodeAddrForUseInPrologue.
  1977. llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F,
  1978. llvm::Value *EncodedAddr);
  1979. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1980. /// arguments for the given function. This is also responsible for naming the
  1981. /// LLVM function arguments.
  1982. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1983. llvm::Function *Fn,
  1984. const FunctionArgList &Args);
  1985. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1986. /// given temporary.
  1987. void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
  1988. SourceLocation EndLoc);
  1989. /// Emit a test that checks if the return value \p RV is nonnull.
  1990. void EmitReturnValueCheck(llvm::Value *RV);
  1991. /// EmitStartEHSpec - Emit the start of the exception spec.
  1992. void EmitStartEHSpec(const Decl *D);
  1993. /// EmitEndEHSpec - Emit the end of the exception spec.
  1994. void EmitEndEHSpec(const Decl *D);
  1995. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1996. llvm::BasicBlock *getTerminateLandingPad();
  1997. /// getTerminateLandingPad - Return a cleanup funclet that just calls
  1998. /// terminate.
  1999. llvm::BasicBlock *getTerminateFunclet();
  2000. /// getTerminateHandler - Return a handler (not a landing pad, just
  2001. /// a catch handler) that just calls terminate. This is used when
  2002. /// a terminate scope encloses a try.
  2003. llvm::BasicBlock *getTerminateHandler();
  2004. llvm::Type *ConvertTypeForMem(QualType T);
  2005. llvm::Type *ConvertType(QualType T);
  2006. llvm::Type *ConvertType(const TypeDecl *T) {
  2007. return ConvertType(getContext().getTypeDeclType(T));
  2008. }
  2009. /// LoadObjCSelf - Load the value of self. This function is only valid while
  2010. /// generating code for an Objective-C method.
  2011. llvm::Value *LoadObjCSelf();
  2012. /// TypeOfSelfObject - Return type of object that this self represents.
  2013. QualType TypeOfSelfObject();
  2014. /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
  2015. static TypeEvaluationKind getEvaluationKind(QualType T);
  2016. static bool hasScalarEvaluationKind(QualType T) {
  2017. return getEvaluationKind(T) == TEK_Scalar;
  2018. }
  2019. static bool hasAggregateEvaluationKind(QualType T) {
  2020. return getEvaluationKind(T) == TEK_Aggregate;
  2021. }
  2022. /// createBasicBlock - Create an LLVM basic block.
  2023. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  2024. llvm::Function *parent = nullptr,
  2025. llvm::BasicBlock *before = nullptr) {
  2026. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  2027. }
  2028. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  2029. /// label maps to.
  2030. JumpDest getJumpDestForLabel(const LabelDecl *S);
  2031. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  2032. /// another basic block, simplify it. This assumes that no other code could
  2033. /// potentially reference the basic block.
  2034. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  2035. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  2036. /// adding a fall-through branch from the current insert block if
  2037. /// necessary. It is legal to call this function even if there is no current
  2038. /// insertion point.
  2039. ///
  2040. /// IsFinished - If true, indicates that the caller has finished emitting
  2041. /// branches to the given block and does not expect to emit code into it. This
  2042. /// means the block can be ignored if it is unreachable.
  2043. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  2044. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  2045. /// near its uses, and leave the insertion point in it.
  2046. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  2047. /// EmitBranch - Emit a branch to the specified basic block from the current
  2048. /// insert block, taking care to avoid creation of branches from dummy
  2049. /// blocks. It is legal to call this function even if there is no current
  2050. /// insertion point.
  2051. ///
  2052. /// This function clears the current insertion point. The caller should follow
  2053. /// calls to this function with calls to Emit*Block prior to generation new
  2054. /// code.
  2055. void EmitBranch(llvm::BasicBlock *Block);
  2056. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  2057. /// indicates that the current code being emitted is unreachable.
  2058. bool HaveInsertPoint() const {
  2059. return Builder.GetInsertBlock() != nullptr;
  2060. }
  2061. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  2062. /// emitted IR has a place to go. Note that by definition, if this function
  2063. /// creates a block then that block is unreachable; callers may do better to
  2064. /// detect when no insertion point is defined and simply skip IR generation.
  2065. void EnsureInsertPoint() {
  2066. if (!HaveInsertPoint())
  2067. EmitBlock(createBasicBlock());
  2068. }
  2069. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  2070. /// specified stmt yet.
  2071. void ErrorUnsupported(const Stmt *S, const char *Type);
  2072. //===--------------------------------------------------------------------===//
  2073. // Helpers
  2074. //===--------------------------------------------------------------------===//
  2075. LValue MakeAddrLValue(Address Addr, QualType T,
  2076. AlignmentSource Source = AlignmentSource::Type) {
  2077. return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
  2078. CGM.getTBAAAccessInfo(T));
  2079. }
  2080. LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
  2081. TBAAAccessInfo TBAAInfo) {
  2082. return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
  2083. }
  2084. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  2085. AlignmentSource Source = AlignmentSource::Type) {
  2086. Address Addr(V, ConvertTypeForMem(T), Alignment);
  2087. return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
  2088. CGM.getTBAAAccessInfo(T));
  2089. }
  2090. LValue
  2091. MakeAddrLValueWithoutTBAA(Address Addr, QualType T,
  2092. AlignmentSource Source = AlignmentSource::Type) {
  2093. return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
  2094. TBAAAccessInfo());
  2095. }
  2096. LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
  2097. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
  2098. Address EmitLoadOfReference(LValue RefLVal,
  2099. LValueBaseInfo *PointeeBaseInfo = nullptr,
  2100. TBAAAccessInfo *PointeeTBAAInfo = nullptr);
  2101. LValue EmitLoadOfReferenceLValue(LValue RefLVal);
  2102. LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
  2103. AlignmentSource Source =
  2104. AlignmentSource::Type) {
  2105. LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
  2106. CGM.getTBAAAccessInfo(RefTy));
  2107. return EmitLoadOfReferenceLValue(RefLVal);
  2108. }
  2109. Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
  2110. LValueBaseInfo *BaseInfo = nullptr,
  2111. TBAAAccessInfo *TBAAInfo = nullptr);
  2112. LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
  2113. /// CreateTempAlloca - This creates an alloca and inserts it into the entry
  2114. /// block if \p ArraySize is nullptr, otherwise inserts it at the current
  2115. /// insertion point of the builder. The caller is responsible for setting an
  2116. /// appropriate alignment on
  2117. /// the alloca.
  2118. ///
  2119. /// \p ArraySize is the number of array elements to be allocated if it
  2120. /// is not nullptr.
  2121. ///
  2122. /// LangAS::Default is the address space of pointers to local variables and
  2123. /// temporaries, as exposed in the source language. In certain
  2124. /// configurations, this is not the same as the alloca address space, and a
  2125. /// cast is needed to lift the pointer from the alloca AS into
  2126. /// LangAS::Default. This can happen when the target uses a restricted
  2127. /// address space for the stack but the source language requires
  2128. /// LangAS::Default to be a generic address space. The latter condition is
  2129. /// common for most programming languages; OpenCL is an exception in that
  2130. /// LangAS::Default is the private address space, which naturally maps
  2131. /// to the stack.
  2132. ///
  2133. /// Because the address of a temporary is often exposed to the program in
  2134. /// various ways, this function will perform the cast. The original alloca
  2135. /// instruction is returned through \p Alloca if it is not nullptr.
  2136. ///
  2137. /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
  2138. /// more efficient if the caller knows that the address will not be exposed.
  2139. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
  2140. llvm::Value *ArraySize = nullptr);
  2141. Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
  2142. const Twine &Name = "tmp",
  2143. llvm::Value *ArraySize = nullptr,
  2144. Address *Alloca = nullptr);
  2145. Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align,
  2146. const Twine &Name = "tmp",
  2147. llvm::Value *ArraySize = nullptr);
  2148. /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
  2149. /// default ABI alignment of the given LLVM type.
  2150. ///
  2151. /// IMPORTANT NOTE: This is *not* generally the right alignment for
  2152. /// any given AST type that happens to have been lowered to the
  2153. /// given IR type. This should only ever be used for function-local,
  2154. /// IR-driven manipulations like saving and restoring a value. Do
  2155. /// not hand this address off to arbitrary IRGen routines, and especially
  2156. /// do not pass it as an argument to a function that might expect a
  2157. /// properly ABI-aligned value.
  2158. Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  2159. const Twine &Name = "tmp");
  2160. /// CreateIRTemp - Create a temporary IR object of the given type, with
  2161. /// appropriate alignment. This routine should only be used when an temporary
  2162. /// value needs to be stored into an alloca (for example, to avoid explicit
  2163. /// PHI construction), but the type is the IR type, not the type appropriate
  2164. /// for storing in memory.
  2165. ///
  2166. /// That is, this is exactly equivalent to CreateMemTemp, but calling
  2167. /// ConvertType instead of ConvertTypeForMem.
  2168. Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
  2169. /// CreateMemTemp - Create a temporary memory object of the given type, with
  2170. /// appropriate alignmen and cast it to the default address space. Returns
  2171. /// the original alloca instruction by \p Alloca if it is not nullptr.
  2172. Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
  2173. Address *Alloca = nullptr);
  2174. Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
  2175. Address *Alloca = nullptr);
  2176. /// CreateMemTemp - Create a temporary memory object of the given type, with
  2177. /// appropriate alignmen without casting it to the default address space.
  2178. Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
  2179. Address CreateMemTempWithoutCast(QualType T, CharUnits Align,
  2180. const Twine &Name = "tmp");
  2181. /// CreateAggTemp - Create a temporary memory object for the given
  2182. /// aggregate type.
  2183. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp",
  2184. Address *Alloca = nullptr) {
  2185. return AggValueSlot::forAddr(CreateMemTemp(T, Name, Alloca),
  2186. T.getQualifiers(),
  2187. AggValueSlot::IsNotDestructed,
  2188. AggValueSlot::DoesNotNeedGCBarriers,
  2189. AggValueSlot::IsNotAliased,
  2190. AggValueSlot::DoesNotOverlap);
  2191. }
  2192. /// Emit a cast to void* in the appropriate address space.
  2193. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  2194. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  2195. /// expression and compare the result against zero, returning an Int1Ty value.
  2196. llvm::Value *EvaluateExprAsBool(const Expr *E);
  2197. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  2198. void EmitIgnoredExpr(const Expr *E);
  2199. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  2200. /// any type. The result is returned as an RValue struct. If this is an
  2201. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  2202. /// the result should be returned.
  2203. ///
  2204. /// \param ignoreResult True if the resulting value isn't used.
  2205. RValue EmitAnyExpr(const Expr *E,
  2206. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2207. bool ignoreResult = false);
  2208. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  2209. // or the value of the expression, depending on how va_list is defined.
  2210. Address EmitVAListRef(const Expr *E);
  2211. /// Emit a "reference" to a __builtin_ms_va_list; this is
  2212. /// always the value of the expression, because a __builtin_ms_va_list is a
  2213. /// pointer to a char.
  2214. Address EmitMSVAListRef(const Expr *E);
  2215. /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
  2216. /// always be accessible even if no aggregate location is provided.
  2217. RValue EmitAnyExprToTemp(const Expr *E);
  2218. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  2219. /// arbitrary expression into the given memory location.
  2220. void EmitAnyExprToMem(const Expr *E, Address Location,
  2221. Qualifiers Quals, bool IsInitializer);
  2222. void EmitAnyExprToExn(const Expr *E, Address Addr);
  2223. /// EmitExprAsInit - Emits the code necessary to initialize a
  2224. /// location in memory with the given initializer.
  2225. void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  2226. bool capturedByInit);
  2227. /// hasVolatileMember - returns true if aggregate type has a volatile
  2228. /// member.
  2229. bool hasVolatileMember(QualType T) {
  2230. if (const RecordType *RT = T->getAs<RecordType>()) {
  2231. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  2232. return RD->hasVolatileMember();
  2233. }
  2234. return false;
  2235. }
  2236. /// Determine whether a return value slot may overlap some other object.
  2237. AggValueSlot::Overlap_t getOverlapForReturnValue() {
  2238. // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
  2239. // class subobjects. These cases may need to be revisited depending on the
  2240. // resolution of the relevant core issue.
  2241. return AggValueSlot::DoesNotOverlap;
  2242. }
  2243. /// Determine whether a field initialization may overlap some other object.
  2244. AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD);
  2245. /// Determine whether a base class initialization may overlap some other
  2246. /// object.
  2247. AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD,
  2248. const CXXRecordDecl *BaseRD,
  2249. bool IsVirtual);
  2250. /// Emit an aggregate assignment.
  2251. void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
  2252. bool IsVolatile = hasVolatileMember(EltTy);
  2253. EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
  2254. }
  2255. void EmitAggregateCopyCtor(LValue Dest, LValue Src,
  2256. AggValueSlot::Overlap_t MayOverlap) {
  2257. EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
  2258. }
  2259. /// EmitAggregateCopy - Emit an aggregate copy.
  2260. ///
  2261. /// \param isVolatile \c true iff either the source or the destination is
  2262. /// volatile.
  2263. /// \param MayOverlap Whether the tail padding of the destination might be
  2264. /// occupied by some other object. More efficient code can often be
  2265. /// generated if not.
  2266. void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
  2267. AggValueSlot::Overlap_t MayOverlap,
  2268. bool isVolatile = false);
  2269. /// GetAddrOfLocalVar - Return the address of a local variable.
  2270. Address GetAddrOfLocalVar(const VarDecl *VD) {
  2271. auto it = LocalDeclMap.find(VD);
  2272. assert(it != LocalDeclMap.end() &&
  2273. "Invalid argument to GetAddrOfLocalVar(), no decl!");
  2274. return it->second;
  2275. }
  2276. /// Given an opaque value expression, return its LValue mapping if it exists,
  2277. /// otherwise create one.
  2278. LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
  2279. /// Given an opaque value expression, return its RValue mapping if it exists,
  2280. /// otherwise create one.
  2281. RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
  2282. /// Get the index of the current ArrayInitLoopExpr, if any.
  2283. llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
  2284. /// getAccessedFieldNo - Given an encoded value and a result number, return
  2285. /// the input field number being accessed.
  2286. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  2287. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  2288. llvm::BasicBlock *GetIndirectGotoBlock();
  2289. /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
  2290. static bool IsWrappedCXXThis(const Expr *E);
  2291. /// EmitNullInitialization - Generate code to set a value of the given type to
  2292. /// null, If the type contains data member pointers, they will be initialized
  2293. /// to -1 in accordance with the Itanium C++ ABI.
  2294. void EmitNullInitialization(Address DestPtr, QualType Ty);
  2295. /// Emits a call to an LLVM variable-argument intrinsic, either
  2296. /// \c llvm.va_start or \c llvm.va_end.
  2297. /// \param ArgValue A reference to the \c va_list as emitted by either
  2298. /// \c EmitVAListRef or \c EmitMSVAListRef.
  2299. /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
  2300. /// calls \c llvm.va_end.
  2301. llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
  2302. /// Generate code to get an argument from the passed in pointer
  2303. /// and update it accordingly.
  2304. /// \param VE The \c VAArgExpr for which to generate code.
  2305. /// \param VAListAddr Receives a reference to the \c va_list as emitted by
  2306. /// either \c EmitVAListRef or \c EmitMSVAListRef.
  2307. /// \returns A pointer to the argument.
  2308. // FIXME: We should be able to get rid of this method and use the va_arg
  2309. // instruction in LLVM instead once it works well enough.
  2310. Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
  2311. /// emitArrayLength - Compute the length of an array, even if it's a
  2312. /// VLA, and drill down to the base element type.
  2313. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  2314. QualType &baseType,
  2315. Address &addr);
  2316. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  2317. /// the given variably-modified type and store them in the VLASizeMap.
  2318. ///
  2319. /// This function can be called with a null (unreachable) insert point.
  2320. void EmitVariablyModifiedType(QualType Ty);
  2321. struct VlaSizePair {
  2322. llvm::Value *NumElts;
  2323. QualType Type;
  2324. VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
  2325. };
  2326. /// Return the number of elements for a single dimension
  2327. /// for the given array type.
  2328. VlaSizePair getVLAElements1D(const VariableArrayType *vla);
  2329. VlaSizePair getVLAElements1D(QualType vla);
  2330. /// Returns an LLVM value that corresponds to the size,
  2331. /// in non-variably-sized elements, of a variable length array type,
  2332. /// plus that largest non-variably-sized element type. Assumes that
  2333. /// the type has already been emitted with EmitVariablyModifiedType.
  2334. VlaSizePair getVLASize(const VariableArrayType *vla);
  2335. VlaSizePair getVLASize(QualType vla);
  2336. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  2337. /// generating code for an C++ member function.
  2338. llvm::Value *LoadCXXThis() {
  2339. assert(CXXThisValue && "no 'this' value for this function");
  2340. return CXXThisValue;
  2341. }
  2342. Address LoadCXXThisAddress();
  2343. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  2344. /// virtual bases.
  2345. // FIXME: Every place that calls LoadCXXVTT is something
  2346. // that needs to be abstracted properly.
  2347. llvm::Value *LoadCXXVTT() {
  2348. assert(CXXStructorImplicitParamValue && "no VTT value for this function");
  2349. return CXXStructorImplicitParamValue;
  2350. }
  2351. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  2352. /// complete class to the given direct base.
  2353. Address
  2354. GetAddressOfDirectBaseInCompleteClass(Address Value,
  2355. const CXXRecordDecl *Derived,
  2356. const CXXRecordDecl *Base,
  2357. bool BaseIsVirtual);
  2358. static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
  2359. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  2360. /// load of 'this' and returns address of the base class.
  2361. Address GetAddressOfBaseClass(Address Value,
  2362. const CXXRecordDecl *Derived,
  2363. CastExpr::path_const_iterator PathBegin,
  2364. CastExpr::path_const_iterator PathEnd,
  2365. bool NullCheckValue, SourceLocation Loc);
  2366. Address GetAddressOfDerivedClass(Address Value,
  2367. const CXXRecordDecl *Derived,
  2368. CastExpr::path_const_iterator PathBegin,
  2369. CastExpr::path_const_iterator PathEnd,
  2370. bool NullCheckValue);
  2371. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  2372. /// base constructor/destructor with virtual bases.
  2373. /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
  2374. /// to ItaniumCXXABI.cpp together with all the references to VTT.
  2375. llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
  2376. bool Delegating);
  2377. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2378. CXXCtorType CtorType,
  2379. const FunctionArgList &Args,
  2380. SourceLocation Loc);
  2381. // It's important not to confuse this and the previous function. Delegating
  2382. // constructors are the C++0x feature. The constructor delegate optimization
  2383. // is used to reduce duplication in the base and complete consturctors where
  2384. // they are substantially the same.
  2385. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2386. const FunctionArgList &Args);
  2387. /// Emit a call to an inheriting constructor (that is, one that invokes a
  2388. /// constructor inherited from a base class) by inlining its definition. This
  2389. /// is necessary if the ABI does not support forwarding the arguments to the
  2390. /// base class constructor (because they're variadic or similar).
  2391. void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2392. CXXCtorType CtorType,
  2393. bool ForVirtualBase,
  2394. bool Delegating,
  2395. CallArgList &Args);
  2396. /// Emit a call to a constructor inherited from a base class, passing the
  2397. /// current constructor's arguments along unmodified (without even making
  2398. /// a copy).
  2399. void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
  2400. bool ForVirtualBase, Address This,
  2401. bool InheritedFromVBase,
  2402. const CXXInheritedCtorInitExpr *E);
  2403. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  2404. bool ForVirtualBase, bool Delegating,
  2405. AggValueSlot ThisAVS, const CXXConstructExpr *E);
  2406. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  2407. bool ForVirtualBase, bool Delegating,
  2408. Address This, CallArgList &Args,
  2409. AggValueSlot::Overlap_t Overlap,
  2410. SourceLocation Loc, bool NewPointerIsChecked);
  2411. /// Emit assumption load for all bases. Requires to be be called only on
  2412. /// most-derived class and not under construction of the object.
  2413. void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
  2414. /// Emit assumption that vptr load == global vtable.
  2415. void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
  2416. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  2417. Address This, Address Src,
  2418. const CXXConstructExpr *E);
  2419. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  2420. const ArrayType *ArrayTy,
  2421. Address ArrayPtr,
  2422. const CXXConstructExpr *E,
  2423. bool NewPointerIsChecked,
  2424. bool ZeroInitialization = false);
  2425. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  2426. llvm::Value *NumElements,
  2427. Address ArrayPtr,
  2428. const CXXConstructExpr *E,
  2429. bool NewPointerIsChecked,
  2430. bool ZeroInitialization = false);
  2431. static Destroyer destroyCXXObject;
  2432. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  2433. bool ForVirtualBase, bool Delegating, Address This,
  2434. QualType ThisTy);
  2435. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  2436. llvm::Type *ElementTy, Address NewPtr,
  2437. llvm::Value *NumElements,
  2438. llvm::Value *AllocSizeWithoutCookie);
  2439. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  2440. Address Ptr);
  2441. void EmitSehCppScopeBegin();
  2442. void EmitSehCppScopeEnd();
  2443. void EmitSehTryScopeBegin();
  2444. void EmitSehTryScopeEnd();
  2445. llvm::Value *EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr);
  2446. void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
  2447. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  2448. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  2449. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  2450. QualType DeleteTy, llvm::Value *NumElements = nullptr,
  2451. CharUnits CookieSize = CharUnits());
  2452. RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
  2453. const CallExpr *TheCallExpr, bool IsDelete);
  2454. llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  2455. llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
  2456. Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  2457. /// Situations in which we might emit a check for the suitability of a
  2458. /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in
  2459. /// compiler-rt.
  2460. enum TypeCheckKind {
  2461. /// Checking the operand of a load. Must be suitably sized and aligned.
  2462. TCK_Load,
  2463. /// Checking the destination of a store. Must be suitably sized and aligned.
  2464. TCK_Store,
  2465. /// Checking the bound value in a reference binding. Must be suitably sized
  2466. /// and aligned, but is not required to refer to an object (until the
  2467. /// reference is used), per core issue 453.
  2468. TCK_ReferenceBinding,
  2469. /// Checking the object expression in a non-static data member access. Must
  2470. /// be an object within its lifetime.
  2471. TCK_MemberAccess,
  2472. /// Checking the 'this' pointer for a call to a non-static member function.
  2473. /// Must be an object within its lifetime.
  2474. TCK_MemberCall,
  2475. /// Checking the 'this' pointer for a constructor call.
  2476. TCK_ConstructorCall,
  2477. /// Checking the operand of a static_cast to a derived pointer type. Must be
  2478. /// null or an object within its lifetime.
  2479. TCK_DowncastPointer,
  2480. /// Checking the operand of a static_cast to a derived reference type. Must
  2481. /// be an object within its lifetime.
  2482. TCK_DowncastReference,
  2483. /// Checking the operand of a cast to a base object. Must be suitably sized
  2484. /// and aligned.
  2485. TCK_Upcast,
  2486. /// Checking the operand of a cast to a virtual base object. Must be an
  2487. /// object within its lifetime.
  2488. TCK_UpcastToVirtualBase,
  2489. /// Checking the value assigned to a _Nonnull pointer. Must not be null.
  2490. TCK_NonnullAssign,
  2491. /// Checking the operand of a dynamic_cast or a typeid expression. Must be
  2492. /// null or an object within its lifetime.
  2493. TCK_DynamicOperation
  2494. };
  2495. /// Determine whether the pointer type check \p TCK permits null pointers.
  2496. static bool isNullPointerAllowed(TypeCheckKind TCK);
  2497. /// Determine whether the pointer type check \p TCK requires a vptr check.
  2498. static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
  2499. /// Whether any type-checking sanitizers are enabled. If \c false,
  2500. /// calls to EmitTypeCheck can be skipped.
  2501. bool sanitizePerformTypeCheck() const;
  2502. /// Emit a check that \p V is the address of storage of the
  2503. /// appropriate size and alignment for an object of type \p Type
  2504. /// (or if ArraySize is provided, for an array of that bound).
  2505. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  2506. QualType Type, CharUnits Alignment = CharUnits::Zero(),
  2507. SanitizerSet SkippedChecks = SanitizerSet(),
  2508. llvm::Value *ArraySize = nullptr);
  2509. /// Emit a check that \p Base points into an array object, which
  2510. /// we can access at index \p Index. \p Accessed should be \c false if we
  2511. /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
  2512. void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
  2513. QualType IndexType, bool Accessed);
  2514. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  2515. bool isInc, bool isPre);
  2516. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  2517. bool isInc, bool isPre);
  2518. /// Converts Location to a DebugLoc, if debug information is enabled.
  2519. llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
  2520. /// Get the record field index as represented in debug info.
  2521. unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
  2522. //===--------------------------------------------------------------------===//
  2523. // Declaration Emission
  2524. //===--------------------------------------------------------------------===//
  2525. /// EmitDecl - Emit a declaration.
  2526. ///
  2527. /// This function can be called with a null (unreachable) insert point.
  2528. void EmitDecl(const Decl &D);
  2529. /// EmitVarDecl - Emit a local variable declaration.
  2530. ///
  2531. /// This function can be called with a null (unreachable) insert point.
  2532. void EmitVarDecl(const VarDecl &D);
  2533. void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  2534. bool capturedByInit);
  2535. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  2536. llvm::Value *Address);
  2537. /// Determine whether the given initializer is trivial in the sense
  2538. /// that it requires no code to be generated.
  2539. bool isTrivialInitializer(const Expr *Init);
  2540. /// EmitAutoVarDecl - Emit an auto variable declaration.
  2541. ///
  2542. /// This function can be called with a null (unreachable) insert point.
  2543. void EmitAutoVarDecl(const VarDecl &D);
  2544. class AutoVarEmission {
  2545. friend class CodeGenFunction;
  2546. const VarDecl *Variable;
  2547. /// The address of the alloca for languages with explicit address space
  2548. /// (e.g. OpenCL) or alloca casted to generic pointer for address space
  2549. /// agnostic languages (e.g. C++). Invalid if the variable was emitted
  2550. /// as a global constant.
  2551. Address Addr;
  2552. llvm::Value *NRVOFlag;
  2553. /// True if the variable is a __block variable that is captured by an
  2554. /// escaping block.
  2555. bool IsEscapingByRef;
  2556. /// True if the variable is of aggregate type and has a constant
  2557. /// initializer.
  2558. bool IsConstantAggregate;
  2559. /// Non-null if we should use lifetime annotations.
  2560. llvm::Value *SizeForLifetimeMarkers;
  2561. /// Address with original alloca instruction. Invalid if the variable was
  2562. /// emitted as a global constant.
  2563. Address AllocaAddr;
  2564. struct Invalid {};
  2565. AutoVarEmission(Invalid)
  2566. : Variable(nullptr), Addr(Address::invalid()),
  2567. AllocaAddr(Address::invalid()) {}
  2568. AutoVarEmission(const VarDecl &variable)
  2569. : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
  2570. IsEscapingByRef(false), IsConstantAggregate(false),
  2571. SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
  2572. bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
  2573. public:
  2574. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  2575. bool useLifetimeMarkers() const {
  2576. return SizeForLifetimeMarkers != nullptr;
  2577. }
  2578. llvm::Value *getSizeForLifetimeMarkers() const {
  2579. assert(useLifetimeMarkers());
  2580. return SizeForLifetimeMarkers;
  2581. }
  2582. /// Returns the raw, allocated address, which is not necessarily
  2583. /// the address of the object itself. It is casted to default
  2584. /// address space for address space agnostic languages.
  2585. Address getAllocatedAddress() const {
  2586. return Addr;
  2587. }
  2588. /// Returns the address for the original alloca instruction.
  2589. Address getOriginalAllocatedAddress() const { return AllocaAddr; }
  2590. /// Returns the address of the object within this declaration.
  2591. /// Note that this does not chase the forwarding pointer for
  2592. /// __block decls.
  2593. Address getObjectAddress(CodeGenFunction &CGF) const {
  2594. if (!IsEscapingByRef) return Addr;
  2595. return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
  2596. }
  2597. };
  2598. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  2599. void EmitAutoVarInit(const AutoVarEmission &emission);
  2600. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  2601. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  2602. QualType::DestructionKind dtorKind);
  2603. /// Emits the alloca and debug information for the size expressions for each
  2604. /// dimension of an array. It registers the association of its (1-dimensional)
  2605. /// QualTypes and size expression's debug node, so that CGDebugInfo can
  2606. /// reference this node when creating the DISubrange object to describe the
  2607. /// array types.
  2608. void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI,
  2609. const VarDecl &D,
  2610. bool EmitDebugInfo);
  2611. void EmitStaticVarDecl(const VarDecl &D,
  2612. llvm::GlobalValue::LinkageTypes Linkage);
  2613. class ParamValue {
  2614. llvm::Value *Value;
  2615. llvm::Type *ElementType;
  2616. unsigned Alignment;
  2617. ParamValue(llvm::Value *V, llvm::Type *T, unsigned A)
  2618. : Value(V), ElementType(T), Alignment(A) {}
  2619. public:
  2620. static ParamValue forDirect(llvm::Value *value) {
  2621. return ParamValue(value, nullptr, 0);
  2622. }
  2623. static ParamValue forIndirect(Address addr) {
  2624. assert(!addr.getAlignment().isZero());
  2625. return ParamValue(addr.getPointer(), addr.getElementType(),
  2626. addr.getAlignment().getQuantity());
  2627. }
  2628. bool isIndirect() const { return Alignment != 0; }
  2629. llvm::Value *getAnyValue() const { return Value; }
  2630. llvm::Value *getDirectValue() const {
  2631. assert(!isIndirect());
  2632. return Value;
  2633. }
  2634. Address getIndirectAddress() const {
  2635. assert(isIndirect());
  2636. return Address(Value, ElementType, CharUnits::fromQuantity(Alignment));
  2637. }
  2638. };
  2639. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  2640. void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
  2641. /// protectFromPeepholes - Protect a value that we're intending to
  2642. /// store to the side, but which will probably be used later, from
  2643. /// aggressive peepholing optimizations that might delete it.
  2644. ///
  2645. /// Pass the result to unprotectFromPeepholes to declare that
  2646. /// protection is no longer required.
  2647. ///
  2648. /// There's no particular reason why this shouldn't apply to
  2649. /// l-values, it's just that no existing peepholes work on pointers.
  2650. PeepholeProtection protectFromPeepholes(RValue rvalue);
  2651. void unprotectFromPeepholes(PeepholeProtection protection);
  2652. void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
  2653. SourceLocation Loc,
  2654. SourceLocation AssumptionLoc,
  2655. llvm::Value *Alignment,
  2656. llvm::Value *OffsetValue,
  2657. llvm::Value *TheCheck,
  2658. llvm::Instruction *Assumption);
  2659. void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
  2660. SourceLocation Loc, SourceLocation AssumptionLoc,
  2661. llvm::Value *Alignment,
  2662. llvm::Value *OffsetValue = nullptr);
  2663. void emitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
  2664. SourceLocation AssumptionLoc,
  2665. llvm::Value *Alignment,
  2666. llvm::Value *OffsetValue = nullptr);
  2667. //===--------------------------------------------------------------------===//
  2668. // Statement Emission
  2669. //===--------------------------------------------------------------------===//
  2670. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  2671. void EmitStopPoint(const Stmt *S);
  2672. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  2673. /// this function even if there is no current insertion point.
  2674. ///
  2675. /// This function may clear the current insertion point; callers should use
  2676. /// EnsureInsertPoint if they wish to subsequently generate code without first
  2677. /// calling EmitBlock, EmitBranch, or EmitStmt.
  2678. void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None);
  2679. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  2680. /// necessarily require an insertion point or debug information; typically
  2681. /// because the statement amounts to a jump or a container of other
  2682. /// statements.
  2683. ///
  2684. /// \return True if the statement was handled.
  2685. bool EmitSimpleStmt(const Stmt *S, ArrayRef<const Attr *> Attrs);
  2686. Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  2687. AggValueSlot AVS = AggValueSlot::ignored());
  2688. Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  2689. bool GetLast = false,
  2690. AggValueSlot AVS =
  2691. AggValueSlot::ignored());
  2692. /// EmitLabel - Emit the block for the given label. It is legal to call this
  2693. /// function even if there is no current insertion point.
  2694. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  2695. void EmitLabelStmt(const LabelStmt &S);
  2696. void EmitAttributedStmt(const AttributedStmt &S);
  2697. void EmitGotoStmt(const GotoStmt &S);
  2698. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  2699. void EmitIfStmt(const IfStmt &S);
  2700. void EmitWhileStmt(const WhileStmt &S,
  2701. ArrayRef<const Attr *> Attrs = None);
  2702. void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
  2703. void EmitForStmt(const ForStmt &S,
  2704. ArrayRef<const Attr *> Attrs = None);
  2705. void EmitReturnStmt(const ReturnStmt &S);
  2706. void EmitDeclStmt(const DeclStmt &S);
  2707. void EmitBreakStmt(const BreakStmt &S);
  2708. void EmitContinueStmt(const ContinueStmt &S);
  2709. void EmitSwitchStmt(const SwitchStmt &S);
  2710. void EmitDefaultStmt(const DefaultStmt &S, ArrayRef<const Attr *> Attrs);
  2711. void EmitCaseStmt(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
  2712. void EmitCaseStmtRange(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
  2713. void EmitAsmStmt(const AsmStmt &S);
  2714. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  2715. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  2716. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  2717. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  2718. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  2719. void EmitCoroutineBody(const CoroutineBodyStmt &S);
  2720. void EmitCoreturnStmt(const CoreturnStmt &S);
  2721. RValue EmitCoawaitExpr(const CoawaitExpr &E,
  2722. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2723. bool ignoreResult = false);
  2724. LValue EmitCoawaitLValue(const CoawaitExpr *E);
  2725. RValue EmitCoyieldExpr(const CoyieldExpr &E,
  2726. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2727. bool ignoreResult = false);
  2728. LValue EmitCoyieldLValue(const CoyieldExpr *E);
  2729. RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
  2730. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  2731. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  2732. void EmitCXXTryStmt(const CXXTryStmt &S);
  2733. void EmitSEHTryStmt(const SEHTryStmt &S);
  2734. void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
  2735. void EnterSEHTryStmt(const SEHTryStmt &S);
  2736. void ExitSEHTryStmt(const SEHTryStmt &S);
  2737. void VolatilizeTryBlocks(llvm::BasicBlock *BB,
  2738. llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V);
  2739. void pushSEHCleanup(CleanupKind kind,
  2740. llvm::Function *FinallyFunc);
  2741. void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
  2742. const Stmt *OutlinedStmt);
  2743. llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  2744. const SEHExceptStmt &Except);
  2745. llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  2746. const SEHFinallyStmt &Finally);
  2747. void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  2748. llvm::Value *ParentFP,
  2749. llvm::Value *EntryEBP);
  2750. llvm::Value *EmitSEHExceptionCode();
  2751. llvm::Value *EmitSEHExceptionInfo();
  2752. llvm::Value *EmitSEHAbnormalTermination();
  2753. /// Emit simple code for OpenMP directives in Simd-only mode.
  2754. void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D);
  2755. /// Scan the outlined statement for captures from the parent function. For
  2756. /// each capture, mark the capture as escaped and emit a call to
  2757. /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
  2758. void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
  2759. bool IsFilter);
  2760. /// Recovers the address of a local in a parent function. ParentVar is the
  2761. /// address of the variable used in the immediate parent function. It can
  2762. /// either be an alloca or a call to llvm.localrecover if there are nested
  2763. /// outlined functions. ParentFP is the frame pointer of the outermost parent
  2764. /// frame.
  2765. Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  2766. Address ParentVar,
  2767. llvm::Value *ParentFP);
  2768. void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  2769. ArrayRef<const Attr *> Attrs = None);
  2770. /// Controls insertion of cancellation exit blocks in worksharing constructs.
  2771. class OMPCancelStackRAII {
  2772. CodeGenFunction &CGF;
  2773. public:
  2774. OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
  2775. bool HasCancel)
  2776. : CGF(CGF) {
  2777. CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
  2778. }
  2779. ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
  2780. };
  2781. /// Returns calculated size of the specified type.
  2782. llvm::Value *getTypeSize(QualType Ty);
  2783. LValue InitCapturedStruct(const CapturedStmt &S);
  2784. llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
  2785. llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
  2786. Address GenerateCapturedStmtArgument(const CapturedStmt &S);
  2787. llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
  2788. SourceLocation Loc);
  2789. void GenerateOpenMPCapturedVars(const CapturedStmt &S,
  2790. SmallVectorImpl<llvm::Value *> &CapturedVars);
  2791. void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
  2792. SourceLocation Loc);
  2793. /// Perform element by element copying of arrays with type \a
  2794. /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
  2795. /// generated by \a CopyGen.
  2796. ///
  2797. /// \param DestAddr Address of the destination array.
  2798. /// \param SrcAddr Address of the source array.
  2799. /// \param OriginalType Type of destination and source arrays.
  2800. /// \param CopyGen Copying procedure that copies value of single array element
  2801. /// to another single array element.
  2802. void EmitOMPAggregateAssign(
  2803. Address DestAddr, Address SrcAddr, QualType OriginalType,
  2804. const llvm::function_ref<void(Address, Address)> CopyGen);
  2805. /// Emit proper copying of data from one variable to another.
  2806. ///
  2807. /// \param OriginalType Original type of the copied variables.
  2808. /// \param DestAddr Destination address.
  2809. /// \param SrcAddr Source address.
  2810. /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
  2811. /// type of the base array element).
  2812. /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
  2813. /// the base array element).
  2814. /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
  2815. /// DestVD.
  2816. void EmitOMPCopy(QualType OriginalType,
  2817. Address DestAddr, Address SrcAddr,
  2818. const VarDecl *DestVD, const VarDecl *SrcVD,
  2819. const Expr *Copy);
  2820. /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
  2821. /// \a X = \a E \a BO \a E.
  2822. ///
  2823. /// \param X Value to be updated.
  2824. /// \param E Update value.
  2825. /// \param BO Binary operation for update operation.
  2826. /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
  2827. /// expression, false otherwise.
  2828. /// \param AO Atomic ordering of the generated atomic instructions.
  2829. /// \param CommonGen Code generator for complex expressions that cannot be
  2830. /// expressed through atomicrmw instruction.
  2831. /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
  2832. /// generated, <false, RValue::get(nullptr)> otherwise.
  2833. std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
  2834. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  2835. llvm::AtomicOrdering AO, SourceLocation Loc,
  2836. const llvm::function_ref<RValue(RValue)> CommonGen);
  2837. bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  2838. OMPPrivateScope &PrivateScope);
  2839. void EmitOMPPrivateClause(const OMPExecutableDirective &D,
  2840. OMPPrivateScope &PrivateScope);
  2841. void EmitOMPUseDevicePtrClause(
  2842. const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
  2843. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
  2844. void EmitOMPUseDeviceAddrClause(
  2845. const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
  2846. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
  2847. /// Emit code for copyin clause in \a D directive. The next code is
  2848. /// generated at the start of outlined functions for directives:
  2849. /// \code
  2850. /// threadprivate_var1 = master_threadprivate_var1;
  2851. /// operator=(threadprivate_var2, master_threadprivate_var2);
  2852. /// ...
  2853. /// __kmpc_barrier(&loc, global_tid);
  2854. /// \endcode
  2855. ///
  2856. /// \param D OpenMP directive possibly with 'copyin' clause(s).
  2857. /// \returns true if at least one copyin variable is found, false otherwise.
  2858. bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
  2859. /// Emit initial code for lastprivate variables. If some variable is
  2860. /// not also firstprivate, then the default initialization is used. Otherwise
  2861. /// initialization of this variable is performed by EmitOMPFirstprivateClause
  2862. /// method.
  2863. ///
  2864. /// \param D Directive that may have 'lastprivate' directives.
  2865. /// \param PrivateScope Private scope for capturing lastprivate variables for
  2866. /// proper codegen in internal captured statement.
  2867. ///
  2868. /// \returns true if there is at least one lastprivate variable, false
  2869. /// otherwise.
  2870. bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
  2871. OMPPrivateScope &PrivateScope);
  2872. /// Emit final copying of lastprivate values to original variables at
  2873. /// the end of the worksharing or simd directive.
  2874. ///
  2875. /// \param D Directive that has at least one 'lastprivate' directives.
  2876. /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
  2877. /// it is the last iteration of the loop code in associated directive, or to
  2878. /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
  2879. void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
  2880. bool NoFinals,
  2881. llvm::Value *IsLastIterCond = nullptr);
  2882. /// Emit initial code for linear clauses.
  2883. void EmitOMPLinearClause(const OMPLoopDirective &D,
  2884. CodeGenFunction::OMPPrivateScope &PrivateScope);
  2885. /// Emit final code for linear clauses.
  2886. /// \param CondGen Optional conditional code for final part of codegen for
  2887. /// linear clause.
  2888. void EmitOMPLinearClauseFinal(
  2889. const OMPLoopDirective &D,
  2890. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
  2891. /// Emit initial code for reduction variables. Creates reduction copies
  2892. /// and initializes them with the values according to OpenMP standard.
  2893. ///
  2894. /// \param D Directive (possibly) with the 'reduction' clause.
  2895. /// \param PrivateScope Private scope for capturing reduction variables for
  2896. /// proper codegen in internal captured statement.
  2897. ///
  2898. void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
  2899. OMPPrivateScope &PrivateScope,
  2900. bool ForInscan = false);
  2901. /// Emit final update of reduction values to original variables at
  2902. /// the end of the directive.
  2903. ///
  2904. /// \param D Directive that has at least one 'reduction' directives.
  2905. /// \param ReductionKind The kind of reduction to perform.
  2906. void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
  2907. const OpenMPDirectiveKind ReductionKind);
  2908. /// Emit initial code for linear variables. Creates private copies
  2909. /// and initializes them with the values according to OpenMP standard.
  2910. ///
  2911. /// \param D Directive (possibly) with the 'linear' clause.
  2912. /// \return true if at least one linear variable is found that should be
  2913. /// initialized with the value of the original variable, false otherwise.
  2914. bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
  2915. typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
  2916. llvm::Function * /*OutlinedFn*/,
  2917. const OMPTaskDataTy & /*Data*/)>
  2918. TaskGenTy;
  2919. void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
  2920. const OpenMPDirectiveKind CapturedRegion,
  2921. const RegionCodeGenTy &BodyGen,
  2922. const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
  2923. struct OMPTargetDataInfo {
  2924. Address BasePointersArray = Address::invalid();
  2925. Address PointersArray = Address::invalid();
  2926. Address SizesArray = Address::invalid();
  2927. Address MappersArray = Address::invalid();
  2928. unsigned NumberOfTargetItems = 0;
  2929. explicit OMPTargetDataInfo() = default;
  2930. OMPTargetDataInfo(Address BasePointersArray, Address PointersArray,
  2931. Address SizesArray, Address MappersArray,
  2932. unsigned NumberOfTargetItems)
  2933. : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
  2934. SizesArray(SizesArray), MappersArray(MappersArray),
  2935. NumberOfTargetItems(NumberOfTargetItems) {}
  2936. };
  2937. void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S,
  2938. const RegionCodeGenTy &BodyGen,
  2939. OMPTargetDataInfo &InputInfo);
  2940. void EmitOMPMetaDirective(const OMPMetaDirective &S);
  2941. void EmitOMPParallelDirective(const OMPParallelDirective &S);
  2942. void EmitOMPSimdDirective(const OMPSimdDirective &S);
  2943. void EmitOMPTileDirective(const OMPTileDirective &S);
  2944. void EmitOMPUnrollDirective(const OMPUnrollDirective &S);
  2945. void EmitOMPForDirective(const OMPForDirective &S);
  2946. void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
  2947. void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
  2948. void EmitOMPSectionDirective(const OMPSectionDirective &S);
  2949. void EmitOMPSingleDirective(const OMPSingleDirective &S);
  2950. void EmitOMPMasterDirective(const OMPMasterDirective &S);
  2951. void EmitOMPMaskedDirective(const OMPMaskedDirective &S);
  2952. void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
  2953. void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
  2954. void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
  2955. void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
  2956. void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S);
  2957. void EmitOMPTaskDirective(const OMPTaskDirective &S);
  2958. void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
  2959. void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
  2960. void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
  2961. void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
  2962. void EmitOMPFlushDirective(const OMPFlushDirective &S);
  2963. void EmitOMPDepobjDirective(const OMPDepobjDirective &S);
  2964. void EmitOMPScanDirective(const OMPScanDirective &S);
  2965. void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
  2966. void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
  2967. void EmitOMPTargetDirective(const OMPTargetDirective &S);
  2968. void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
  2969. void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
  2970. void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
  2971. void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
  2972. void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
  2973. void
  2974. EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
  2975. void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
  2976. void
  2977. EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
  2978. void EmitOMPCancelDirective(const OMPCancelDirective &S);
  2979. void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
  2980. void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
  2981. void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
  2982. void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S);
  2983. void
  2984. EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S);
  2985. void EmitOMPParallelMasterTaskLoopDirective(
  2986. const OMPParallelMasterTaskLoopDirective &S);
  2987. void EmitOMPParallelMasterTaskLoopSimdDirective(
  2988. const OMPParallelMasterTaskLoopSimdDirective &S);
  2989. void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
  2990. void EmitOMPDistributeParallelForDirective(
  2991. const OMPDistributeParallelForDirective &S);
  2992. void EmitOMPDistributeParallelForSimdDirective(
  2993. const OMPDistributeParallelForSimdDirective &S);
  2994. void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
  2995. void EmitOMPTargetParallelForSimdDirective(
  2996. const OMPTargetParallelForSimdDirective &S);
  2997. void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
  2998. void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
  2999. void
  3000. EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
  3001. void EmitOMPTeamsDistributeParallelForSimdDirective(
  3002. const OMPTeamsDistributeParallelForSimdDirective &S);
  3003. void EmitOMPTeamsDistributeParallelForDirective(
  3004. const OMPTeamsDistributeParallelForDirective &S);
  3005. void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
  3006. void EmitOMPTargetTeamsDistributeDirective(
  3007. const OMPTargetTeamsDistributeDirective &S);
  3008. void EmitOMPTargetTeamsDistributeParallelForDirective(
  3009. const OMPTargetTeamsDistributeParallelForDirective &S);
  3010. void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
  3011. const OMPTargetTeamsDistributeParallelForSimdDirective &S);
  3012. void EmitOMPTargetTeamsDistributeSimdDirective(
  3013. const OMPTargetTeamsDistributeSimdDirective &S);
  3014. void EmitOMPGenericLoopDirective(const OMPGenericLoopDirective &S);
  3015. void EmitOMPInteropDirective(const OMPInteropDirective &S);
  3016. /// Emit device code for the target directive.
  3017. static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
  3018. StringRef ParentName,
  3019. const OMPTargetDirective &S);
  3020. static void
  3021. EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
  3022. const OMPTargetParallelDirective &S);
  3023. /// Emit device code for the target parallel for directive.
  3024. static void EmitOMPTargetParallelForDeviceFunction(
  3025. CodeGenModule &CGM, StringRef ParentName,
  3026. const OMPTargetParallelForDirective &S);
  3027. /// Emit device code for the target parallel for simd directive.
  3028. static void EmitOMPTargetParallelForSimdDeviceFunction(
  3029. CodeGenModule &CGM, StringRef ParentName,
  3030. const OMPTargetParallelForSimdDirective &S);
  3031. /// Emit device code for the target teams directive.
  3032. static void
  3033. EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
  3034. const OMPTargetTeamsDirective &S);
  3035. /// Emit device code for the target teams distribute directive.
  3036. static void EmitOMPTargetTeamsDistributeDeviceFunction(
  3037. CodeGenModule &CGM, StringRef ParentName,
  3038. const OMPTargetTeamsDistributeDirective &S);
  3039. /// Emit device code for the target teams distribute simd directive.
  3040. static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  3041. CodeGenModule &CGM, StringRef ParentName,
  3042. const OMPTargetTeamsDistributeSimdDirective &S);
  3043. /// Emit device code for the target simd directive.
  3044. static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
  3045. StringRef ParentName,
  3046. const OMPTargetSimdDirective &S);
  3047. /// Emit device code for the target teams distribute parallel for simd
  3048. /// directive.
  3049. static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
  3050. CodeGenModule &CGM, StringRef ParentName,
  3051. const OMPTargetTeamsDistributeParallelForSimdDirective &S);
  3052. static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
  3053. CodeGenModule &CGM, StringRef ParentName,
  3054. const OMPTargetTeamsDistributeParallelForDirective &S);
  3055. /// Emit the Stmt \p S and return its topmost canonical loop, if any.
  3056. /// TODO: The \p Depth paramter is not yet implemented and must be 1. In the
  3057. /// future it is meant to be the number of loops expected in the loop nests
  3058. /// (usually specified by the "collapse" clause) that are collapsed to a
  3059. /// single loop by this function.
  3060. llvm::CanonicalLoopInfo *EmitOMPCollapsedCanonicalLoopNest(const Stmt *S,
  3061. int Depth);
  3062. /// Emit an OMPCanonicalLoop using the OpenMPIRBuilder.
  3063. void EmitOMPCanonicalLoop(const OMPCanonicalLoop *S);
  3064. /// Emit inner loop of the worksharing/simd construct.
  3065. ///
  3066. /// \param S Directive, for which the inner loop must be emitted.
  3067. /// \param RequiresCleanup true, if directive has some associated private
  3068. /// variables.
  3069. /// \param LoopCond Bollean condition for loop continuation.
  3070. /// \param IncExpr Increment expression for loop control variable.
  3071. /// \param BodyGen Generator for the inner body of the inner loop.
  3072. /// \param PostIncGen Genrator for post-increment code (required for ordered
  3073. /// loop directvies).
  3074. void EmitOMPInnerLoop(
  3075. const OMPExecutableDirective &S, bool RequiresCleanup,
  3076. const Expr *LoopCond, const Expr *IncExpr,
  3077. const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
  3078. const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
  3079. JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
  3080. /// Emit initial code for loop counters of loop-based directives.
  3081. void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
  3082. OMPPrivateScope &LoopScope);
  3083. /// Helper for the OpenMP loop directives.
  3084. void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
  3085. /// Emit code for the worksharing loop-based directive.
  3086. /// \return true, if this construct has any lastprivate clause, false -
  3087. /// otherwise.
  3088. bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
  3089. const CodeGenLoopBoundsTy &CodeGenLoopBounds,
  3090. const CodeGenDispatchBoundsTy &CGDispatchBounds);
  3091. /// Emit code for the distribute loop-based directive.
  3092. void EmitOMPDistributeLoop(const OMPLoopDirective &S,
  3093. const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
  3094. /// Helpers for the OpenMP loop directives.
  3095. void EmitOMPSimdInit(const OMPLoopDirective &D);
  3096. void EmitOMPSimdFinal(
  3097. const OMPLoopDirective &D,
  3098. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
  3099. /// Emits the lvalue for the expression with possibly captured variable.
  3100. LValue EmitOMPSharedLValue(const Expr *E);
  3101. private:
  3102. /// Helpers for blocks.
  3103. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  3104. /// struct with the values to be passed to the OpenMP loop-related functions
  3105. struct OMPLoopArguments {
  3106. /// loop lower bound
  3107. Address LB = Address::invalid();
  3108. /// loop upper bound
  3109. Address UB = Address::invalid();
  3110. /// loop stride
  3111. Address ST = Address::invalid();
  3112. /// isLastIteration argument for runtime functions
  3113. Address IL = Address::invalid();
  3114. /// Chunk value generated by sema
  3115. llvm::Value *Chunk = nullptr;
  3116. /// EnsureUpperBound
  3117. Expr *EUB = nullptr;
  3118. /// IncrementExpression
  3119. Expr *IncExpr = nullptr;
  3120. /// Loop initialization
  3121. Expr *Init = nullptr;
  3122. /// Loop exit condition
  3123. Expr *Cond = nullptr;
  3124. /// Update of LB after a whole chunk has been executed
  3125. Expr *NextLB = nullptr;
  3126. /// Update of UB after a whole chunk has been executed
  3127. Expr *NextUB = nullptr;
  3128. OMPLoopArguments() = default;
  3129. OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
  3130. llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
  3131. Expr *IncExpr = nullptr, Expr *Init = nullptr,
  3132. Expr *Cond = nullptr, Expr *NextLB = nullptr,
  3133. Expr *NextUB = nullptr)
  3134. : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
  3135. IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
  3136. NextUB(NextUB) {}
  3137. };
  3138. void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
  3139. const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
  3140. const OMPLoopArguments &LoopArgs,
  3141. const CodeGenLoopTy &CodeGenLoop,
  3142. const CodeGenOrderedTy &CodeGenOrdered);
  3143. void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
  3144. bool IsMonotonic, const OMPLoopDirective &S,
  3145. OMPPrivateScope &LoopScope, bool Ordered,
  3146. const OMPLoopArguments &LoopArgs,
  3147. const CodeGenDispatchBoundsTy &CGDispatchBounds);
  3148. void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
  3149. const OMPLoopDirective &S,
  3150. OMPPrivateScope &LoopScope,
  3151. const OMPLoopArguments &LoopArgs,
  3152. const CodeGenLoopTy &CodeGenLoopContent);
  3153. /// Emit code for sections directive.
  3154. void EmitSections(const OMPExecutableDirective &S);
  3155. public:
  3156. //===--------------------------------------------------------------------===//
  3157. // LValue Expression Emission
  3158. //===--------------------------------------------------------------------===//
  3159. /// Create a check that a scalar RValue is non-null.
  3160. llvm::Value *EmitNonNullRValueCheck(RValue RV, QualType T);
  3161. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  3162. RValue GetUndefRValue(QualType Ty);
  3163. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  3164. /// and issue an ErrorUnsupported style diagnostic (using the
  3165. /// provided Name).
  3166. RValue EmitUnsupportedRValue(const Expr *E,
  3167. const char *Name);
  3168. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  3169. /// an ErrorUnsupported style diagnostic (using the provided Name).
  3170. LValue EmitUnsupportedLValue(const Expr *E,
  3171. const char *Name);
  3172. /// EmitLValue - Emit code to compute a designator that specifies the location
  3173. /// of the expression.
  3174. ///
  3175. /// This can return one of two things: a simple address or a bitfield
  3176. /// reference. In either case, the LLVM Value* in the LValue structure is
  3177. /// guaranteed to be an LLVM pointer type.
  3178. ///
  3179. /// If this returns a bitfield reference, nothing about the pointee type of
  3180. /// the LLVM value is known: For example, it may not be a pointer to an
  3181. /// integer.
  3182. ///
  3183. /// If this returns a normal address, and if the lvalue's C type is fixed
  3184. /// size, this method guarantees that the returned pointer type will point to
  3185. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  3186. /// variable length type, this is not possible.
  3187. ///
  3188. LValue EmitLValue(const Expr *E);
  3189. /// Same as EmitLValue but additionally we generate checking code to
  3190. /// guard against undefined behavior. This is only suitable when we know
  3191. /// that the address will be used to access the object.
  3192. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  3193. RValue convertTempToRValue(Address addr, QualType type,
  3194. SourceLocation Loc);
  3195. void EmitAtomicInit(Expr *E, LValue lvalue);
  3196. bool LValueIsSuitableForInlineAtomic(LValue Src);
  3197. RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
  3198. AggValueSlot Slot = AggValueSlot::ignored());
  3199. RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
  3200. llvm::AtomicOrdering AO, bool IsVolatile = false,
  3201. AggValueSlot slot = AggValueSlot::ignored());
  3202. void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
  3203. void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
  3204. bool IsVolatile, bool isInit);
  3205. std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
  3206. LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
  3207. llvm::AtomicOrdering Success =
  3208. llvm::AtomicOrdering::SequentiallyConsistent,
  3209. llvm::AtomicOrdering Failure =
  3210. llvm::AtomicOrdering::SequentiallyConsistent,
  3211. bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
  3212. void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
  3213. const llvm::function_ref<RValue(RValue)> &UpdateOp,
  3214. bool IsVolatile);
  3215. /// EmitToMemory - Change a scalar value from its value
  3216. /// representation to its in-memory representation.
  3217. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  3218. /// EmitFromMemory - Change a scalar value from its memory
  3219. /// representation to its value representation.
  3220. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  3221. /// Check if the scalar \p Value is within the valid range for the given
  3222. /// type \p Ty.
  3223. ///
  3224. /// Returns true if a check is needed (even if the range is unknown).
  3225. bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
  3226. SourceLocation Loc);
  3227. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  3228. /// care to appropriately convert from the memory representation to
  3229. /// the LLVM value representation.
  3230. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  3231. SourceLocation Loc,
  3232. AlignmentSource Source = AlignmentSource::Type,
  3233. bool isNontemporal = false) {
  3234. return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
  3235. CGM.getTBAAAccessInfo(Ty), isNontemporal);
  3236. }
  3237. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  3238. SourceLocation Loc, LValueBaseInfo BaseInfo,
  3239. TBAAAccessInfo TBAAInfo,
  3240. bool isNontemporal = false);
  3241. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  3242. /// care to appropriately convert from the memory representation to
  3243. /// the LLVM value representation. The l-value must be a simple
  3244. /// l-value.
  3245. llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
  3246. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  3247. /// care to appropriately convert from the memory representation to
  3248. /// the LLVM value representation.
  3249. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  3250. bool Volatile, QualType Ty,
  3251. AlignmentSource Source = AlignmentSource::Type,
  3252. bool isInit = false, bool isNontemporal = false) {
  3253. EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
  3254. CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
  3255. }
  3256. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  3257. bool Volatile, QualType Ty,
  3258. LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
  3259. bool isInit = false, bool isNontemporal = false);
  3260. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  3261. /// care to appropriately convert from the memory representation to
  3262. /// the LLVM value representation. The l-value must be a simple
  3263. /// l-value. The isInit flag indicates whether this is an initialization.
  3264. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  3265. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  3266. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  3267. /// this method emits the address of the lvalue, then loads the result as an
  3268. /// rvalue, returning the rvalue.
  3269. RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
  3270. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  3271. RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
  3272. RValue EmitLoadOfGlobalRegLValue(LValue LV);
  3273. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  3274. /// lvalue, where both are guaranteed to the have the same type, and that type
  3275. /// is 'Ty'.
  3276. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
  3277. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  3278. void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
  3279. /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
  3280. /// as EmitStoreThroughLValue.
  3281. ///
  3282. /// \param Result [out] - If non-null, this will be set to a Value* for the
  3283. /// bit-field contents after the store, appropriate for use as the result of
  3284. /// an assignment to the bit-field.
  3285. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  3286. llvm::Value **Result=nullptr);
  3287. /// Emit an l-value for an assignment (simple or compound) of complex type.
  3288. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  3289. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  3290. LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  3291. llvm::Value *&Result);
  3292. // Note: only available for agg return types
  3293. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  3294. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  3295. // Note: only available for agg return types
  3296. LValue EmitCallExprLValue(const CallExpr *E);
  3297. // Note: only available for agg return types
  3298. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  3299. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  3300. LValue EmitStringLiteralLValue(const StringLiteral *E);
  3301. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  3302. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  3303. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  3304. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  3305. bool Accessed = false);
  3306. LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E);
  3307. LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  3308. bool IsLowerBound = true);
  3309. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  3310. LValue EmitMemberExpr(const MemberExpr *E);
  3311. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  3312. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  3313. LValue EmitInitListLValue(const InitListExpr *E);
  3314. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  3315. LValue EmitCastLValue(const CastExpr *E);
  3316. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  3317. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  3318. Address EmitExtVectorElementLValue(LValue V);
  3319. RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
  3320. Address EmitArrayToPointerDecay(const Expr *Array,
  3321. LValueBaseInfo *BaseInfo = nullptr,
  3322. TBAAAccessInfo *TBAAInfo = nullptr);
  3323. class ConstantEmission {
  3324. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  3325. ConstantEmission(llvm::Constant *C, bool isReference)
  3326. : ValueAndIsReference(C, isReference) {}
  3327. public:
  3328. ConstantEmission() {}
  3329. static ConstantEmission forReference(llvm::Constant *C) {
  3330. return ConstantEmission(C, true);
  3331. }
  3332. static ConstantEmission forValue(llvm::Constant *C) {
  3333. return ConstantEmission(C, false);
  3334. }
  3335. explicit operator bool() const {
  3336. return ValueAndIsReference.getOpaqueValue() != nullptr;
  3337. }
  3338. bool isReference() const { return ValueAndIsReference.getInt(); }
  3339. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  3340. assert(isReference());
  3341. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  3342. refExpr->getType());
  3343. }
  3344. llvm::Constant *getValue() const {
  3345. assert(!isReference());
  3346. return ValueAndIsReference.getPointer();
  3347. }
  3348. };
  3349. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  3350. ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
  3351. llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
  3352. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  3353. AggValueSlot slot = AggValueSlot::ignored());
  3354. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  3355. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  3356. const ObjCIvarDecl *Ivar);
  3357. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  3358. LValue EmitLValueForLambdaField(const FieldDecl *Field);
  3359. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  3360. /// if the Field is a reference, this will return the address of the reference
  3361. /// and not the address of the value stored in the reference.
  3362. LValue EmitLValueForFieldInitialization(LValue Base,
  3363. const FieldDecl* Field);
  3364. LValue EmitLValueForIvar(QualType ObjectTy,
  3365. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  3366. unsigned CVRQualifiers);
  3367. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  3368. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  3369. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  3370. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  3371. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  3372. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  3373. LValue EmitStmtExprLValue(const StmtExpr *E);
  3374. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  3375. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  3376. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
  3377. //===--------------------------------------------------------------------===//
  3378. // Scalar Expression Emission
  3379. //===--------------------------------------------------------------------===//
  3380. /// EmitCall - Generate a call of the given function, expecting the given
  3381. /// result type, and using the given argument list which specifies both the
  3382. /// LLVM arguments and the types they were derived from.
  3383. RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
  3384. ReturnValueSlot ReturnValue, const CallArgList &Args,
  3385. llvm::CallBase **callOrInvoke, bool IsMustTail,
  3386. SourceLocation Loc);
  3387. RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
  3388. ReturnValueSlot ReturnValue, const CallArgList &Args,
  3389. llvm::CallBase **callOrInvoke = nullptr,
  3390. bool IsMustTail = false) {
  3391. return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
  3392. IsMustTail, SourceLocation());
  3393. }
  3394. RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
  3395. ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
  3396. RValue EmitCallExpr(const CallExpr *E,
  3397. ReturnValueSlot ReturnValue = ReturnValueSlot());
  3398. RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  3399. CGCallee EmitCallee(const Expr *E);
  3400. void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
  3401. void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl);
  3402. llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
  3403. const Twine &name = "");
  3404. llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
  3405. ArrayRef<llvm::Value *> args,
  3406. const Twine &name = "");
  3407. llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3408. const Twine &name = "");
  3409. llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3410. ArrayRef<llvm::Value *> args,
  3411. const Twine &name = "");
  3412. SmallVector<llvm::OperandBundleDef, 1>
  3413. getBundlesForFunclet(llvm::Value *Callee);
  3414. llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee,
  3415. ArrayRef<llvm::Value *> Args,
  3416. const Twine &Name = "");
  3417. llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3418. ArrayRef<llvm::Value *> args,
  3419. const Twine &name = "");
  3420. llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3421. const Twine &name = "");
  3422. void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3423. ArrayRef<llvm::Value *> args);
  3424. CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  3425. NestedNameSpecifier *Qual,
  3426. llvm::Type *Ty);
  3427. CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  3428. CXXDtorType Type,
  3429. const CXXRecordDecl *RD);
  3430. // Return the copy constructor name with the prefix "__copy_constructor_"
  3431. // removed.
  3432. static std::string getNonTrivialCopyConstructorStr(QualType QT,
  3433. CharUnits Alignment,
  3434. bool IsVolatile,
  3435. ASTContext &Ctx);
  3436. // Return the destructor name with the prefix "__destructor_" removed.
  3437. static std::string getNonTrivialDestructorStr(QualType QT,
  3438. CharUnits Alignment,
  3439. bool IsVolatile,
  3440. ASTContext &Ctx);
  3441. // These functions emit calls to the special functions of non-trivial C
  3442. // structs.
  3443. void defaultInitNonTrivialCStructVar(LValue Dst);
  3444. void callCStructDefaultConstructor(LValue Dst);
  3445. void callCStructDestructor(LValue Dst);
  3446. void callCStructCopyConstructor(LValue Dst, LValue Src);
  3447. void callCStructMoveConstructor(LValue Dst, LValue Src);
  3448. void callCStructCopyAssignmentOperator(LValue Dst, LValue Src);
  3449. void callCStructMoveAssignmentOperator(LValue Dst, LValue Src);
  3450. RValue
  3451. EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
  3452. const CGCallee &Callee,
  3453. ReturnValueSlot ReturnValue, llvm::Value *This,
  3454. llvm::Value *ImplicitParam,
  3455. QualType ImplicitParamTy, const CallExpr *E,
  3456. CallArgList *RtlArgs);
  3457. RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee,
  3458. llvm::Value *This, QualType ThisTy,
  3459. llvm::Value *ImplicitParam,
  3460. QualType ImplicitParamTy, const CallExpr *E);
  3461. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  3462. ReturnValueSlot ReturnValue);
  3463. RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
  3464. const CXXMethodDecl *MD,
  3465. ReturnValueSlot ReturnValue,
  3466. bool HasQualifier,
  3467. NestedNameSpecifier *Qualifier,
  3468. bool IsArrow, const Expr *Base);
  3469. // Compute the object pointer.
  3470. Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
  3471. llvm::Value *memberPtr,
  3472. const MemberPointerType *memberPtrType,
  3473. LValueBaseInfo *BaseInfo = nullptr,
  3474. TBAAAccessInfo *TBAAInfo = nullptr);
  3475. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  3476. ReturnValueSlot ReturnValue);
  3477. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  3478. const CXXMethodDecl *MD,
  3479. ReturnValueSlot ReturnValue);
  3480. RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
  3481. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  3482. ReturnValueSlot ReturnValue);
  3483. RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E);
  3484. RValue EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E);
  3485. RValue EmitOpenMPDevicePrintfCallExpr(const CallExpr *E);
  3486. RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
  3487. const CallExpr *E, ReturnValueSlot ReturnValue);
  3488. RValue emitRotate(const CallExpr *E, bool IsRotateRight);
  3489. /// Emit IR for __builtin_os_log_format.
  3490. RValue emitBuiltinOSLogFormat(const CallExpr &E);
  3491. /// Emit IR for __builtin_is_aligned.
  3492. RValue EmitBuiltinIsAligned(const CallExpr *E);
  3493. /// Emit IR for __builtin_align_up/__builtin_align_down.
  3494. RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp);
  3495. llvm::Function *generateBuiltinOSLogHelperFunction(
  3496. const analyze_os_log::OSLogBufferLayout &Layout,
  3497. CharUnits BufferAlignment);
  3498. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  3499. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  3500. /// is unhandled by the current target.
  3501. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3502. ReturnValueSlot ReturnValue);
  3503. llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
  3504. const llvm::CmpInst::Predicate Fp,
  3505. const llvm::CmpInst::Predicate Ip,
  3506. const llvm::Twine &Name = "");
  3507. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3508. ReturnValueSlot ReturnValue,
  3509. llvm::Triple::ArchType Arch);
  3510. llvm::Value *EmitARMMVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3511. ReturnValueSlot ReturnValue,
  3512. llvm::Triple::ArchType Arch);
  3513. llvm::Value *EmitARMCDEBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3514. ReturnValueSlot ReturnValue,
  3515. llvm::Triple::ArchType Arch);
  3516. llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy,
  3517. QualType RTy);
  3518. llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::ArrayType *ATy,
  3519. QualType RTy);
  3520. llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
  3521. unsigned LLVMIntrinsic,
  3522. unsigned AltLLVMIntrinsic,
  3523. const char *NameHint,
  3524. unsigned Modifier,
  3525. const CallExpr *E,
  3526. SmallVectorImpl<llvm::Value *> &Ops,
  3527. Address PtrOp0, Address PtrOp1,
  3528. llvm::Triple::ArchType Arch);
  3529. llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
  3530. unsigned Modifier, llvm::Type *ArgTy,
  3531. const CallExpr *E);
  3532. llvm::Value *EmitNeonCall(llvm::Function *F,
  3533. SmallVectorImpl<llvm::Value*> &O,
  3534. const char *name,
  3535. unsigned shift = 0, bool rightshift = false);
  3536. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx,
  3537. const llvm::ElementCount &Count);
  3538. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  3539. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  3540. bool negateForRightShift);
  3541. llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
  3542. llvm::Type *Ty, bool usgn, const char *name);
  3543. llvm::Value *vectorWrapScalar16(llvm::Value *Op);
  3544. /// SVEBuiltinMemEltTy - Returns the memory element type for this memory
  3545. /// access builtin. Only required if it can't be inferred from the base
  3546. /// pointer operand.
  3547. llvm::Type *SVEBuiltinMemEltTy(const SVETypeFlags &TypeFlags);
  3548. SmallVector<llvm::Type *, 2>
  3549. getSVEOverloadTypes(const SVETypeFlags &TypeFlags, llvm::Type *ReturnType,
  3550. ArrayRef<llvm::Value *> Ops);
  3551. llvm::Type *getEltType(const SVETypeFlags &TypeFlags);
  3552. llvm::ScalableVectorType *getSVEType(const SVETypeFlags &TypeFlags);
  3553. llvm::ScalableVectorType *getSVEPredType(const SVETypeFlags &TypeFlags);
  3554. llvm::Value *EmitSVEAllTruePred(const SVETypeFlags &TypeFlags);
  3555. llvm::Value *EmitSVEDupX(llvm::Value *Scalar);
  3556. llvm::Value *EmitSVEDupX(llvm::Value *Scalar, llvm::Type *Ty);
  3557. llvm::Value *EmitSVEReinterpret(llvm::Value *Val, llvm::Type *Ty);
  3558. llvm::Value *EmitSVEPMull(const SVETypeFlags &TypeFlags,
  3559. llvm::SmallVectorImpl<llvm::Value *> &Ops,
  3560. unsigned BuiltinID);
  3561. llvm::Value *EmitSVEMovl(const SVETypeFlags &TypeFlags,
  3562. llvm::ArrayRef<llvm::Value *> Ops,
  3563. unsigned BuiltinID);
  3564. llvm::Value *EmitSVEPredicateCast(llvm::Value *Pred,
  3565. llvm::ScalableVectorType *VTy);
  3566. llvm::Value *EmitSVEGatherLoad(const SVETypeFlags &TypeFlags,
  3567. llvm::SmallVectorImpl<llvm::Value *> &Ops,
  3568. unsigned IntID);
  3569. llvm::Value *EmitSVEScatterStore(const SVETypeFlags &TypeFlags,
  3570. llvm::SmallVectorImpl<llvm::Value *> &Ops,
  3571. unsigned IntID);
  3572. llvm::Value *EmitSVEMaskedLoad(const CallExpr *, llvm::Type *ReturnTy,
  3573. SmallVectorImpl<llvm::Value *> &Ops,
  3574. unsigned BuiltinID, bool IsZExtReturn);
  3575. llvm::Value *EmitSVEMaskedStore(const CallExpr *,
  3576. SmallVectorImpl<llvm::Value *> &Ops,
  3577. unsigned BuiltinID);
  3578. llvm::Value *EmitSVEPrefetchLoad(const SVETypeFlags &TypeFlags,
  3579. SmallVectorImpl<llvm::Value *> &Ops,
  3580. unsigned BuiltinID);
  3581. llvm::Value *EmitSVEGatherPrefetch(const SVETypeFlags &TypeFlags,
  3582. SmallVectorImpl<llvm::Value *> &Ops,
  3583. unsigned IntID);
  3584. llvm::Value *EmitSVEStructLoad(const SVETypeFlags &TypeFlags,
  3585. SmallVectorImpl<llvm::Value *> &Ops,
  3586. unsigned IntID);
  3587. llvm::Value *EmitSVEStructStore(const SVETypeFlags &TypeFlags,
  3588. SmallVectorImpl<llvm::Value *> &Ops,
  3589. unsigned IntID);
  3590. llvm::Value *EmitAArch64SVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3591. llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3592. llvm::Triple::ArchType Arch);
  3593. llvm::Value *EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3594. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  3595. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3596. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3597. llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3598. llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3599. llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3600. llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
  3601. const CallExpr *E);
  3602. llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3603. llvm::Value *EmitRISCVBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3604. ReturnValueSlot ReturnValue);
  3605. bool ProcessOrderScopeAMDGCN(llvm::Value *Order, llvm::Value *Scope,
  3606. llvm::AtomicOrdering &AO,
  3607. llvm::SyncScope::ID &SSID);
  3608. enum class MSVCIntrin;
  3609. llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
  3610. llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version);
  3611. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  3612. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  3613. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  3614. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  3615. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  3616. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  3617. const ObjCMethodDecl *MethodWithObjects);
  3618. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  3619. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  3620. ReturnValueSlot Return = ReturnValueSlot());
  3621. /// Retrieves the default cleanup kind for an ARC cleanup.
  3622. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  3623. CleanupKind getARCCleanupKind() {
  3624. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  3625. ? NormalAndEHCleanup : NormalCleanup;
  3626. }
  3627. // ARC primitives.
  3628. void EmitARCInitWeak(Address addr, llvm::Value *value);
  3629. void EmitARCDestroyWeak(Address addr);
  3630. llvm::Value *EmitARCLoadWeak(Address addr);
  3631. llvm::Value *EmitARCLoadWeakRetained(Address addr);
  3632. llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
  3633. void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
  3634. void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
  3635. void EmitARCCopyWeak(Address dst, Address src);
  3636. void EmitARCMoveWeak(Address dst, Address src);
  3637. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  3638. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  3639. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  3640. bool resultIgnored);
  3641. llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
  3642. bool resultIgnored);
  3643. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  3644. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  3645. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  3646. void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
  3647. void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  3648. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  3649. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  3650. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  3651. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  3652. llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
  3653. llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType);
  3654. llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value,
  3655. llvm::Type *returnType);
  3656. void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  3657. std::pair<LValue,llvm::Value*>
  3658. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  3659. std::pair<LValue,llvm::Value*>
  3660. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  3661. std::pair<LValue,llvm::Value*>
  3662. EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
  3663. llvm::Value *EmitObjCAlloc(llvm::Value *value,
  3664. llvm::Type *returnType);
  3665. llvm::Value *EmitObjCAllocWithZone(llvm::Value *value,
  3666. llvm::Type *returnType);
  3667. llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType);
  3668. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  3669. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  3670. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  3671. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  3672. llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
  3673. bool allowUnsafeClaim);
  3674. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  3675. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  3676. llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
  3677. void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
  3678. void EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values);
  3679. static Destroyer destroyARCStrongImprecise;
  3680. static Destroyer destroyARCStrongPrecise;
  3681. static Destroyer destroyARCWeak;
  3682. static Destroyer emitARCIntrinsicUse;
  3683. static Destroyer destroyNonTrivialCStruct;
  3684. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  3685. llvm::Value *EmitObjCAutoreleasePoolPush();
  3686. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  3687. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  3688. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  3689. /// Emits a reference binding to the passed in expression.
  3690. RValue EmitReferenceBindingToExpr(const Expr *E);
  3691. //===--------------------------------------------------------------------===//
  3692. // Expression Emission
  3693. //===--------------------------------------------------------------------===//
  3694. // Expressions are broken into three classes: scalar, complex, aggregate.
  3695. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  3696. /// scalar type, returning the result.
  3697. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  3698. /// Emit a conversion from the specified type to the specified destination
  3699. /// type, both of which are LLVM scalar types.
  3700. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  3701. QualType DstTy, SourceLocation Loc);
  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. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  3705. QualType DstTy,
  3706. SourceLocation Loc);
  3707. /// EmitAggExpr - Emit the computation of the specified expression
  3708. /// of aggregate type. The result is computed into the given slot,
  3709. /// which may be null to indicate that the value is not needed.
  3710. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  3711. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  3712. /// aggregate type into a temporary LValue.
  3713. LValue EmitAggExprToLValue(const Expr *E);
  3714. /// Build all the stores needed to initialize an aggregate at Dest with the
  3715. /// value Val.
  3716. void EmitAggregateStore(llvm::Value *Val, Address Dest, bool DestIsVolatile);
  3717. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  3718. /// make sure it survives garbage collection until this point.
  3719. void EmitExtendGCLifetime(llvm::Value *object);
  3720. /// EmitComplexExpr - Emit the computation of the specified expression of
  3721. /// complex type, returning the result.
  3722. ComplexPairTy EmitComplexExpr(const Expr *E,
  3723. bool IgnoreReal = false,
  3724. bool IgnoreImag = false);
  3725. /// EmitComplexExprIntoLValue - Emit the given expression of complex
  3726. /// type and place its result into the specified l-value.
  3727. void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
  3728. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  3729. void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
  3730. /// EmitLoadOfComplex - Load a complex number from the specified l-value.
  3731. ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
  3732. Address emitAddrOfRealComponent(Address complex, QualType complexType);
  3733. Address emitAddrOfImagComponent(Address complex, QualType complexType);
  3734. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  3735. /// global variable that has already been created for it. If the initializer
  3736. /// has a different type than GV does, this may free GV and return a different
  3737. /// one. Otherwise it just returns GV.
  3738. llvm::GlobalVariable *
  3739. AddInitializerToStaticVarDecl(const VarDecl &D,
  3740. llvm::GlobalVariable *GV);
  3741. // Emit an @llvm.invariant.start call for the given memory region.
  3742. void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size);
  3743. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  3744. /// variable with global storage.
  3745. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV,
  3746. bool PerformInit);
  3747. llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor,
  3748. llvm::Constant *Addr);
  3749. llvm::Function *createTLSAtExitStub(const VarDecl &VD,
  3750. llvm::FunctionCallee Dtor,
  3751. llvm::Constant *Addr,
  3752. llvm::FunctionCallee &AtExit);
  3753. /// Call atexit() with a function that passes the given argument to
  3754. /// the given function.
  3755. void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn,
  3756. llvm::Constant *addr);
  3757. /// Call atexit() with function dtorStub.
  3758. void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
  3759. /// Call unatexit() with function dtorStub.
  3760. llvm::Value *unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub);
  3761. /// Emit code in this function to perform a guarded variable
  3762. /// initialization. Guarded initializations are used when it's not
  3763. /// possible to prove that an initialization will be done exactly
  3764. /// once, e.g. with a static local variable or a static data member
  3765. /// of a class template.
  3766. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  3767. bool PerformInit);
  3768. enum class GuardKind { VariableGuard, TlsGuard };
  3769. /// Emit a branch to select whether or not to perform guarded initialization.
  3770. void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
  3771. llvm::BasicBlock *InitBlock,
  3772. llvm::BasicBlock *NoInitBlock,
  3773. GuardKind Kind, const VarDecl *D);
  3774. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  3775. /// variables.
  3776. void
  3777. GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  3778. ArrayRef<llvm::Function *> CXXThreadLocals,
  3779. ConstantAddress Guard = ConstantAddress::invalid());
  3780. /// GenerateCXXGlobalCleanUpFunc - Generates code for cleaning up global
  3781. /// variables.
  3782. void GenerateCXXGlobalCleanUpFunc(
  3783. llvm::Function *Fn,
  3784. ArrayRef<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
  3785. llvm::Constant *>>
  3786. DtorsOrStermFinalizers);
  3787. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  3788. const VarDecl *D,
  3789. llvm::GlobalVariable *Addr,
  3790. bool PerformInit);
  3791. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  3792. void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
  3793. void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
  3794. RValue EmitAtomicExpr(AtomicExpr *E);
  3795. //===--------------------------------------------------------------------===//
  3796. // Annotations Emission
  3797. //===--------------------------------------------------------------------===//
  3798. /// Emit an annotation call (intrinsic).
  3799. llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn,
  3800. llvm::Value *AnnotatedVal,
  3801. StringRef AnnotationStr,
  3802. SourceLocation Location,
  3803. const AnnotateAttr *Attr);
  3804. /// Emit local annotations for the local variable V, declared by D.
  3805. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  3806. /// Emit field annotations for the given field & value. Returns the
  3807. /// annotation result.
  3808. Address EmitFieldAnnotations(const FieldDecl *D, Address V);
  3809. //===--------------------------------------------------------------------===//
  3810. // Internal Helpers
  3811. //===--------------------------------------------------------------------===//
  3812. /// ContainsLabel - Return true if the statement contains a label in it. If
  3813. /// this statement is not executed normally, it not containing a label means
  3814. /// that we can just remove the code.
  3815. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  3816. /// containsBreak - Return true if the statement contains a break out of it.
  3817. /// If the statement (recursively) contains a switch or loop with a break
  3818. /// inside of it, this is fine.
  3819. static bool containsBreak(const Stmt *S);
  3820. /// Determine if the given statement might introduce a declaration into the
  3821. /// current scope, by being a (possibly-labelled) DeclStmt.
  3822. static bool mightAddDeclToScope(const Stmt *S);
  3823. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  3824. /// to a constant, or if it does but contains a label, return false. If it
  3825. /// constant folds return true and set the boolean result in Result.
  3826. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
  3827. bool AllowLabels = false);
  3828. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  3829. /// to a constant, or if it does but contains a label, return false. If it
  3830. /// constant folds return true and set the folded value.
  3831. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
  3832. bool AllowLabels = false);
  3833. /// isInstrumentedCondition - Determine whether the given condition is an
  3834. /// instrumentable condition (i.e. no "&&" or "||").
  3835. static bool isInstrumentedCondition(const Expr *C);
  3836. /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
  3837. /// increments a profile counter based on the semantics of the given logical
  3838. /// operator opcode. This is used to instrument branch condition coverage
  3839. /// for logical operators.
  3840. void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp,
  3841. llvm::BasicBlock *TrueBlock,
  3842. llvm::BasicBlock *FalseBlock,
  3843. uint64_t TrueCount = 0,
  3844. Stmt::Likelihood LH = Stmt::LH_None,
  3845. const Expr *CntrIdx = nullptr);
  3846. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  3847. /// if statement) to the specified blocks. Based on the condition, this might
  3848. /// try to simplify the codegen of the conditional based on the branch.
  3849. /// TrueCount should be the number of times we expect the condition to
  3850. /// evaluate to true based on PGO data.
  3851. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  3852. llvm::BasicBlock *FalseBlock, uint64_t TrueCount,
  3853. Stmt::Likelihood LH = Stmt::LH_None);
  3854. /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
  3855. /// nonnull, if \p LHS is marked _Nonnull.
  3856. void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
  3857. /// An enumeration which makes it easier to specify whether or not an
  3858. /// operation is a subtraction.
  3859. enum { NotSubtraction = false, IsSubtraction = true };
  3860. /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
  3861. /// detect undefined behavior when the pointer overflow sanitizer is enabled.
  3862. /// \p SignedIndices indicates whether any of the GEP indices are signed.
  3863. /// \p IsSubtraction indicates whether the expression used to form the GEP
  3864. /// is a subtraction.
  3865. llvm::Value *EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr,
  3866. ArrayRef<llvm::Value *> IdxList,
  3867. bool SignedIndices,
  3868. bool IsSubtraction,
  3869. SourceLocation Loc,
  3870. const Twine &Name = "");
  3871. /// Specifies which type of sanitizer check to apply when handling a
  3872. /// particular builtin.
  3873. enum BuiltinCheckKind {
  3874. BCK_CTZPassedZero,
  3875. BCK_CLZPassedZero,
  3876. };
  3877. /// Emits an argument for a call to a builtin. If the builtin sanitizer is
  3878. /// enabled, a runtime check specified by \p Kind is also emitted.
  3879. llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
  3880. /// Emit a description of a type in a format suitable for passing to
  3881. /// a runtime sanitizer handler.
  3882. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  3883. /// Convert a value into a format suitable for passing to a runtime
  3884. /// sanitizer handler.
  3885. llvm::Value *EmitCheckValue(llvm::Value *V);
  3886. /// Emit a description of a source location in a format suitable for
  3887. /// passing to a runtime sanitizer handler.
  3888. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  3889. /// Create a basic block that will either trap or call a handler function in
  3890. /// the UBSan runtime with the provided arguments, and create a conditional
  3891. /// branch to it.
  3892. void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  3893. SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
  3894. ArrayRef<llvm::Value *> DynamicArgs);
  3895. /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
  3896. /// if Cond if false.
  3897. void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
  3898. llvm::ConstantInt *TypeId, llvm::Value *Ptr,
  3899. ArrayRef<llvm::Constant *> StaticArgs);
  3900. /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime
  3901. /// checking is enabled. Otherwise, just emit an unreachable instruction.
  3902. void EmitUnreachable(SourceLocation Loc);
  3903. /// Create a basic block that will call the trap intrinsic, and emit a
  3904. /// conditional branch to it, for the -ftrapv checks.
  3905. void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID);
  3906. /// Emit a call to trap or debugtrap and attach function attribute
  3907. /// "trap-func-name" if specified.
  3908. llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
  3909. /// Emit a stub for the cross-DSO CFI check function.
  3910. void EmitCfiCheckStub();
  3911. /// Emit a cross-DSO CFI failure handling function.
  3912. void EmitCfiCheckFail();
  3913. /// Create a check for a function parameter that may potentially be
  3914. /// declared as non-null.
  3915. void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
  3916. AbstractCallee AC, unsigned ParmNum);
  3917. /// EmitCallArg - Emit a single call argument.
  3918. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  3919. /// EmitDelegateCallArg - We are performing a delegate call; that
  3920. /// is, the current function is delegating to another one. Produce
  3921. /// a r-value suitable for passing the given parameter.
  3922. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
  3923. SourceLocation loc);
  3924. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  3925. /// point operation, expressed as the maximum relative error in ulp.
  3926. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  3927. /// Set the codegen fast-math flags.
  3928. void SetFastMathFlags(FPOptions FPFeatures);
  3929. private:
  3930. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  3931. void EmitReturnOfRValue(RValue RV, QualType Ty);
  3932. void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
  3933. llvm::SmallVector<std::pair<llvm::WeakTrackingVH, llvm::Value *>, 4>
  3934. DeferredReplacements;
  3935. /// Set the address of a local variable.
  3936. void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
  3937. assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
  3938. LocalDeclMap.insert({VD, Addr});
  3939. }
  3940. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  3941. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  3942. ///
  3943. /// \param AI - The first function argument of the expansion.
  3944. void ExpandTypeFromArgs(QualType Ty, LValue Dst,
  3945. llvm::Function::arg_iterator &AI);
  3946. /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg
  3947. /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
  3948. /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
  3949. void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
  3950. SmallVectorImpl<llvm::Value *> &IRCallArgs,
  3951. unsigned &IRCallArgPos);
  3952. std::pair<llvm::Value *, llvm::Type *>
  3953. EmitAsmInput(const TargetInfo::ConstraintInfo &Info, const Expr *InputExpr,
  3954. std::string &ConstraintStr);
  3955. std::pair<llvm::Value *, llvm::Type *>
  3956. EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, LValue InputValue,
  3957. QualType InputType, std::string &ConstraintStr,
  3958. SourceLocation Loc);
  3959. /// Attempts to statically evaluate the object size of E. If that
  3960. /// fails, emits code to figure the size of E out for us. This is
  3961. /// pass_object_size aware.
  3962. ///
  3963. /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
  3964. llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
  3965. llvm::IntegerType *ResType,
  3966. llvm::Value *EmittedE,
  3967. bool IsDynamic);
  3968. /// Emits the size of E, as required by __builtin_object_size. This
  3969. /// function is aware of pass_object_size parameters, and will act accordingly
  3970. /// if E is a parameter with the pass_object_size attribute.
  3971. llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
  3972. llvm::IntegerType *ResType,
  3973. llvm::Value *EmittedE,
  3974. bool IsDynamic);
  3975. void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D,
  3976. Address Loc);
  3977. public:
  3978. enum class EvaluationOrder {
  3979. ///! No language constraints on evaluation order.
  3980. Default,
  3981. ///! Language semantics require left-to-right evaluation.
  3982. ForceLeftToRight,
  3983. ///! Language semantics require right-to-left evaluation.
  3984. ForceRightToLeft
  3985. };
  3986. // Wrapper for function prototype sources. Wraps either a FunctionProtoType or
  3987. // an ObjCMethodDecl.
  3988. struct PrototypeWrapper {
  3989. llvm::PointerUnion<const FunctionProtoType *, const ObjCMethodDecl *> P;
  3990. PrototypeWrapper(const FunctionProtoType *FT) : P(FT) {}
  3991. PrototypeWrapper(const ObjCMethodDecl *MD) : P(MD) {}
  3992. };
  3993. void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype,
  3994. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  3995. AbstractCallee AC = AbstractCallee(),
  3996. unsigned ParamsToSkip = 0,
  3997. EvaluationOrder Order = EvaluationOrder::Default);
  3998. /// EmitPointerWithAlignment - Given an expression with a pointer type,
  3999. /// emit the value and compute our best estimate of the alignment of the
  4000. /// pointee.
  4001. ///
  4002. /// \param BaseInfo - If non-null, this will be initialized with
  4003. /// information about the source of the alignment and the may-alias
  4004. /// attribute. Note that this function will conservatively fall back on
  4005. /// the type when it doesn't recognize the expression and may-alias will
  4006. /// be set to false.
  4007. ///
  4008. /// One reasonable way to use this information is when there's a language
  4009. /// guarantee that the pointer must be aligned to some stricter value, and
  4010. /// we're simply trying to ensure that sufficiently obvious uses of under-
  4011. /// aligned objects don't get miscompiled; for example, a placement new
  4012. /// into the address of a local variable. In such a case, it's quite
  4013. /// reasonable to just ignore the returned alignment when it isn't from an
  4014. /// explicit source.
  4015. Address EmitPointerWithAlignment(const Expr *Addr,
  4016. LValueBaseInfo *BaseInfo = nullptr,
  4017. TBAAAccessInfo *TBAAInfo = nullptr);
  4018. /// If \p E references a parameter with pass_object_size info or a constant
  4019. /// array size modifier, emit the object size divided by the size of \p EltTy.
  4020. /// Otherwise return null.
  4021. llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
  4022. void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
  4023. struct MultiVersionResolverOption {
  4024. llvm::Function *Function;
  4025. struct Conds {
  4026. StringRef Architecture;
  4027. llvm::SmallVector<StringRef, 8> Features;
  4028. Conds(StringRef Arch, ArrayRef<StringRef> Feats)
  4029. : Architecture(Arch), Features(Feats.begin(), Feats.end()) {}
  4030. } Conditions;
  4031. MultiVersionResolverOption(llvm::Function *F, StringRef Arch,
  4032. ArrayRef<StringRef> Feats)
  4033. : Function(F), Conditions(Arch, Feats) {}
  4034. };
  4035. // Emits the body of a multiversion function's resolver. Assumes that the
  4036. // options are already sorted in the proper order, with the 'default' option
  4037. // last (if it exists).
  4038. void EmitMultiVersionResolver(llvm::Function *Resolver,
  4039. ArrayRef<MultiVersionResolverOption> Options);
  4040. private:
  4041. QualType getVarArgType(const Expr *Arg);
  4042. void EmitDeclMetadata();
  4043. BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
  4044. const AutoVarEmission &emission);
  4045. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  4046. llvm::Value *GetValueForARMHint(unsigned BuiltinID);
  4047. llvm::Value *EmitX86CpuIs(const CallExpr *E);
  4048. llvm::Value *EmitX86CpuIs(StringRef CPUStr);
  4049. llvm::Value *EmitX86CpuSupports(const CallExpr *E);
  4050. llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
  4051. llvm::Value *EmitX86CpuSupports(uint64_t Mask);
  4052. llvm::Value *EmitX86CpuInit();
  4053. llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO);
  4054. };
  4055. /// TargetFeatures - This class is used to check whether the builtin function
  4056. /// has the required tagert specific features. It is able to support the
  4057. /// combination of ','(and), '|'(or), and '()'. By default, the priority of
  4058. /// ',' is higher than that of '|' .
  4059. /// E.g:
  4060. /// A,B|C means the builtin function requires both A and B, or C.
  4061. /// If we want the builtin function requires both A and B, or both A and C,
  4062. /// there are two ways: A,B|A,C or A,(B|C).
  4063. /// The FeaturesList should not contain spaces, and brackets must appear in
  4064. /// pairs.
  4065. class TargetFeatures {
  4066. struct FeatureListStatus {
  4067. bool HasFeatures;
  4068. StringRef CurFeaturesList;
  4069. };
  4070. const llvm::StringMap<bool> &CallerFeatureMap;
  4071. FeatureListStatus getAndFeatures(StringRef FeatureList) {
  4072. int InParentheses = 0;
  4073. bool HasFeatures = true;
  4074. size_t SubexpressionStart = 0;
  4075. for (size_t i = 0, e = FeatureList.size(); i < e; ++i) {
  4076. char CurrentToken = FeatureList[i];
  4077. switch (CurrentToken) {
  4078. default:
  4079. break;
  4080. case '(':
  4081. if (InParentheses == 0)
  4082. SubexpressionStart = i + 1;
  4083. ++InParentheses;
  4084. break;
  4085. case ')':
  4086. --InParentheses;
  4087. assert(InParentheses >= 0 && "Parentheses are not in pair");
  4088. LLVM_FALLTHROUGH;
  4089. case '|':
  4090. case ',':
  4091. if (InParentheses == 0) {
  4092. if (HasFeatures && i != SubexpressionStart) {
  4093. StringRef F = FeatureList.slice(SubexpressionStart, i);
  4094. HasFeatures = CurrentToken == ')' ? hasRequiredFeatures(F)
  4095. : CallerFeatureMap.lookup(F);
  4096. }
  4097. SubexpressionStart = i + 1;
  4098. if (CurrentToken == '|') {
  4099. return {HasFeatures, FeatureList.substr(SubexpressionStart)};
  4100. }
  4101. }
  4102. break;
  4103. }
  4104. }
  4105. assert(InParentheses == 0 && "Parentheses are not in pair");
  4106. if (HasFeatures && SubexpressionStart != FeatureList.size())
  4107. HasFeatures =
  4108. CallerFeatureMap.lookup(FeatureList.substr(SubexpressionStart));
  4109. return {HasFeatures, StringRef()};
  4110. }
  4111. public:
  4112. bool hasRequiredFeatures(StringRef FeatureList) {
  4113. FeatureListStatus FS = {false, FeatureList};
  4114. while (!FS.HasFeatures && !FS.CurFeaturesList.empty())
  4115. FS = getAndFeatures(FS.CurFeaturesList);
  4116. return FS.HasFeatures;
  4117. }
  4118. TargetFeatures(const llvm::StringMap<bool> &CallerFeatureMap)
  4119. : CallerFeatureMap(CallerFeatureMap) {}
  4120. };
  4121. inline DominatingLLVMValue::saved_type
  4122. DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) {
  4123. if (!needsSaving(value)) return saved_type(value, false);
  4124. // Otherwise, we need an alloca.
  4125. auto align = CharUnits::fromQuantity(
  4126. CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
  4127. Address alloca =
  4128. CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
  4129. CGF.Builder.CreateStore(value, alloca);
  4130. return saved_type(alloca.getPointer(), true);
  4131. }
  4132. inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF,
  4133. saved_type value) {
  4134. // If the value says it wasn't saved, trust that it's still dominating.
  4135. if (!value.getInt()) return value.getPointer();
  4136. // Otherwise, it should be an alloca instruction, as set up in save().
  4137. auto alloca = cast<llvm::AllocaInst>(value.getPointer());
  4138. return CGF.Builder.CreateAlignedLoad(alloca->getAllocatedType(), alloca,
  4139. alloca->getAlign());
  4140. }
  4141. } // end namespace CodeGen
  4142. // Map the LangOption for floating point exception behavior into
  4143. // the corresponding enum in the IR.
  4144. llvm::fp::ExceptionBehavior
  4145. ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind);
  4146. } // end namespace clang
  4147. #endif