CodeGenFunction.h 157 KB

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