CodeGenFunction.h 187 KB

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