CodeGenFunction.h 186 KB

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