CodeGenModule.cpp 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  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 coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGBlocks.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCall.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGObjCRuntime.h"
  20. #include "CGOpenCLRuntime.h"
  21. #include "CGOpenMPRuntime.h"
  22. #include "CGOpenMPRuntimeNVPTX.h"
  23. #include "CodeGenFunction.h"
  24. #include "CodeGenPGO.h"
  25. #include "ConstantEmitter.h"
  26. #include "CoverageMappingGen.h"
  27. #include "TargetInfo.h"
  28. #include "clang/AST/ASTContext.h"
  29. #include "clang/AST/CharUnits.h"
  30. #include "clang/AST/DeclCXX.h"
  31. #include "clang/AST/DeclObjC.h"
  32. #include "clang/AST/DeclTemplate.h"
  33. #include "clang/AST/Mangle.h"
  34. #include "clang/AST/RecordLayout.h"
  35. #include "clang/AST/RecursiveASTVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/Diagnostic.h"
  39. #include "clang/Basic/Module.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/TargetInfo.h"
  42. #include "clang/Basic/Version.h"
  43. #include "clang/CodeGen/ConstantInitBuilder.h"
  44. #include "clang/Frontend/CodeGenOptions.h"
  45. #include "clang/Sema/SemaDiagnostic.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include "llvm/Analysis/TargetLibraryInfo.h"
  48. #include "llvm/IR/CallSite.h"
  49. #include "llvm/IR/CallingConv.h"
  50. #include "llvm/IR/DataLayout.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/Module.h"
  54. #include "llvm/ProfileData/InstrProfReader.h"
  55. #include "llvm/Support/ConvertUTF.h"
  56. #include "llvm/Support/ErrorHandling.h"
  57. #include "llvm/Support/MD5.h"
  58. using namespace clang;
  59. using namespace CodeGen;
  60. static llvm::cl::opt<bool> LimitedCoverage(
  61. "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
  62. llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
  63. llvm::cl::init(false));
  64. static const char AnnotationSection[] = "llvm.metadata";
  65. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  66. switch (CGM.getTarget().getCXXABI().getKind()) {
  67. case TargetCXXABI::GenericAArch64:
  68. case TargetCXXABI::GenericARM:
  69. case TargetCXXABI::iOS:
  70. case TargetCXXABI::iOS64:
  71. case TargetCXXABI::WatchOS:
  72. case TargetCXXABI::GenericMIPS:
  73. case TargetCXXABI::GenericItanium:
  74. case TargetCXXABI::WebAssembly:
  75. return CreateItaniumCXXABI(CGM);
  76. case TargetCXXABI::Microsoft:
  77. return CreateMicrosoftCXXABI(CGM);
  78. }
  79. llvm_unreachable("invalid C++ ABI kind");
  80. }
  81. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  82. const PreprocessorOptions &PPO,
  83. const CodeGenOptions &CGO, llvm::Module &M,
  84. DiagnosticsEngine &diags,
  85. CoverageSourceInfo *CoverageInfo)
  86. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  87. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  88. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  89. VMContext(M.getContext()), Types(*this), VTables(*this),
  90. SanitizerMD(new SanitizerMetadata(*this)) {
  91. // Initialize the type cache.
  92. llvm::LLVMContext &LLVMContext = M.getContext();
  93. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  94. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  95. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  96. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  97. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  98. HalfTy = llvm::Type::getHalfTy(LLVMContext);
  99. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  100. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  101. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  102. PointerAlignInBytes =
  103. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  104. SizeSizeInBytes =
  105. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  106. IntAlignInBytes =
  107. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  108. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  109. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  110. C.getTargetInfo().getMaxPointerWidth());
  111. Int8PtrTy = Int8Ty->getPointerTo(0);
  112. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  113. AllocaInt8PtrTy = Int8Ty->getPointerTo(
  114. M.getDataLayout().getAllocaAddrSpace());
  115. ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
  116. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  117. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  118. if (LangOpts.ObjC1)
  119. createObjCRuntime();
  120. if (LangOpts.OpenCL)
  121. createOpenCLRuntime();
  122. if (LangOpts.OpenMP)
  123. createOpenMPRuntime();
  124. if (LangOpts.CUDA)
  125. createCUDARuntime();
  126. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  127. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  128. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  129. TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
  130. getCXXABI().getMangleContext()));
  131. // If debug info or coverage generation is enabled, create the CGDebugInfo
  132. // object.
  133. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  134. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  135. DebugInfo.reset(new CGDebugInfo(*this));
  136. Block.GlobalUniqueCount = 0;
  137. if (C.getLangOpts().ObjC1)
  138. ObjCData.reset(new ObjCEntrypoints());
  139. if (CodeGenOpts.hasProfileClangUse()) {
  140. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  141. CodeGenOpts.ProfileInstrumentUsePath);
  142. if (auto E = ReaderOrErr.takeError()) {
  143. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  144. "Could not read profile %0: %1");
  145. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  146. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  147. << EI.message();
  148. });
  149. } else
  150. PGOReader = std::move(ReaderOrErr.get());
  151. }
  152. // If coverage mapping generation is enabled, create the
  153. // CoverageMappingModuleGen object.
  154. if (CodeGenOpts.CoverageMapping)
  155. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  156. }
  157. CodeGenModule::~CodeGenModule() {}
  158. void CodeGenModule::createObjCRuntime() {
  159. // This is just isGNUFamily(), but we want to force implementors of
  160. // new ABIs to decide how best to do this.
  161. switch (LangOpts.ObjCRuntime.getKind()) {
  162. case ObjCRuntime::GNUstep:
  163. case ObjCRuntime::GCC:
  164. case ObjCRuntime::ObjFW:
  165. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  166. return;
  167. case ObjCRuntime::FragileMacOSX:
  168. case ObjCRuntime::MacOSX:
  169. case ObjCRuntime::iOS:
  170. case ObjCRuntime::WatchOS:
  171. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  172. return;
  173. }
  174. llvm_unreachable("bad runtime kind");
  175. }
  176. void CodeGenModule::createOpenCLRuntime() {
  177. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  178. }
  179. void CodeGenModule::createOpenMPRuntime() {
  180. // Select a specialized code generation class based on the target, if any.
  181. // If it does not exist use the default implementation.
  182. switch (getTriple().getArch()) {
  183. case llvm::Triple::nvptx:
  184. case llvm::Triple::nvptx64:
  185. assert(getLangOpts().OpenMPIsDevice &&
  186. "OpenMP NVPTX is only prepared to deal with device code.");
  187. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  188. break;
  189. default:
  190. if (LangOpts.OpenMPSimd)
  191. OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
  192. else
  193. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  194. break;
  195. }
  196. }
  197. void CodeGenModule::createCUDARuntime() {
  198. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  199. }
  200. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  201. Replacements[Name] = C;
  202. }
  203. void CodeGenModule::applyReplacements() {
  204. for (auto &I : Replacements) {
  205. StringRef MangledName = I.first();
  206. llvm::Constant *Replacement = I.second;
  207. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  208. if (!Entry)
  209. continue;
  210. auto *OldF = cast<llvm::Function>(Entry);
  211. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  212. if (!NewF) {
  213. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  214. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  215. } else {
  216. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  217. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  218. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  219. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  220. }
  221. }
  222. // Replace old with new, but keep the old order.
  223. OldF->replaceAllUsesWith(Replacement);
  224. if (NewF) {
  225. NewF->removeFromParent();
  226. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  227. NewF);
  228. }
  229. OldF->eraseFromParent();
  230. }
  231. }
  232. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  233. GlobalValReplacements.push_back(std::make_pair(GV, C));
  234. }
  235. void CodeGenModule::applyGlobalValReplacements() {
  236. for (auto &I : GlobalValReplacements) {
  237. llvm::GlobalValue *GV = I.first;
  238. llvm::Constant *C = I.second;
  239. GV->replaceAllUsesWith(C);
  240. GV->eraseFromParent();
  241. }
  242. }
  243. // This is only used in aliases that we created and we know they have a
  244. // linear structure.
  245. static const llvm::GlobalObject *getAliasedGlobal(
  246. const llvm::GlobalIndirectSymbol &GIS) {
  247. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  248. const llvm::Constant *C = &GIS;
  249. for (;;) {
  250. C = C->stripPointerCasts();
  251. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  252. return GO;
  253. // stripPointerCasts will not walk over weak aliases.
  254. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  255. if (!GIS2)
  256. return nullptr;
  257. if (!Visited.insert(GIS2).second)
  258. return nullptr;
  259. C = GIS2->getIndirectSymbol();
  260. }
  261. }
  262. void CodeGenModule::checkAliases() {
  263. // Check if the constructed aliases are well formed. It is really unfortunate
  264. // that we have to do this in CodeGen, but we only construct mangled names
  265. // and aliases during codegen.
  266. bool Error = false;
  267. DiagnosticsEngine &Diags = getDiags();
  268. for (const GlobalDecl &GD : Aliases) {
  269. const auto *D = cast<ValueDecl>(GD.getDecl());
  270. SourceLocation Location;
  271. bool IsIFunc = D->hasAttr<IFuncAttr>();
  272. if (const Attr *A = D->getDefiningAttr())
  273. Location = A->getLocation();
  274. else
  275. llvm_unreachable("Not an alias or ifunc?");
  276. StringRef MangledName = getMangledName(GD);
  277. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  278. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  279. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  280. if (!GV) {
  281. Error = true;
  282. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  283. } else if (GV->isDeclaration()) {
  284. Error = true;
  285. Diags.Report(Location, diag::err_alias_to_undefined)
  286. << IsIFunc << IsIFunc;
  287. } else if (IsIFunc) {
  288. // Check resolver function type.
  289. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  290. GV->getType()->getPointerElementType());
  291. assert(FTy);
  292. if (!FTy->getReturnType()->isPointerTy())
  293. Diags.Report(Location, diag::err_ifunc_resolver_return);
  294. if (FTy->getNumParams())
  295. Diags.Report(Location, diag::err_ifunc_resolver_params);
  296. }
  297. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  298. llvm::GlobalValue *AliaseeGV;
  299. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  300. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  301. else
  302. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  303. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  304. StringRef AliasSection = SA->getName();
  305. if (AliasSection != AliaseeGV->getSection())
  306. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  307. << AliasSection << IsIFunc << IsIFunc;
  308. }
  309. // We have to handle alias to weak aliases in here. LLVM itself disallows
  310. // this since the object semantics would not match the IL one. For
  311. // compatibility with gcc we implement it by just pointing the alias
  312. // to its aliasee's aliasee. We also warn, since the user is probably
  313. // expecting the link to be weak.
  314. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  315. if (GA->isInterposable()) {
  316. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  317. << GV->getName() << GA->getName() << IsIFunc;
  318. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  319. GA->getIndirectSymbol(), Alias->getType());
  320. Alias->setIndirectSymbol(Aliasee);
  321. }
  322. }
  323. }
  324. if (!Error)
  325. return;
  326. for (const GlobalDecl &GD : Aliases) {
  327. StringRef MangledName = getMangledName(GD);
  328. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  329. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  330. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  331. Alias->eraseFromParent();
  332. }
  333. }
  334. void CodeGenModule::clear() {
  335. DeferredDeclsToEmit.clear();
  336. if (OpenMPRuntime)
  337. OpenMPRuntime->clear();
  338. }
  339. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  340. StringRef MainFile) {
  341. if (!hasDiagnostics())
  342. return;
  343. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  344. if (MainFile.empty())
  345. MainFile = "<stdin>";
  346. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  347. } else {
  348. if (Mismatched > 0)
  349. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
  350. if (Missing > 0)
  351. Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
  352. }
  353. }
  354. void CodeGenModule::Release() {
  355. EmitDeferred();
  356. EmitVTablesOpportunistically();
  357. applyGlobalValReplacements();
  358. applyReplacements();
  359. checkAliases();
  360. emitMultiVersionFunctions();
  361. EmitCXXGlobalInitFunc();
  362. EmitCXXGlobalDtorFunc();
  363. EmitCXXThreadLocalInitFunc();
  364. if (ObjCRuntime)
  365. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  366. AddGlobalCtor(ObjCInitFunction);
  367. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  368. CUDARuntime) {
  369. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  370. AddGlobalCtor(CudaCtorFunction);
  371. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  372. AddGlobalDtor(CudaDtorFunction);
  373. }
  374. if (OpenMPRuntime)
  375. if (llvm::Function *OpenMPRegistrationFunction =
  376. OpenMPRuntime->emitRegistrationFunction()) {
  377. auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
  378. OpenMPRegistrationFunction : nullptr;
  379. AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
  380. }
  381. if (PGOReader) {
  382. getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
  383. if (PGOStats.hasDiagnostics())
  384. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  385. }
  386. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  387. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  388. EmitGlobalAnnotations();
  389. EmitStaticExternCAliases();
  390. EmitDeferredUnusedCoverageMappings();
  391. if (CoverageMapping)
  392. CoverageMapping->emit();
  393. if (CodeGenOpts.SanitizeCfiCrossDso) {
  394. CodeGenFunction(*this).EmitCfiCheckFail();
  395. CodeGenFunction(*this).EmitCfiCheckStub();
  396. }
  397. emitAtAvailableLinkGuard();
  398. emitLLVMUsed();
  399. if (SanStats)
  400. SanStats->finish();
  401. if (CodeGenOpts.Autolink &&
  402. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  403. EmitModuleLinkOptions();
  404. }
  405. // Record mregparm value now so it is visible through rest of codegen.
  406. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  407. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  408. CodeGenOpts.NumRegisterParameters);
  409. if (CodeGenOpts.DwarfVersion) {
  410. // We actually want the latest version when there are conflicts.
  411. // We can change from Warning to Latest if such mode is supported.
  412. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  413. CodeGenOpts.DwarfVersion);
  414. }
  415. if (CodeGenOpts.EmitCodeView) {
  416. // Indicate that we want CodeView in the metadata.
  417. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  418. }
  419. if (CodeGenOpts.ControlFlowGuard) {
  420. // We want function ID tables for Control Flow Guard.
  421. getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
  422. }
  423. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  424. // We don't support LTO with 2 with different StrictVTablePointers
  425. // FIXME: we could support it by stripping all the information introduced
  426. // by StrictVTablePointers.
  427. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  428. llvm::Metadata *Ops[2] = {
  429. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  430. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  431. llvm::Type::getInt32Ty(VMContext), 1))};
  432. getModule().addModuleFlag(llvm::Module::Require,
  433. "StrictVTablePointersRequirement",
  434. llvm::MDNode::get(VMContext, Ops));
  435. }
  436. if (DebugInfo)
  437. // We support a single version in the linked module. The LLVM
  438. // parser will drop debug info with a different version number
  439. // (and warn about it, too).
  440. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  441. llvm::DEBUG_METADATA_VERSION);
  442. // We need to record the widths of enums and wchar_t, so that we can generate
  443. // the correct build attributes in the ARM backend. wchar_size is also used by
  444. // TargetLibraryInfo.
  445. uint64_t WCharWidth =
  446. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  447. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  448. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  449. if ( Arch == llvm::Triple::arm
  450. || Arch == llvm::Triple::armeb
  451. || Arch == llvm::Triple::thumb
  452. || Arch == llvm::Triple::thumbeb) {
  453. // The minimum width of an enum in bytes
  454. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  455. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  456. }
  457. if (CodeGenOpts.SanitizeCfiCrossDso) {
  458. // Indicate that we want cross-DSO control flow integrity checks.
  459. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  460. }
  461. if (CodeGenOpts.CFProtectionReturn &&
  462. Target.checkCFProtectionReturnSupported(getDiags())) {
  463. // Indicate that we want to instrument return control flow protection.
  464. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
  465. 1);
  466. }
  467. if (CodeGenOpts.CFProtectionBranch &&
  468. Target.checkCFProtectionBranchSupported(getDiags())) {
  469. // Indicate that we want to instrument branch control flow protection.
  470. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
  471. 1);
  472. }
  473. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  474. // Indicate whether __nvvm_reflect should be configured to flush denormal
  475. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  476. // property.)
  477. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  478. LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
  479. }
  480. // Emit OpenCL specific module metadata: OpenCL/SPIR version.
  481. if (LangOpts.OpenCL) {
  482. EmitOpenCLMetadata();
  483. // Emit SPIR version.
  484. if (getTriple().getArch() == llvm::Triple::spir ||
  485. getTriple().getArch() == llvm::Triple::spir64) {
  486. // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
  487. // opencl.spir.version named metadata.
  488. llvm::Metadata *SPIRVerElts[] = {
  489. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  490. Int32Ty, LangOpts.OpenCLVersion / 100)),
  491. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  492. Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
  493. llvm::NamedMDNode *SPIRVerMD =
  494. TheModule.getOrInsertNamedMetadata("opencl.spir.version");
  495. llvm::LLVMContext &Ctx = TheModule.getContext();
  496. SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
  497. }
  498. }
  499. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  500. assert(PLevel < 3 && "Invalid PIC Level");
  501. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  502. if (Context.getLangOpts().PIE)
  503. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  504. }
  505. SimplifyPersonality();
  506. if (getCodeGenOpts().EmitDeclMetadata)
  507. EmitDeclMetadata();
  508. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  509. EmitCoverageFile();
  510. if (DebugInfo)
  511. DebugInfo->finalize();
  512. EmitVersionIdentMetadata();
  513. EmitTargetMetadata();
  514. }
  515. void CodeGenModule::EmitOpenCLMetadata() {
  516. // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
  517. // opencl.ocl.version named metadata node.
  518. llvm::Metadata *OCLVerElts[] = {
  519. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  520. Int32Ty, LangOpts.OpenCLVersion / 100)),
  521. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  522. Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
  523. llvm::NamedMDNode *OCLVerMD =
  524. TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
  525. llvm::LLVMContext &Ctx = TheModule.getContext();
  526. OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
  527. }
  528. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  529. // Make sure that this type is translated.
  530. Types.UpdateCompletedType(TD);
  531. }
  532. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  533. // Make sure that this type is translated.
  534. Types.RefreshTypeCacheForClass(RD);
  535. }
  536. llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
  537. if (!TBAA)
  538. return nullptr;
  539. return TBAA->getTypeInfo(QTy);
  540. }
  541. TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
  542. // Pointee values may have incomplete types, but they shall never be
  543. // dereferenced.
  544. if (AccessType->isIncompleteType())
  545. return TBAAAccessInfo::getIncompleteInfo();
  546. uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity();
  547. return TBAAAccessInfo(getTBAATypeInfo(AccessType), Size);
  548. }
  549. TBAAAccessInfo
  550. CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
  551. if (!TBAA)
  552. return TBAAAccessInfo();
  553. return TBAA->getVTablePtrAccessInfo(VTablePtrType);
  554. }
  555. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  556. if (!TBAA)
  557. return nullptr;
  558. return TBAA->getTBAAStructInfo(QTy);
  559. }
  560. llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
  561. if (!TBAA)
  562. return nullptr;
  563. return TBAA->getBaseTypeInfo(QTy);
  564. }
  565. llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
  566. if (!TBAA)
  567. return nullptr;
  568. return TBAA->getAccessTagInfo(Info);
  569. }
  570. TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  571. TBAAAccessInfo TargetInfo) {
  572. if (!TBAA)
  573. return TBAAAccessInfo();
  574. return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
  575. }
  576. TBAAAccessInfo
  577. CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  578. TBAAAccessInfo InfoB) {
  579. if (!TBAA)
  580. return TBAAAccessInfo();
  581. return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
  582. }
  583. TBAAAccessInfo
  584. CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  585. TBAAAccessInfo SrcInfo) {
  586. if (!TBAA)
  587. return TBAAAccessInfo();
  588. return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
  589. }
  590. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  591. TBAAAccessInfo TBAAInfo) {
  592. if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
  593. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
  594. }
  595. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  596. llvm::Instruction *I, const CXXRecordDecl *RD) {
  597. I->setMetadata(llvm::LLVMContext::MD_invariant_group,
  598. llvm::MDNode::get(getLLVMContext(), {}));
  599. }
  600. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  601. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  602. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  603. }
  604. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  605. /// specified stmt yet.
  606. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  607. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  608. "cannot compile this %0 yet");
  609. std::string Msg = Type;
  610. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  611. << Msg << S->getSourceRange();
  612. }
  613. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  614. /// specified decl yet.
  615. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  616. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  617. "cannot compile this %0 yet");
  618. std::string Msg = Type;
  619. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  620. }
  621. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  622. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  623. }
  624. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  625. const NamedDecl *D) const {
  626. if (GV->hasDLLImportStorageClass())
  627. return;
  628. // Internal definitions always have default visibility.
  629. if (GV->hasLocalLinkage()) {
  630. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  631. return;
  632. }
  633. // Set visibility for definitions.
  634. LinkageInfo LV = D->getLinkageAndVisibility();
  635. if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
  636. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  637. }
  638. static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
  639. llvm::GlobalValue *GV, const NamedDecl *D) {
  640. const llvm::Triple &TT = CGM.getTriple();
  641. // Only handle ELF for now.
  642. if (!TT.isOSBinFormatELF())
  643. return false;
  644. // If this is not an executable, don't assume anything is local.
  645. const auto &CGOpts = CGM.getCodeGenOpts();
  646. llvm::Reloc::Model RM = CGOpts.RelocationModel;
  647. const auto &LOpts = CGM.getLangOpts();
  648. if (RM != llvm::Reloc::Static && !LOpts.PIE)
  649. return false;
  650. // A definition cannot be preempted from an executable.
  651. if (!GV->isDeclarationForLinker())
  652. return true;
  653. // Most PIC code sequences that assume that a symbol is local cannot produce a
  654. // 0 if it turns out the symbol is undefined. While this is ABI and relocation
  655. // depended, it seems worth it to handle it here.
  656. if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
  657. return false;
  658. // PPC has no copy relocations and cannot use a plt entry as a symbol address.
  659. llvm::Triple::ArchType Arch = TT.getArch();
  660. if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  661. Arch == llvm::Triple::ppc64le)
  662. return false;
  663. // If we can use copy relocations we can assume it is local.
  664. if (isa<VarDecl>(D) &&
  665. (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
  666. return true;
  667. // If we can use a plt entry as the symbol address we can assume it
  668. // is local.
  669. // FIXME: This should work for PIE, but the gold linker doesn't support it.
  670. if (isa<FunctionDecl>(D) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
  671. return true;
  672. // Otherwise don't assue it is local.
  673. return false;
  674. }
  675. void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV,
  676. const NamedDecl *D) const {
  677. if (shouldAssumeDSOLocal(*this, GV, D))
  678. GV->setDSOLocal(true);
  679. }
  680. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  681. const NamedDecl *D) const {
  682. setGlobalVisibility(GV, D);
  683. setDSOLocal(GV, D);
  684. }
  685. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  686. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  687. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  688. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  689. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  690. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  691. }
  692. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  693. CodeGenOptions::TLSModel M) {
  694. switch (M) {
  695. case CodeGenOptions::GeneralDynamicTLSModel:
  696. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  697. case CodeGenOptions::LocalDynamicTLSModel:
  698. return llvm::GlobalVariable::LocalDynamicTLSModel;
  699. case CodeGenOptions::InitialExecTLSModel:
  700. return llvm::GlobalVariable::InitialExecTLSModel;
  701. case CodeGenOptions::LocalExecTLSModel:
  702. return llvm::GlobalVariable::LocalExecTLSModel;
  703. }
  704. llvm_unreachable("Invalid TLS model!");
  705. }
  706. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  707. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  708. llvm::GlobalValue::ThreadLocalMode TLM;
  709. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  710. // Override the TLS model if it is explicitly specified.
  711. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  712. TLM = GetLLVMTLSModel(Attr->getModel());
  713. }
  714. GV->setThreadLocalMode(TLM);
  715. }
  716. static void AppendTargetMangling(const CodeGenModule &CGM,
  717. const TargetAttr *Attr, raw_ostream &Out) {
  718. if (Attr->isDefaultVersion())
  719. return;
  720. Out << '.';
  721. const auto &Target = CGM.getTarget();
  722. TargetAttr::ParsedTargetAttr Info =
  723. Attr->parse([&Target](StringRef LHS, StringRef RHS) {
  724. // Multiversioning doesn't allow "no-${feature}", so we can
  725. // only have "+" prefixes here.
  726. assert(LHS.startswith("+") && RHS.startswith("+") &&
  727. "Features should always have a prefix.");
  728. return Target.multiVersionSortPriority(LHS.substr(1)) >
  729. Target.multiVersionSortPriority(RHS.substr(1));
  730. });
  731. bool IsFirst = true;
  732. if (!Info.Architecture.empty()) {
  733. IsFirst = false;
  734. Out << "arch_" << Info.Architecture;
  735. }
  736. for (StringRef Feat : Info.Features) {
  737. if (!IsFirst)
  738. Out << '_';
  739. IsFirst = false;
  740. Out << Feat.substr(1);
  741. }
  742. }
  743. static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
  744. const NamedDecl *ND,
  745. bool OmitTargetMangling = false) {
  746. SmallString<256> Buffer;
  747. llvm::raw_svector_ostream Out(Buffer);
  748. MangleContext &MC = CGM.getCXXABI().getMangleContext();
  749. if (MC.shouldMangleDeclName(ND)) {
  750. llvm::raw_svector_ostream Out(Buffer);
  751. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  752. MC.mangleCXXCtor(D, GD.getCtorType(), Out);
  753. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  754. MC.mangleCXXDtor(D, GD.getDtorType(), Out);
  755. else
  756. MC.mangleName(ND, Out);
  757. } else {
  758. IdentifierInfo *II = ND->getIdentifier();
  759. assert(II && "Attempt to mangle unnamed decl.");
  760. const auto *FD = dyn_cast<FunctionDecl>(ND);
  761. if (FD &&
  762. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  763. llvm::raw_svector_ostream Out(Buffer);
  764. Out << "__regcall3__" << II->getName();
  765. } else {
  766. Out << II->getName();
  767. }
  768. }
  769. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  770. if (FD->isMultiVersion() && !OmitTargetMangling)
  771. AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
  772. return Out.str();
  773. }
  774. void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
  775. const FunctionDecl *FD) {
  776. if (!FD->isMultiVersion())
  777. return;
  778. // Get the name of what this would be without the 'target' attribute. This
  779. // allows us to lookup the version that was emitted when this wasn't a
  780. // multiversion function.
  781. std::string NonTargetName =
  782. getMangledNameImpl(*this, GD, FD, /*OmitTargetMangling=*/true);
  783. GlobalDecl OtherGD;
  784. if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
  785. assert(OtherGD.getCanonicalDecl()
  786. .getDecl()
  787. ->getAsFunction()
  788. ->isMultiVersion() &&
  789. "Other GD should now be a multiversioned function");
  790. // OtherFD is the version of this function that was mangled BEFORE
  791. // becoming a MultiVersion function. It potentially needs to be updated.
  792. const FunctionDecl *OtherFD =
  793. OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
  794. std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
  795. // This is so that if the initial version was already the 'default'
  796. // version, we don't try to update it.
  797. if (OtherName != NonTargetName) {
  798. // Remove instead of erase, since others may have stored the StringRef
  799. // to this.
  800. const auto ExistingRecord = Manglings.find(NonTargetName);
  801. if (ExistingRecord != std::end(Manglings))
  802. Manglings.remove(&(*ExistingRecord));
  803. auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
  804. MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
  805. if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
  806. Entry->setName(OtherName);
  807. }
  808. }
  809. }
  810. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  811. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  812. // Some ABIs don't have constructor variants. Make sure that base and
  813. // complete constructors get mangled the same.
  814. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  815. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  816. CXXCtorType OrigCtorType = GD.getCtorType();
  817. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  818. if (OrigCtorType == Ctor_Base)
  819. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  820. }
  821. }
  822. auto FoundName = MangledDeclNames.find(CanonicalGD);
  823. if (FoundName != MangledDeclNames.end())
  824. return FoundName->second;
  825. // Keep the first result in the case of a mangling collision.
  826. const auto *ND = cast<NamedDecl>(GD.getDecl());
  827. auto Result =
  828. Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
  829. return MangledDeclNames[CanonicalGD] = Result.first->first();
  830. }
  831. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  832. const BlockDecl *BD) {
  833. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  834. const Decl *D = GD.getDecl();
  835. SmallString<256> Buffer;
  836. llvm::raw_svector_ostream Out(Buffer);
  837. if (!D)
  838. MangleCtx.mangleGlobalBlock(BD,
  839. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  840. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  841. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  842. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  843. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  844. else
  845. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  846. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  847. return Result.first->first();
  848. }
  849. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  850. return getModule().getNamedValue(Name);
  851. }
  852. /// AddGlobalCtor - Add a function to the list that will be called before
  853. /// main() runs.
  854. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  855. llvm::Constant *AssociatedData) {
  856. // FIXME: Type coercion of void()* types.
  857. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  858. }
  859. /// AddGlobalDtor - Add a function to the list that will be called
  860. /// when the module is unloaded.
  861. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  862. // FIXME: Type coercion of void()* types.
  863. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  864. }
  865. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  866. if (Fns.empty()) return;
  867. // Ctor function type is void()*.
  868. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  869. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  870. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  871. llvm::StructType *CtorStructTy = llvm::StructType::get(
  872. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
  873. // Construct the constructor and destructor arrays.
  874. ConstantInitBuilder builder(*this);
  875. auto ctors = builder.beginArray(CtorStructTy);
  876. for (const auto &I : Fns) {
  877. auto ctor = ctors.beginStruct(CtorStructTy);
  878. ctor.addInt(Int32Ty, I.Priority);
  879. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  880. if (I.AssociatedData)
  881. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  882. else
  883. ctor.addNullPointer(VoidPtrTy);
  884. ctor.finishAndAddTo(ctors);
  885. }
  886. auto list =
  887. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  888. /*constant*/ false,
  889. llvm::GlobalValue::AppendingLinkage);
  890. // The LTO linker doesn't seem to like it when we set an alignment
  891. // on appending variables. Take it off as a workaround.
  892. list->setAlignment(0);
  893. Fns.clear();
  894. }
  895. llvm::GlobalValue::LinkageTypes
  896. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  897. const auto *D = cast<FunctionDecl>(GD.getDecl());
  898. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  899. if (isa<CXXDestructorDecl>(D) &&
  900. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  901. GD.getDtorType())) {
  902. // Destructor variants in the Microsoft C++ ABI are always internal or
  903. // linkonce_odr thunks emitted on an as-needed basis.
  904. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  905. : llvm::GlobalValue::LinkOnceODRLinkage;
  906. }
  907. if (isa<CXXConstructorDecl>(D) &&
  908. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  909. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  910. // Our approach to inheriting constructors is fundamentally different from
  911. // that used by the MS ABI, so keep our inheriting constructor thunks
  912. // internal rather than trying to pick an unambiguous mangling for them.
  913. return llvm::GlobalValue::InternalLinkage;
  914. }
  915. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  916. }
  917. void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
  918. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  919. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  920. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  921. // Don't dllexport/import destructor thunks.
  922. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  923. return;
  924. }
  925. }
  926. if (FD->hasAttr<DLLImportAttr>())
  927. F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  928. else if (FD->hasAttr<DLLExportAttr>())
  929. F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  930. else
  931. F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  932. }
  933. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  934. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  935. if (!MDS) return nullptr;
  936. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  937. }
  938. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  939. llvm::Function *F) {
  940. setNonAliasAttributes(D, F);
  941. }
  942. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  943. const CGFunctionInfo &Info,
  944. llvm::Function *F) {
  945. unsigned CallingConv;
  946. llvm::AttributeList PAL;
  947. ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
  948. F->setAttributes(PAL);
  949. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  950. }
  951. /// Determines whether the language options require us to model
  952. /// unwind exceptions. We treat -fexceptions as mandating this
  953. /// except under the fragile ObjC ABI with only ObjC exceptions
  954. /// enabled. This means, for example, that C with -fexceptions
  955. /// enables this.
  956. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  957. // If exceptions are completely disabled, obviously this is false.
  958. if (!LangOpts.Exceptions) return false;
  959. // If C++ exceptions are enabled, this is true.
  960. if (LangOpts.CXXExceptions) return true;
  961. // If ObjC exceptions are enabled, this depends on the ABI.
  962. if (LangOpts.ObjCExceptions) {
  963. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  964. }
  965. return true;
  966. }
  967. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  968. llvm::Function *F) {
  969. llvm::AttrBuilder B;
  970. if (CodeGenOpts.UnwindTables)
  971. B.addAttribute(llvm::Attribute::UWTable);
  972. if (!hasUnwindExceptions(LangOpts))
  973. B.addAttribute(llvm::Attribute::NoUnwind);
  974. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  975. B.addAttribute(llvm::Attribute::StackProtect);
  976. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  977. B.addAttribute(llvm::Attribute::StackProtectStrong);
  978. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  979. B.addAttribute(llvm::Attribute::StackProtectReq);
  980. if (!D) {
  981. // If we don't have a declaration to control inlining, the function isn't
  982. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  983. // disabled, mark the function as noinline.
  984. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  985. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  986. B.addAttribute(llvm::Attribute::NoInline);
  987. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  988. return;
  989. }
  990. // Track whether we need to add the optnone LLVM attribute,
  991. // starting with the default for this optimization level.
  992. bool ShouldAddOptNone =
  993. !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
  994. // We can't add optnone in the following cases, it won't pass the verifier.
  995. ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
  996. ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
  997. ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
  998. if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
  999. B.addAttribute(llvm::Attribute::OptimizeNone);
  1000. // OptimizeNone implies noinline; we should not be inlining such functions.
  1001. B.addAttribute(llvm::Attribute::NoInline);
  1002. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1003. "OptimizeNone and AlwaysInline on same function!");
  1004. // We still need to handle naked functions even though optnone subsumes
  1005. // much of their semantics.
  1006. if (D->hasAttr<NakedAttr>())
  1007. B.addAttribute(llvm::Attribute::Naked);
  1008. // OptimizeNone wins over OptimizeForSize and MinSize.
  1009. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  1010. F->removeFnAttr(llvm::Attribute::MinSize);
  1011. } else if (D->hasAttr<NakedAttr>()) {
  1012. // Naked implies noinline: we should not be inlining such functions.
  1013. B.addAttribute(llvm::Attribute::Naked);
  1014. B.addAttribute(llvm::Attribute::NoInline);
  1015. } else if (D->hasAttr<NoDuplicateAttr>()) {
  1016. B.addAttribute(llvm::Attribute::NoDuplicate);
  1017. } else if (D->hasAttr<NoInlineAttr>()) {
  1018. B.addAttribute(llvm::Attribute::NoInline);
  1019. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  1020. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  1021. // (noinline wins over always_inline, and we can't specify both in IR)
  1022. B.addAttribute(llvm::Attribute::AlwaysInline);
  1023. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  1024. // If we're not inlining, then force everything that isn't always_inline to
  1025. // carry an explicit noinline attribute.
  1026. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  1027. B.addAttribute(llvm::Attribute::NoInline);
  1028. } else {
  1029. // Otherwise, propagate the inline hint attribute and potentially use its
  1030. // absence to mark things as noinline.
  1031. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1032. if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
  1033. return Redecl->isInlineSpecified();
  1034. })) {
  1035. B.addAttribute(llvm::Attribute::InlineHint);
  1036. } else if (CodeGenOpts.getInlining() ==
  1037. CodeGenOptions::OnlyHintInlining &&
  1038. !FD->isInlined() &&
  1039. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1040. B.addAttribute(llvm::Attribute::NoInline);
  1041. }
  1042. }
  1043. }
  1044. // Add other optimization related attributes if we are optimizing this
  1045. // function.
  1046. if (!D->hasAttr<OptimizeNoneAttr>()) {
  1047. if (D->hasAttr<ColdAttr>()) {
  1048. if (!ShouldAddOptNone)
  1049. B.addAttribute(llvm::Attribute::OptimizeForSize);
  1050. B.addAttribute(llvm::Attribute::Cold);
  1051. }
  1052. if (D->hasAttr<MinSizeAttr>())
  1053. B.addAttribute(llvm::Attribute::MinSize);
  1054. }
  1055. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1056. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  1057. if (alignment)
  1058. F->setAlignment(alignment);
  1059. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  1060. // reserve a bit for differentiating between virtual and non-virtual member
  1061. // functions. If the current target's C++ ABI requires this and this is a
  1062. // member function, set its alignment accordingly.
  1063. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  1064. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  1065. F->setAlignment(2);
  1066. }
  1067. // In the cross-dso CFI mode, we want !type attributes on definitions only.
  1068. if (CodeGenOpts.SanitizeCfiCrossDso)
  1069. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1070. CreateFunctionTypeMetadata(FD, F);
  1071. }
  1072. void CodeGenModule::SetCommonAttributes(const Decl *D,
  1073. llvm::GlobalValue *GV) {
  1074. if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
  1075. setGVProperties(GV, ND);
  1076. else
  1077. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  1078. if (D && D->hasAttr<UsedAttr>())
  1079. addUsedGlobal(GV);
  1080. }
  1081. void CodeGenModule::setAliasAttributes(const Decl *D,
  1082. llvm::GlobalValue *GV) {
  1083. SetCommonAttributes(D, GV);
  1084. // Process the dllexport attribute based on whether the original definition
  1085. // (not necessarily the aliasee) was exported.
  1086. if (D->hasAttr<DLLExportAttr>())
  1087. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  1088. }
  1089. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  1090. llvm::GlobalObject *GO) {
  1091. SetCommonAttributes(D, GO);
  1092. if (D) {
  1093. if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
  1094. if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
  1095. GV->addAttribute("bss-section", SA->getName());
  1096. if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
  1097. GV->addAttribute("data-section", SA->getName());
  1098. if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
  1099. GV->addAttribute("rodata-section", SA->getName());
  1100. }
  1101. if (auto *F = dyn_cast<llvm::Function>(GO)) {
  1102. if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
  1103. if (!D->getAttr<SectionAttr>())
  1104. F->addFnAttr("implicit-section-name", SA->getName());
  1105. }
  1106. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  1107. GO->setSection(SA->getName());
  1108. }
  1109. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  1110. }
  1111. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  1112. llvm::Function *F,
  1113. const CGFunctionInfo &FI) {
  1114. SetLLVMFunctionAttributes(D, FI, F);
  1115. SetLLVMFunctionAttributesForDefinition(D, F);
  1116. F->setLinkage(llvm::Function::InternalLinkage);
  1117. setNonAliasAttributes(D, F);
  1118. }
  1119. static void setLinkageForGV(llvm::GlobalValue *GV,
  1120. const NamedDecl *ND) {
  1121. // Set linkage and visibility in case we never see a definition.
  1122. LinkageInfo LV = ND->getLinkageAndVisibility();
  1123. if (!isExternallyVisible(LV.getLinkage())) {
  1124. // Don't set internal linkage on declarations.
  1125. } else {
  1126. if (ND->hasAttr<DLLImportAttr>()) {
  1127. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1128. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  1129. } else if (ND->hasAttr<DLLExportAttr>()) {
  1130. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1131. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  1132. // "extern_weak" is overloaded in LLVM; we probably should have
  1133. // separate linkage types for this.
  1134. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1135. }
  1136. }
  1137. }
  1138. void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
  1139. llvm::Function *F) {
  1140. // Only if we are checking indirect calls.
  1141. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  1142. return;
  1143. // Non-static class methods are handled via vtable pointer checks elsewhere.
  1144. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  1145. return;
  1146. // Additionally, if building with cross-DSO support...
  1147. if (CodeGenOpts.SanitizeCfiCrossDso) {
  1148. // Skip available_externally functions. They won't be codegen'ed in the
  1149. // current module anyway.
  1150. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  1151. return;
  1152. }
  1153. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  1154. F->addTypeMetadata(0, MD);
  1155. F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
  1156. // Emit a hash-based bit set entry for cross-DSO calls.
  1157. if (CodeGenOpts.SanitizeCfiCrossDso)
  1158. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  1159. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  1160. }
  1161. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1162. bool IsIncompleteFunction,
  1163. bool IsThunk) {
  1164. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  1165. // If this is an intrinsic function, set the function's attributes
  1166. // to the intrinsic's attributes.
  1167. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  1168. return;
  1169. }
  1170. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1171. if (!IsIncompleteFunction) {
  1172. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  1173. // Setup target-specific attributes.
  1174. if (F->isDeclaration())
  1175. getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
  1176. }
  1177. // Add the Returned attribute for "this", except for iOS 5 and earlier
  1178. // where substantial code, including the libstdc++ dylib, was compiled with
  1179. // GCC and does not actually return "this".
  1180. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  1181. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  1182. assert(!F->arg_empty() &&
  1183. F->arg_begin()->getType()
  1184. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  1185. "unexpected this return");
  1186. F->addAttribute(1, llvm::Attribute::Returned);
  1187. }
  1188. // Only a few attributes are set on declarations; these may later be
  1189. // overridden by a definition.
  1190. setLinkageForGV(F, FD);
  1191. setGVProperties(F, FD);
  1192. if (FD->getAttr<PragmaClangTextSectionAttr>()) {
  1193. F->addFnAttr("implicit-section-name");
  1194. }
  1195. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  1196. F->setSection(SA->getName());
  1197. if (FD->isReplaceableGlobalAllocationFunction()) {
  1198. // A replaceable global allocation function does not act like a builtin by
  1199. // default, only if it is invoked by a new-expression or delete-expression.
  1200. F->addAttribute(llvm::AttributeList::FunctionIndex,
  1201. llvm::Attribute::NoBuiltin);
  1202. // A sane operator new returns a non-aliasing pointer.
  1203. // FIXME: Also add NonNull attribute to the return value
  1204. // for the non-nothrow forms?
  1205. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  1206. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  1207. (Kind == OO_New || Kind == OO_Array_New))
  1208. F->addAttribute(llvm::AttributeList::ReturnIndex,
  1209. llvm::Attribute::NoAlias);
  1210. }
  1211. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  1212. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1213. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1214. if (MD->isVirtual())
  1215. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1216. // Don't emit entries for function declarations in the cross-DSO mode. This
  1217. // is handled with better precision by the receiving DSO.
  1218. if (!CodeGenOpts.SanitizeCfiCrossDso)
  1219. CreateFunctionTypeMetadata(FD, F);
  1220. if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
  1221. getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
  1222. }
  1223. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  1224. assert(!GV->isDeclaration() &&
  1225. "Only globals with definition can force usage.");
  1226. LLVMUsed.emplace_back(GV);
  1227. }
  1228. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1229. assert(!GV->isDeclaration() &&
  1230. "Only globals with definition can force usage.");
  1231. LLVMCompilerUsed.emplace_back(GV);
  1232. }
  1233. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  1234. std::vector<llvm::WeakTrackingVH> &List) {
  1235. // Don't create llvm.used if there is no need.
  1236. if (List.empty())
  1237. return;
  1238. // Convert List to what ConstantArray needs.
  1239. SmallVector<llvm::Constant*, 8> UsedArray;
  1240. UsedArray.resize(List.size());
  1241. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  1242. UsedArray[i] =
  1243. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1244. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  1245. }
  1246. if (UsedArray.empty())
  1247. return;
  1248. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  1249. auto *GV = new llvm::GlobalVariable(
  1250. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  1251. llvm::ConstantArray::get(ATy, UsedArray), Name);
  1252. GV->setSection("llvm.metadata");
  1253. }
  1254. void CodeGenModule::emitLLVMUsed() {
  1255. emitUsed(*this, "llvm.used", LLVMUsed);
  1256. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  1257. }
  1258. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  1259. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  1260. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1261. }
  1262. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  1263. llvm::SmallString<32> Opt;
  1264. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  1265. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1266. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1267. }
  1268. void CodeGenModule::AddELFLibDirective(StringRef Lib) {
  1269. auto &C = getLLVMContext();
  1270. LinkerOptionsMetadata.push_back(llvm::MDNode::get(
  1271. C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
  1272. }
  1273. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1274. llvm::SmallString<24> Opt;
  1275. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1276. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1277. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1278. }
  1279. /// \brief Add link options implied by the given module, including modules
  1280. /// it depends on, using a postorder walk.
  1281. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1282. SmallVectorImpl<llvm::MDNode *> &Metadata,
  1283. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1284. // Import this module's parent.
  1285. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1286. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1287. }
  1288. // Import this module's dependencies.
  1289. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1290. if (Visited.insert(Mod->Imports[I - 1]).second)
  1291. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1292. }
  1293. // Add linker options to link against the libraries/frameworks
  1294. // described by this module.
  1295. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1296. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1297. // Link against a framework. Frameworks are currently Darwin only, so we
  1298. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1299. if (Mod->LinkLibraries[I-1].IsFramework) {
  1300. llvm::Metadata *Args[2] = {
  1301. llvm::MDString::get(Context, "-framework"),
  1302. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1303. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1304. continue;
  1305. }
  1306. // Link against a library.
  1307. llvm::SmallString<24> Opt;
  1308. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1309. Mod->LinkLibraries[I-1].Library, Opt);
  1310. auto *OptString = llvm::MDString::get(Context, Opt);
  1311. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1312. }
  1313. }
  1314. void CodeGenModule::EmitModuleLinkOptions() {
  1315. // Collect the set of all of the modules we want to visit to emit link
  1316. // options, which is essentially the imported modules and all of their
  1317. // non-explicit child modules.
  1318. llvm::SetVector<clang::Module *> LinkModules;
  1319. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1320. SmallVector<clang::Module *, 16> Stack;
  1321. // Seed the stack with imported modules.
  1322. for (Module *M : ImportedModules) {
  1323. // Do not add any link flags when an implementation TU of a module imports
  1324. // a header of that same module.
  1325. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  1326. !getLangOpts().isCompilingModule())
  1327. continue;
  1328. if (Visited.insert(M).second)
  1329. Stack.push_back(M);
  1330. }
  1331. // Find all of the modules to import, making a little effort to prune
  1332. // non-leaf modules.
  1333. while (!Stack.empty()) {
  1334. clang::Module *Mod = Stack.pop_back_val();
  1335. bool AnyChildren = false;
  1336. // Visit the submodules of this module.
  1337. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  1338. SubEnd = Mod->submodule_end();
  1339. Sub != SubEnd; ++Sub) {
  1340. // Skip explicit children; they need to be explicitly imported to be
  1341. // linked against.
  1342. if ((*Sub)->IsExplicit)
  1343. continue;
  1344. if (Visited.insert(*Sub).second) {
  1345. Stack.push_back(*Sub);
  1346. AnyChildren = true;
  1347. }
  1348. }
  1349. // We didn't find any children, so add this module to the list of
  1350. // modules to link against.
  1351. if (!AnyChildren) {
  1352. LinkModules.insert(Mod);
  1353. }
  1354. }
  1355. // Add link options for all of the imported modules in reverse topological
  1356. // order. We don't do anything to try to order import link flags with respect
  1357. // to linker options inserted by things like #pragma comment().
  1358. SmallVector<llvm::MDNode *, 16> MetadataArgs;
  1359. Visited.clear();
  1360. for (Module *M : LinkModules)
  1361. if (Visited.insert(M).second)
  1362. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1363. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1364. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1365. // Add the linker options metadata flag.
  1366. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
  1367. for (auto *MD : LinkerOptionsMetadata)
  1368. NMD->addOperand(MD);
  1369. }
  1370. void CodeGenModule::EmitDeferred() {
  1371. // Emit code for any potentially referenced deferred decls. Since a
  1372. // previously unused static decl may become used during the generation of code
  1373. // for a static function, iterate until no changes are made.
  1374. if (!DeferredVTables.empty()) {
  1375. EmitDeferredVTables();
  1376. // Emitting a vtable doesn't directly cause more vtables to
  1377. // become deferred, although it can cause functions to be
  1378. // emitted that then need those vtables.
  1379. assert(DeferredVTables.empty());
  1380. }
  1381. // Stop if we're out of both deferred vtables and deferred declarations.
  1382. if (DeferredDeclsToEmit.empty())
  1383. return;
  1384. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1385. // work, it will not interfere with this.
  1386. std::vector<GlobalDecl> CurDeclsToEmit;
  1387. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1388. for (GlobalDecl &D : CurDeclsToEmit) {
  1389. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1390. // to get GlobalValue with exactly the type we need, not something that
  1391. // might had been created for another decl with the same mangled name but
  1392. // different type.
  1393. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1394. GetAddrOfGlobal(D, ForDefinition));
  1395. // In case of different address spaces, we may still get a cast, even with
  1396. // IsForDefinition equal to true. Query mangled names table to get
  1397. // GlobalValue.
  1398. if (!GV)
  1399. GV = GetGlobalValue(getMangledName(D));
  1400. // Make sure GetGlobalValue returned non-null.
  1401. assert(GV);
  1402. // Check to see if we've already emitted this. This is necessary
  1403. // for a couple of reasons: first, decls can end up in the
  1404. // deferred-decls queue multiple times, and second, decls can end
  1405. // up with definitions in unusual ways (e.g. by an extern inline
  1406. // function acquiring a strong function redefinition). Just
  1407. // ignore these cases.
  1408. if (!GV->isDeclaration())
  1409. continue;
  1410. // Otherwise, emit the definition and move on to the next one.
  1411. EmitGlobalDefinition(D, GV);
  1412. // If we found out that we need to emit more decls, do that recursively.
  1413. // This has the advantage that the decls are emitted in a DFS and related
  1414. // ones are close together, which is convenient for testing.
  1415. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1416. EmitDeferred();
  1417. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1418. }
  1419. }
  1420. }
  1421. void CodeGenModule::EmitVTablesOpportunistically() {
  1422. // Try to emit external vtables as available_externally if they have emitted
  1423. // all inlined virtual functions. It runs after EmitDeferred() and therefore
  1424. // is not allowed to create new references to things that need to be emitted
  1425. // lazily. Note that it also uses fact that we eagerly emitting RTTI.
  1426. assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
  1427. && "Only emit opportunistic vtables with optimizations");
  1428. for (const CXXRecordDecl *RD : OpportunisticVTables) {
  1429. assert(getVTables().isVTableExternal(RD) &&
  1430. "This queue should only contain external vtables");
  1431. if (getCXXABI().canSpeculativelyEmitVTable(RD))
  1432. VTables.GenerateClassData(RD);
  1433. }
  1434. OpportunisticVTables.clear();
  1435. }
  1436. void CodeGenModule::EmitGlobalAnnotations() {
  1437. if (Annotations.empty())
  1438. return;
  1439. // Create a new global variable for the ConstantStruct in the Module.
  1440. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1441. Annotations[0]->getType(), Annotations.size()), Annotations);
  1442. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1443. llvm::GlobalValue::AppendingLinkage,
  1444. Array, "llvm.global.annotations");
  1445. gv->setSection(AnnotationSection);
  1446. }
  1447. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1448. llvm::Constant *&AStr = AnnotationStrings[Str];
  1449. if (AStr)
  1450. return AStr;
  1451. // Not found yet, create a new global.
  1452. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1453. auto *gv =
  1454. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1455. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1456. gv->setSection(AnnotationSection);
  1457. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1458. AStr = gv;
  1459. return gv;
  1460. }
  1461. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1462. SourceManager &SM = getContext().getSourceManager();
  1463. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1464. if (PLoc.isValid())
  1465. return EmitAnnotationString(PLoc.getFilename());
  1466. return EmitAnnotationString(SM.getBufferName(Loc));
  1467. }
  1468. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1469. SourceManager &SM = getContext().getSourceManager();
  1470. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1471. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1472. SM.getExpansionLineNumber(L);
  1473. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1474. }
  1475. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1476. const AnnotateAttr *AA,
  1477. SourceLocation L) {
  1478. // Get the globals for file name, annotation, and the line number.
  1479. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1480. *UnitGV = EmitAnnotationUnit(L),
  1481. *LineNoCst = EmitAnnotationLineNo(L);
  1482. // Create the ConstantStruct for the global annotation.
  1483. llvm::Constant *Fields[4] = {
  1484. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1485. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1486. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1487. LineNoCst
  1488. };
  1489. return llvm::ConstantStruct::getAnon(Fields);
  1490. }
  1491. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1492. llvm::GlobalValue *GV) {
  1493. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1494. // Get the struct elements for these annotations.
  1495. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1496. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1497. }
  1498. bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
  1499. llvm::Function *Fn,
  1500. SourceLocation Loc) const {
  1501. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1502. // Blacklist by function name.
  1503. if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
  1504. return true;
  1505. // Blacklist by location.
  1506. if (Loc.isValid())
  1507. return SanitizerBL.isBlacklistedLocation(Kind, Loc);
  1508. // If location is unknown, this may be a compiler-generated function. Assume
  1509. // it's located in the main file.
  1510. auto &SM = Context.getSourceManager();
  1511. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1512. return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
  1513. }
  1514. return false;
  1515. }
  1516. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1517. SourceLocation Loc, QualType Ty,
  1518. StringRef Category) const {
  1519. // For now globals can be blacklisted only in ASan and KASan.
  1520. const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
  1521. (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress);
  1522. if (!EnabledAsanMask)
  1523. return false;
  1524. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1525. if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
  1526. return true;
  1527. if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
  1528. return true;
  1529. // Check global type.
  1530. if (!Ty.isNull()) {
  1531. // Drill down the array types: if global variable of a fixed type is
  1532. // blacklisted, we also don't instrument arrays of them.
  1533. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1534. Ty = AT->getElementType();
  1535. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1536. // We allow to blacklist only record types (classes, structs etc.)
  1537. if (Ty->isRecordType()) {
  1538. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1539. if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
  1540. return true;
  1541. }
  1542. }
  1543. return false;
  1544. }
  1545. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1546. StringRef Category) const {
  1547. if (!LangOpts.XRayInstrument)
  1548. return false;
  1549. const auto &XRayFilter = getContext().getXRayFilter();
  1550. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  1551. auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
  1552. if (Loc.isValid())
  1553. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  1554. if (Attr == ImbueAttr::NONE)
  1555. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  1556. switch (Attr) {
  1557. case ImbueAttr::NONE:
  1558. return false;
  1559. case ImbueAttr::ALWAYS:
  1560. Fn->addFnAttr("function-instrument", "xray-always");
  1561. break;
  1562. case ImbueAttr::ALWAYS_ARG1:
  1563. Fn->addFnAttr("function-instrument", "xray-always");
  1564. Fn->addFnAttr("xray-log-args", "1");
  1565. break;
  1566. case ImbueAttr::NEVER:
  1567. Fn->addFnAttr("function-instrument", "xray-never");
  1568. break;
  1569. }
  1570. return true;
  1571. }
  1572. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1573. // Never defer when EmitAllDecls is specified.
  1574. if (LangOpts.EmitAllDecls)
  1575. return true;
  1576. return getContext().DeclMustBeEmitted(Global);
  1577. }
  1578. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1579. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1580. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1581. // Implicit template instantiations may change linkage if they are later
  1582. // explicitly instantiated, so they should not be emitted eagerly.
  1583. return false;
  1584. if (const auto *VD = dyn_cast<VarDecl>(Global))
  1585. if (Context.getInlineVariableDefinitionKind(VD) ==
  1586. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  1587. // A definition of an inline constexpr static data member may change
  1588. // linkage later if it's redeclared outside the class.
  1589. return false;
  1590. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1591. // codegen for global variables, because they may be marked as threadprivate.
  1592. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1593. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1594. return false;
  1595. return true;
  1596. }
  1597. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1598. const CXXUuidofExpr* E) {
  1599. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1600. // well-formed.
  1601. StringRef Uuid = E->getUuidStr();
  1602. std::string Name = "_GUID_" + Uuid.lower();
  1603. std::replace(Name.begin(), Name.end(), '-', '_');
  1604. // The UUID descriptor should be pointer aligned.
  1605. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1606. // Look for an existing global.
  1607. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1608. return ConstantAddress(GV, Alignment);
  1609. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1610. assert(Init && "failed to initialize as constant");
  1611. auto *GV = new llvm::GlobalVariable(
  1612. getModule(), Init->getType(),
  1613. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1614. if (supportsCOMDAT())
  1615. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1616. return ConstantAddress(GV, Alignment);
  1617. }
  1618. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1619. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1620. assert(AA && "No alias?");
  1621. CharUnits Alignment = getContext().getDeclAlign(VD);
  1622. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1623. // See if there is already something with the target's name in the module.
  1624. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1625. if (Entry) {
  1626. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1627. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1628. return ConstantAddress(Ptr, Alignment);
  1629. }
  1630. llvm::Constant *Aliasee;
  1631. if (isa<llvm::FunctionType>(DeclTy))
  1632. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1633. GlobalDecl(cast<FunctionDecl>(VD)),
  1634. /*ForVTable=*/false);
  1635. else
  1636. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1637. llvm::PointerType::getUnqual(DeclTy),
  1638. nullptr);
  1639. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1640. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1641. WeakRefReferences.insert(F);
  1642. return ConstantAddress(Aliasee, Alignment);
  1643. }
  1644. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1645. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1646. // Weak references don't produce any output by themselves.
  1647. if (Global->hasAttr<WeakRefAttr>())
  1648. return;
  1649. // If this is an alias definition (which otherwise looks like a declaration)
  1650. // emit it now.
  1651. if (Global->hasAttr<AliasAttr>())
  1652. return EmitAliasDefinition(GD);
  1653. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1654. if (Global->hasAttr<IFuncAttr>())
  1655. return emitIFuncDefinition(GD);
  1656. // If this is CUDA, be selective about which declarations we emit.
  1657. if (LangOpts.CUDA) {
  1658. if (LangOpts.CUDAIsDevice) {
  1659. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1660. !Global->hasAttr<CUDAGlobalAttr>() &&
  1661. !Global->hasAttr<CUDAConstantAttr>() &&
  1662. !Global->hasAttr<CUDASharedAttr>())
  1663. return;
  1664. } else {
  1665. // We need to emit host-side 'shadows' for all global
  1666. // device-side variables because the CUDA runtime needs their
  1667. // size and host-side address in order to provide access to
  1668. // their device-side incarnations.
  1669. // So device-only functions are the only things we skip.
  1670. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1671. Global->hasAttr<CUDADeviceAttr>())
  1672. return;
  1673. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1674. "Expected Variable or Function");
  1675. }
  1676. }
  1677. if (LangOpts.OpenMP) {
  1678. // If this is OpenMP device, check if it is legal to emit this global
  1679. // normally.
  1680. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1681. return;
  1682. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1683. if (MustBeEmitted(Global))
  1684. EmitOMPDeclareReduction(DRD);
  1685. return;
  1686. }
  1687. }
  1688. // Ignore declarations, they will be emitted on their first use.
  1689. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1690. // Forward declarations are emitted lazily on first use.
  1691. if (!FD->doesThisDeclarationHaveABody()) {
  1692. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1693. return;
  1694. StringRef MangledName = getMangledName(GD);
  1695. // Compute the function info and LLVM type.
  1696. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1697. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1698. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1699. /*DontDefer=*/false);
  1700. return;
  1701. }
  1702. } else {
  1703. const auto *VD = cast<VarDecl>(Global);
  1704. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1705. // We need to emit device-side global CUDA variables even if a
  1706. // variable does not have a definition -- we still need to define
  1707. // host-side shadow for it.
  1708. bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  1709. !VD->hasDefinition() &&
  1710. (VD->hasAttr<CUDAConstantAttr>() ||
  1711. VD->hasAttr<CUDADeviceAttr>());
  1712. if (!MustEmitForCuda &&
  1713. VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1714. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  1715. // If this declaration may have caused an inline variable definition to
  1716. // change linkage, make sure that it's emitted.
  1717. if (Context.getInlineVariableDefinitionKind(VD) ==
  1718. ASTContext::InlineVariableDefinitionKind::Strong)
  1719. GetAddrOfGlobalVar(VD);
  1720. return;
  1721. }
  1722. }
  1723. // Defer code generation to first use when possible, e.g. if this is an inline
  1724. // function. If the global must always be emitted, do it eagerly if possible
  1725. // to benefit from cache locality.
  1726. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1727. // Emit the definition if it can't be deferred.
  1728. EmitGlobalDefinition(GD);
  1729. return;
  1730. }
  1731. // If we're deferring emission of a C++ variable with an
  1732. // initializer, remember the order in which it appeared in the file.
  1733. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1734. cast<VarDecl>(Global)->hasInit()) {
  1735. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1736. CXXGlobalInits.push_back(nullptr);
  1737. }
  1738. StringRef MangledName = getMangledName(GD);
  1739. if (GetGlobalValue(MangledName) != nullptr) {
  1740. // The value has already been used and should therefore be emitted.
  1741. addDeferredDeclToEmit(GD);
  1742. } else if (MustBeEmitted(Global)) {
  1743. // The value must be emitted, but cannot be emitted eagerly.
  1744. assert(!MayBeEmittedEagerly(Global));
  1745. addDeferredDeclToEmit(GD);
  1746. } else {
  1747. // Otherwise, remember that we saw a deferred decl with this name. The
  1748. // first use of the mangled name will cause it to move into
  1749. // DeferredDeclsToEmit.
  1750. DeferredDecls[MangledName] = GD;
  1751. }
  1752. }
  1753. // Check if T is a class type with a destructor that's not dllimport.
  1754. static bool HasNonDllImportDtor(QualType T) {
  1755. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1756. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1757. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  1758. return true;
  1759. return false;
  1760. }
  1761. namespace {
  1762. struct FunctionIsDirectlyRecursive :
  1763. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1764. const StringRef Name;
  1765. const Builtin::Context &BI;
  1766. bool Result;
  1767. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1768. Name(N), BI(C), Result(false) {
  1769. }
  1770. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1771. bool TraverseCallExpr(CallExpr *E) {
  1772. const FunctionDecl *FD = E->getDirectCallee();
  1773. if (!FD)
  1774. return true;
  1775. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1776. if (Attr && Name == Attr->getLabel()) {
  1777. Result = true;
  1778. return false;
  1779. }
  1780. unsigned BuiltinID = FD->getBuiltinID();
  1781. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1782. return true;
  1783. StringRef BuiltinName = BI.getName(BuiltinID);
  1784. if (BuiltinName.startswith("__builtin_") &&
  1785. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1786. Result = true;
  1787. return false;
  1788. }
  1789. return true;
  1790. }
  1791. };
  1792. // Make sure we're not referencing non-imported vars or functions.
  1793. struct DLLImportFunctionVisitor
  1794. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  1795. bool SafeToInline = true;
  1796. bool shouldVisitImplicitCode() const { return true; }
  1797. bool VisitVarDecl(VarDecl *VD) {
  1798. if (VD->getTLSKind()) {
  1799. // A thread-local variable cannot be imported.
  1800. SafeToInline = false;
  1801. return SafeToInline;
  1802. }
  1803. // A variable definition might imply a destructor call.
  1804. if (VD->isThisDeclarationADefinition())
  1805. SafeToInline = !HasNonDllImportDtor(VD->getType());
  1806. return SafeToInline;
  1807. }
  1808. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  1809. if (const auto *D = E->getTemporary()->getDestructor())
  1810. SafeToInline = D->hasAttr<DLLImportAttr>();
  1811. return SafeToInline;
  1812. }
  1813. bool VisitDeclRefExpr(DeclRefExpr *E) {
  1814. ValueDecl *VD = E->getDecl();
  1815. if (isa<FunctionDecl>(VD))
  1816. SafeToInline = VD->hasAttr<DLLImportAttr>();
  1817. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  1818. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  1819. return SafeToInline;
  1820. }
  1821. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  1822. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  1823. return SafeToInline;
  1824. }
  1825. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  1826. CXXMethodDecl *M = E->getMethodDecl();
  1827. if (!M) {
  1828. // Call through a pointer to member function. This is safe to inline.
  1829. SafeToInline = true;
  1830. } else {
  1831. SafeToInline = M->hasAttr<DLLImportAttr>();
  1832. }
  1833. return SafeToInline;
  1834. }
  1835. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  1836. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  1837. return SafeToInline;
  1838. }
  1839. bool VisitCXXNewExpr(CXXNewExpr *E) {
  1840. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  1841. return SafeToInline;
  1842. }
  1843. };
  1844. }
  1845. // isTriviallyRecursive - Check if this function calls another
  1846. // decl that, because of the asm attribute or the other decl being a builtin,
  1847. // ends up pointing to itself.
  1848. bool
  1849. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1850. StringRef Name;
  1851. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1852. // asm labels are a special kind of mangling we have to support.
  1853. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1854. if (!Attr)
  1855. return false;
  1856. Name = Attr->getLabel();
  1857. } else {
  1858. Name = FD->getName();
  1859. }
  1860. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1861. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1862. return Walker.Result;
  1863. }
  1864. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1865. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1866. return true;
  1867. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1868. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1869. return false;
  1870. if (F->hasAttr<DLLImportAttr>()) {
  1871. // Check whether it would be safe to inline this dllimport function.
  1872. DLLImportFunctionVisitor Visitor;
  1873. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  1874. if (!Visitor.SafeToInline)
  1875. return false;
  1876. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  1877. // Implicit destructor invocations aren't captured in the AST, so the
  1878. // check above can't see them. Check for them manually here.
  1879. for (const Decl *Member : Dtor->getParent()->decls())
  1880. if (isa<FieldDecl>(Member))
  1881. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  1882. return false;
  1883. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  1884. if (HasNonDllImportDtor(B.getType()))
  1885. return false;
  1886. }
  1887. }
  1888. // PR9614. Avoid cases where the source code is lying to us. An available
  1889. // externally function should have an equivalent function somewhere else,
  1890. // but a function that calls itself is clearly not equivalent to the real
  1891. // implementation.
  1892. // This happens in glibc's btowc and in some configure checks.
  1893. return !isTriviallyRecursive(F);
  1894. }
  1895. bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
  1896. return CodeGenOpts.OptimizationLevel > 0;
  1897. }
  1898. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1899. const auto *D = cast<ValueDecl>(GD.getDecl());
  1900. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1901. Context.getSourceManager(),
  1902. "Generating code for declaration");
  1903. if (isa<FunctionDecl>(D)) {
  1904. // At -O0, don't generate IR for functions with available_externally
  1905. // linkage.
  1906. if (!shouldEmitFunction(GD))
  1907. return;
  1908. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1909. // Make sure to emit the definition(s) before we emit the thunks.
  1910. // This is necessary for the generation of certain thunks.
  1911. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1912. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1913. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1914. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1915. else
  1916. EmitGlobalFunctionDefinition(GD, GV);
  1917. if (Method->isVirtual())
  1918. getVTables().EmitThunks(GD);
  1919. return;
  1920. }
  1921. return EmitGlobalFunctionDefinition(GD, GV);
  1922. }
  1923. if (const auto *VD = dyn_cast<VarDecl>(D))
  1924. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  1925. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1926. }
  1927. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1928. llvm::Function *NewFn);
  1929. void CodeGenModule::emitMultiVersionFunctions() {
  1930. for (GlobalDecl GD : MultiVersionFuncs) {
  1931. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  1932. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1933. getContext().forEachMultiversionedFunctionVersion(
  1934. FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
  1935. GlobalDecl CurGD{
  1936. (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
  1937. StringRef MangledName = getMangledName(CurGD);
  1938. llvm::Constant *Func = GetGlobalValue(MangledName);
  1939. if (!Func) {
  1940. if (CurFD->isDefined()) {
  1941. EmitGlobalFunctionDefinition(CurGD, nullptr);
  1942. Func = GetGlobalValue(MangledName);
  1943. } else {
  1944. const CGFunctionInfo &FI =
  1945. getTypes().arrangeGlobalDeclaration(GD);
  1946. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1947. Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
  1948. /*DontDefer=*/false, ForDefinition);
  1949. }
  1950. assert(Func && "This should have just been created");
  1951. }
  1952. Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
  1953. CurFD->getAttr<TargetAttr>()->parse());
  1954. });
  1955. llvm::Function *ResolverFunc = cast<llvm::Function>(
  1956. GetGlobalValue((getMangledName(GD) + ".resolver").str()));
  1957. if (supportsCOMDAT())
  1958. ResolverFunc->setComdat(
  1959. getModule().getOrInsertComdat(ResolverFunc->getName()));
  1960. std::stable_sort(
  1961. Options.begin(), Options.end(),
  1962. std::greater<CodeGenFunction::MultiVersionResolverOption>());
  1963. CodeGenFunction CGF(*this);
  1964. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  1965. }
  1966. }
  1967. /// If an ifunc for the specified mangled name is not in the module, create and
  1968. /// return an llvm IFunc Function with the specified type.
  1969. llvm::Constant *
  1970. CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
  1971. StringRef MangledName,
  1972. const FunctionDecl *FD) {
  1973. std::string IFuncName = (MangledName + ".ifunc").str();
  1974. if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
  1975. return IFuncGV;
  1976. // Since this is the first time we've created this IFunc, make sure
  1977. // that we put this multiversioned function into the list to be
  1978. // replaced later.
  1979. MultiVersionFuncs.push_back(GD);
  1980. std::string ResolverName = (MangledName + ".resolver").str();
  1981. llvm::Type *ResolverType = llvm::FunctionType::get(
  1982. llvm::PointerType::get(DeclTy,
  1983. Context.getTargetAddressSpace(FD->getType())),
  1984. false);
  1985. llvm::Constant *Resolver =
  1986. GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
  1987. /*ForVTable=*/false);
  1988. llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
  1989. DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
  1990. GIF->setName(IFuncName);
  1991. SetCommonAttributes(FD, GIF);
  1992. return GIF;
  1993. }
  1994. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1995. /// module, create and return an llvm Function with the specified type. If there
  1996. /// is something in the module with the specified name, return it potentially
  1997. /// bitcasted to the right type.
  1998. ///
  1999. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2000. /// to set the attributes on the function when it is first created.
  2001. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  2002. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  2003. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  2004. ForDefinition_t IsForDefinition) {
  2005. const Decl *D = GD.getDecl();
  2006. // Any attempts to use a MultiVersion function should result in retrieving
  2007. // the iFunc instead. Name Mangling will handle the rest of the changes.
  2008. if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
  2009. if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) {
  2010. UpdateMultiVersionNames(GD, FD);
  2011. if (!IsForDefinition)
  2012. return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD);
  2013. }
  2014. }
  2015. // Lookup the entry, lazily creating it if necessary.
  2016. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2017. if (Entry) {
  2018. if (WeakRefReferences.erase(Entry)) {
  2019. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  2020. if (FD && !FD->hasAttr<WeakAttr>())
  2021. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2022. }
  2023. // Handle dropped DLL attributes.
  2024. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2025. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2026. // If there are two attempts to define the same mangled name, issue an
  2027. // error.
  2028. if (IsForDefinition && !Entry->isDeclaration()) {
  2029. GlobalDecl OtherGD;
  2030. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  2031. // to make sure that we issue an error only once.
  2032. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2033. (GD.getCanonicalDecl().getDecl() !=
  2034. OtherGD.getCanonicalDecl().getDecl()) &&
  2035. DiagnosedConflictingDefinitions.insert(GD).second) {
  2036. getDiags().Report(D->getLocation(),
  2037. diag::err_duplicate_mangled_name);
  2038. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2039. diag::note_previous_definition);
  2040. }
  2041. }
  2042. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  2043. (Entry->getType()->getElementType() == Ty)) {
  2044. return Entry;
  2045. }
  2046. // Make sure the result is of the correct type.
  2047. // (If function is requested for a definition, we always need to create a new
  2048. // function, not just return a bitcast.)
  2049. if (!IsForDefinition)
  2050. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  2051. }
  2052. // This function doesn't have a complete type (for example, the return
  2053. // type is an incomplete struct). Use a fake type instead, and make
  2054. // sure not to try to set attributes.
  2055. bool IsIncompleteFunction = false;
  2056. llvm::FunctionType *FTy;
  2057. if (isa<llvm::FunctionType>(Ty)) {
  2058. FTy = cast<llvm::FunctionType>(Ty);
  2059. } else {
  2060. FTy = llvm::FunctionType::get(VoidTy, false);
  2061. IsIncompleteFunction = true;
  2062. }
  2063. llvm::Function *F =
  2064. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  2065. Entry ? StringRef() : MangledName, &getModule());
  2066. // If we already created a function with the same mangled name (but different
  2067. // type) before, take its name and add it to the list of functions to be
  2068. // replaced with F at the end of CodeGen.
  2069. //
  2070. // This happens if there is a prototype for a function (e.g. "int f()") and
  2071. // then a definition of a different type (e.g. "int f(int x)").
  2072. if (Entry) {
  2073. F->takeName(Entry);
  2074. // This might be an implementation of a function without a prototype, in
  2075. // which case, try to do special replacement of calls which match the new
  2076. // prototype. The really key thing here is that we also potentially drop
  2077. // arguments from the call site so as to make a direct call, which makes the
  2078. // inliner happier and suppresses a number of optimizer warnings (!) about
  2079. // dropping arguments.
  2080. if (!Entry->use_empty()) {
  2081. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  2082. Entry->removeDeadConstantUsers();
  2083. }
  2084. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  2085. F, Entry->getType()->getElementType()->getPointerTo());
  2086. addGlobalValReplacement(Entry, BC);
  2087. }
  2088. assert(F->getName() == MangledName && "name was uniqued!");
  2089. if (D)
  2090. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  2091. if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
  2092. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
  2093. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  2094. }
  2095. if (!DontDefer) {
  2096. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  2097. // each other bottoming out with the base dtor. Therefore we emit non-base
  2098. // dtors on usage, even if there is no dtor definition in the TU.
  2099. if (D && isa<CXXDestructorDecl>(D) &&
  2100. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  2101. GD.getDtorType()))
  2102. addDeferredDeclToEmit(GD);
  2103. // This is the first use or definition of a mangled name. If there is a
  2104. // deferred decl with this name, remember that we need to emit it at the end
  2105. // of the file.
  2106. auto DDI = DeferredDecls.find(MangledName);
  2107. if (DDI != DeferredDecls.end()) {
  2108. // Move the potentially referenced deferred decl to the
  2109. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  2110. // don't need it anymore).
  2111. addDeferredDeclToEmit(DDI->second);
  2112. DeferredDecls.erase(DDI);
  2113. // Otherwise, there are cases we have to worry about where we're
  2114. // using a declaration for which we must emit a definition but where
  2115. // we might not find a top-level definition:
  2116. // - member functions defined inline in their classes
  2117. // - friend functions defined inline in some class
  2118. // - special member functions with implicit definitions
  2119. // If we ever change our AST traversal to walk into class methods,
  2120. // this will be unnecessary.
  2121. //
  2122. // We also don't emit a definition for a function if it's going to be an
  2123. // entry in a vtable, unless it's already marked as used.
  2124. } else if (getLangOpts().CPlusPlus && D) {
  2125. // Look for a declaration that's lexically in a record.
  2126. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  2127. FD = FD->getPreviousDecl()) {
  2128. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  2129. if (FD->doesThisDeclarationHaveABody()) {
  2130. addDeferredDeclToEmit(GD.getWithDecl(FD));
  2131. break;
  2132. }
  2133. }
  2134. }
  2135. }
  2136. }
  2137. // Make sure the result is of the requested type.
  2138. if (!IsIncompleteFunction) {
  2139. assert(F->getType()->getElementType() == Ty);
  2140. return F;
  2141. }
  2142. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2143. return llvm::ConstantExpr::getBitCast(F, PTy);
  2144. }
  2145. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  2146. /// non-null, then this function will use the specified type if it has to
  2147. /// create it (this occurs when we see a definition of the function).
  2148. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  2149. llvm::Type *Ty,
  2150. bool ForVTable,
  2151. bool DontDefer,
  2152. ForDefinition_t IsForDefinition) {
  2153. // If there was no specific requested type, just convert it now.
  2154. if (!Ty) {
  2155. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2156. auto CanonTy = Context.getCanonicalType(FD->getType());
  2157. Ty = getTypes().ConvertFunctionType(CanonTy, FD);
  2158. }
  2159. StringRef MangledName = getMangledName(GD);
  2160. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  2161. /*IsThunk=*/false, llvm::AttributeList(),
  2162. IsForDefinition);
  2163. }
  2164. static const FunctionDecl *
  2165. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  2166. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  2167. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2168. IdentifierInfo &CII = C.Idents.get(Name);
  2169. for (const auto &Result : DC->lookup(&CII))
  2170. if (const auto FD = dyn_cast<FunctionDecl>(Result))
  2171. return FD;
  2172. if (!C.getLangOpts().CPlusPlus)
  2173. return nullptr;
  2174. // Demangle the premangled name from getTerminateFn()
  2175. IdentifierInfo &CXXII =
  2176. (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
  2177. ? C.Idents.get("terminate")
  2178. : C.Idents.get(Name);
  2179. for (const auto &N : {"__cxxabiv1", "std"}) {
  2180. IdentifierInfo &NS = C.Idents.get(N);
  2181. for (const auto &Result : DC->lookup(&NS)) {
  2182. NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  2183. if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
  2184. for (const auto &Result : LSD->lookup(&NS))
  2185. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  2186. break;
  2187. if (ND)
  2188. for (const auto &Result : ND->lookup(&CXXII))
  2189. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  2190. return FD;
  2191. }
  2192. }
  2193. return nullptr;
  2194. }
  2195. /// CreateRuntimeFunction - Create a new runtime function with the specified
  2196. /// type and name.
  2197. llvm::Constant *
  2198. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  2199. llvm::AttributeList ExtraAttrs,
  2200. bool Local) {
  2201. llvm::Constant *C =
  2202. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2203. /*DontDefer=*/false, /*IsThunk=*/false,
  2204. ExtraAttrs);
  2205. if (auto *F = dyn_cast<llvm::Function>(C)) {
  2206. if (F->empty()) {
  2207. F->setCallingConv(getRuntimeCC());
  2208. if (!Local && getTriple().isOSBinFormatCOFF() &&
  2209. !getCodeGenOpts().LTOVisibilityPublicStd &&
  2210. !getTriple().isWindowsGNUEnvironment()) {
  2211. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  2212. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  2213. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2214. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2215. }
  2216. }
  2217. }
  2218. }
  2219. return C;
  2220. }
  2221. /// CreateBuiltinFunction - Create a new builtin function with the specified
  2222. /// type and name.
  2223. llvm::Constant *
  2224. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
  2225. llvm::AttributeList ExtraAttrs) {
  2226. llvm::Constant *C =
  2227. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2228. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  2229. if (auto *F = dyn_cast<llvm::Function>(C))
  2230. if (F->empty())
  2231. F->setCallingConv(getBuiltinCC());
  2232. return C;
  2233. }
  2234. /// isTypeConstant - Determine whether an object of this type can be emitted
  2235. /// as a constant.
  2236. ///
  2237. /// If ExcludeCtor is true, the duration when the object's constructor runs
  2238. /// will not be considered. The caller will need to verify that the object is
  2239. /// not written to during its construction.
  2240. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  2241. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  2242. return false;
  2243. if (Context.getLangOpts().CPlusPlus) {
  2244. if (const CXXRecordDecl *Record
  2245. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  2246. return ExcludeCtor && !Record->hasMutableFields() &&
  2247. Record->hasTrivialDestructor();
  2248. }
  2249. return true;
  2250. }
  2251. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  2252. /// create and return an llvm GlobalVariable with the specified type. If there
  2253. /// is something in the module with the specified name, return it potentially
  2254. /// bitcasted to the right type.
  2255. ///
  2256. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2257. /// to set the attributes on the global when it is first created.
  2258. ///
  2259. /// If IsForDefinition is true, it is guranteed that an actual global with
  2260. /// type Ty will be returned, not conversion of a variable with the same
  2261. /// mangled name but some other type.
  2262. llvm::Constant *
  2263. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  2264. llvm::PointerType *Ty,
  2265. const VarDecl *D,
  2266. ForDefinition_t IsForDefinition) {
  2267. // Lookup the entry, lazily creating it if necessary.
  2268. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2269. if (Entry) {
  2270. if (WeakRefReferences.erase(Entry)) {
  2271. if (D && !D->hasAttr<WeakAttr>())
  2272. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2273. }
  2274. // Handle dropped DLL attributes.
  2275. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2276. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2277. if (Entry->getType() == Ty)
  2278. return Entry;
  2279. // If there are two attempts to define the same mangled name, issue an
  2280. // error.
  2281. if (IsForDefinition && !Entry->isDeclaration()) {
  2282. GlobalDecl OtherGD;
  2283. const VarDecl *OtherD;
  2284. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  2285. // to make sure that we issue an error only once.
  2286. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  2287. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  2288. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  2289. OtherD->hasInit() &&
  2290. DiagnosedConflictingDefinitions.insert(D).second) {
  2291. getDiags().Report(D->getLocation(),
  2292. diag::err_duplicate_mangled_name);
  2293. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2294. diag::note_previous_definition);
  2295. }
  2296. }
  2297. // Make sure the result is of the correct type.
  2298. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  2299. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  2300. // (If global is requested for a definition, we always need to create a new
  2301. // global, not just return a bitcast.)
  2302. if (!IsForDefinition)
  2303. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  2304. }
  2305. auto AddrSpace = GetGlobalVarAddressSpace(D);
  2306. auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
  2307. auto *GV = new llvm::GlobalVariable(
  2308. getModule(), Ty->getElementType(), false,
  2309. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  2310. llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
  2311. // If we already created a global with the same mangled name (but different
  2312. // type) before, take its name and remove it from its parent.
  2313. if (Entry) {
  2314. GV->takeName(Entry);
  2315. if (!Entry->use_empty()) {
  2316. llvm::Constant *NewPtrForOldDecl =
  2317. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2318. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2319. }
  2320. Entry->eraseFromParent();
  2321. }
  2322. // This is the first use or definition of a mangled name. If there is a
  2323. // deferred decl with this name, remember that we need to emit it at the end
  2324. // of the file.
  2325. auto DDI = DeferredDecls.find(MangledName);
  2326. if (DDI != DeferredDecls.end()) {
  2327. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  2328. // list, and remove it from DeferredDecls (since we don't need it anymore).
  2329. addDeferredDeclToEmit(DDI->second);
  2330. DeferredDecls.erase(DDI);
  2331. }
  2332. // Handle things which are present even on external declarations.
  2333. if (D) {
  2334. // FIXME: This code is overly simple and should be merged with other global
  2335. // handling.
  2336. GV->setConstant(isTypeConstant(D->getType(), false));
  2337. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2338. setLinkageForGV(GV, D);
  2339. setGVProperties(GV, D);
  2340. if (D->getTLSKind()) {
  2341. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2342. CXXThreadLocals.push_back(D);
  2343. setTLSMode(GV, *D);
  2344. }
  2345. // If required by the ABI, treat declarations of static data members with
  2346. // inline initializers as definitions.
  2347. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  2348. EmitGlobalVarDefinition(D);
  2349. }
  2350. // Emit section information for extern variables.
  2351. if (D->hasExternalStorage()) {
  2352. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  2353. GV->setSection(SA->getName());
  2354. }
  2355. // Handle XCore specific ABI requirements.
  2356. if (getTriple().getArch() == llvm::Triple::xcore &&
  2357. D->getLanguageLinkage() == CLanguageLinkage &&
  2358. D->getType().isConstant(Context) &&
  2359. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  2360. GV->setSection(".cp.rodata");
  2361. // Check if we a have a const declaration with an initializer, we may be
  2362. // able to emit it as available_externally to expose it's value to the
  2363. // optimizer.
  2364. if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
  2365. D->getType().isConstQualified() && !GV->hasInitializer() &&
  2366. !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
  2367. const auto *Record =
  2368. Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
  2369. bool HasMutableFields = Record && Record->hasMutableFields();
  2370. if (!HasMutableFields) {
  2371. const VarDecl *InitDecl;
  2372. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2373. if (InitExpr) {
  2374. ConstantEmitter emitter(*this);
  2375. llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
  2376. if (Init) {
  2377. auto *InitType = Init->getType();
  2378. if (GV->getType()->getElementType() != InitType) {
  2379. // The type of the initializer does not match the definition.
  2380. // This happens when an initializer has a different type from
  2381. // the type of the global (because of padding at the end of a
  2382. // structure for instance).
  2383. GV->setName(StringRef());
  2384. // Make a new global with the correct type, this is now guaranteed
  2385. // to work.
  2386. auto *NewGV = cast<llvm::GlobalVariable>(
  2387. GetAddrOfGlobalVar(D, InitType, IsForDefinition));
  2388. // Erase the old global, since it is no longer used.
  2389. cast<llvm::GlobalValue>(GV)->eraseFromParent();
  2390. GV = NewGV;
  2391. } else {
  2392. GV->setInitializer(Init);
  2393. GV->setConstant(true);
  2394. GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  2395. }
  2396. emitter.finalize(GV);
  2397. }
  2398. }
  2399. }
  2400. }
  2401. }
  2402. LangAS ExpectedAS =
  2403. D ? D->getType().getAddressSpace()
  2404. : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
  2405. assert(getContext().getTargetAddressSpace(ExpectedAS) ==
  2406. Ty->getPointerAddressSpace());
  2407. if (AddrSpace != ExpectedAS)
  2408. return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
  2409. ExpectedAS, Ty);
  2410. return GV;
  2411. }
  2412. llvm::Constant *
  2413. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  2414. ForDefinition_t IsForDefinition) {
  2415. const Decl *D = GD.getDecl();
  2416. if (isa<CXXConstructorDecl>(D))
  2417. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
  2418. getFromCtorType(GD.getCtorType()),
  2419. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2420. /*DontDefer=*/false, IsForDefinition);
  2421. else if (isa<CXXDestructorDecl>(D))
  2422. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
  2423. getFromDtorType(GD.getDtorType()),
  2424. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2425. /*DontDefer=*/false, IsForDefinition);
  2426. else if (isa<CXXMethodDecl>(D)) {
  2427. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  2428. cast<CXXMethodDecl>(D));
  2429. auto Ty = getTypes().GetFunctionType(*FInfo);
  2430. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2431. IsForDefinition);
  2432. } else if (isa<FunctionDecl>(D)) {
  2433. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2434. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2435. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2436. IsForDefinition);
  2437. } else
  2438. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
  2439. IsForDefinition);
  2440. }
  2441. llvm::GlobalVariable *
  2442. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  2443. llvm::Type *Ty,
  2444. llvm::GlobalValue::LinkageTypes Linkage) {
  2445. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  2446. llvm::GlobalVariable *OldGV = nullptr;
  2447. if (GV) {
  2448. // Check if the variable has the right type.
  2449. if (GV->getType()->getElementType() == Ty)
  2450. return GV;
  2451. // Because C++ name mangling, the only way we can end up with an already
  2452. // existing global with the same name is if it has been declared extern "C".
  2453. assert(GV->isDeclaration() && "Declaration has wrong type!");
  2454. OldGV = GV;
  2455. }
  2456. // Create a new variable.
  2457. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  2458. Linkage, nullptr, Name);
  2459. if (OldGV) {
  2460. // Replace occurrences of the old variable if needed.
  2461. GV->takeName(OldGV);
  2462. if (!OldGV->use_empty()) {
  2463. llvm::Constant *NewPtrForOldDecl =
  2464. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2465. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  2466. }
  2467. OldGV->eraseFromParent();
  2468. }
  2469. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  2470. !GV->hasAvailableExternallyLinkage())
  2471. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2472. return GV;
  2473. }
  2474. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  2475. /// given global variable. If Ty is non-null and if the global doesn't exist,
  2476. /// then it will be created with the specified type instead of whatever the
  2477. /// normal requested type would be. If IsForDefinition is true, it is guranteed
  2478. /// that an actual global with type Ty will be returned, not conversion of a
  2479. /// variable with the same mangled name but some other type.
  2480. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  2481. llvm::Type *Ty,
  2482. ForDefinition_t IsForDefinition) {
  2483. assert(D->hasGlobalStorage() && "Not a global variable");
  2484. QualType ASTTy = D->getType();
  2485. if (!Ty)
  2486. Ty = getTypes().ConvertTypeForMem(ASTTy);
  2487. llvm::PointerType *PTy =
  2488. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  2489. StringRef MangledName = getMangledName(D);
  2490. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  2491. }
  2492. /// CreateRuntimeVariable - Create a new runtime global variable with the
  2493. /// specified type and name.
  2494. llvm::Constant *
  2495. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  2496. StringRef Name) {
  2497. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  2498. }
  2499. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  2500. assert(!D->getInit() && "Cannot emit definite definitions here!");
  2501. StringRef MangledName = getMangledName(D);
  2502. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  2503. // We already have a definition, not declaration, with the same mangled name.
  2504. // Emitting of declaration is not required (and actually overwrites emitted
  2505. // definition).
  2506. if (GV && !GV->isDeclaration())
  2507. return;
  2508. // If we have not seen a reference to this variable yet, place it into the
  2509. // deferred declarations table to be emitted if needed later.
  2510. if (!MustBeEmitted(D) && !GV) {
  2511. DeferredDecls[MangledName] = D;
  2512. return;
  2513. }
  2514. // The tentative definition is the only definition.
  2515. EmitGlobalVarDefinition(D);
  2516. }
  2517. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  2518. return Context.toCharUnitsFromBits(
  2519. getDataLayout().getTypeStoreSizeInBits(Ty));
  2520. }
  2521. LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
  2522. LangAS AddrSpace = LangAS::Default;
  2523. if (LangOpts.OpenCL) {
  2524. AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
  2525. assert(AddrSpace == LangAS::opencl_global ||
  2526. AddrSpace == LangAS::opencl_constant ||
  2527. AddrSpace == LangAS::opencl_local ||
  2528. AddrSpace >= LangAS::FirstTargetAddressSpace);
  2529. return AddrSpace;
  2530. }
  2531. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  2532. if (D && D->hasAttr<CUDAConstantAttr>())
  2533. return LangAS::cuda_constant;
  2534. else if (D && D->hasAttr<CUDASharedAttr>())
  2535. return LangAS::cuda_shared;
  2536. else
  2537. return LangAS::cuda_device;
  2538. }
  2539. return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
  2540. }
  2541. template<typename SomeDecl>
  2542. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2543. llvm::GlobalValue *GV) {
  2544. if (!getLangOpts().CPlusPlus)
  2545. return;
  2546. // Must have 'used' attribute, or else inline assembly can't rely on
  2547. // the name existing.
  2548. if (!D->template hasAttr<UsedAttr>())
  2549. return;
  2550. // Must have internal linkage and an ordinary name.
  2551. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2552. return;
  2553. // Must be in an extern "C" context. Entities declared directly within
  2554. // a record are not extern "C" even if the record is in such a context.
  2555. const SomeDecl *First = D->getFirstDecl();
  2556. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2557. return;
  2558. // OK, this is an internal linkage entity inside an extern "C" linkage
  2559. // specification. Make a note of that so we can give it the "expected"
  2560. // mangled name if nothing else is using that name.
  2561. std::pair<StaticExternCMap::iterator, bool> R =
  2562. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2563. // If we have multiple internal linkage entities with the same name
  2564. // in extern "C" regions, none of them gets that name.
  2565. if (!R.second)
  2566. R.first->second = nullptr;
  2567. }
  2568. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2569. if (!CGM.supportsCOMDAT())
  2570. return false;
  2571. if (D.hasAttr<SelectAnyAttr>())
  2572. return true;
  2573. GVALinkage Linkage;
  2574. if (auto *VD = dyn_cast<VarDecl>(&D))
  2575. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  2576. else
  2577. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  2578. switch (Linkage) {
  2579. case GVA_Internal:
  2580. case GVA_AvailableExternally:
  2581. case GVA_StrongExternal:
  2582. return false;
  2583. case GVA_DiscardableODR:
  2584. case GVA_StrongODR:
  2585. return true;
  2586. }
  2587. llvm_unreachable("No such linkage");
  2588. }
  2589. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  2590. llvm::GlobalObject &GO) {
  2591. if (!shouldBeInCOMDAT(*this, D))
  2592. return;
  2593. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  2594. }
  2595. /// Pass IsTentative as true if you want to create a tentative definition.
  2596. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  2597. bool IsTentative) {
  2598. // OpenCL global variables of sampler type are translated to function calls,
  2599. // therefore no need to be translated.
  2600. QualType ASTTy = D->getType();
  2601. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  2602. return;
  2603. llvm::Constant *Init = nullptr;
  2604. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2605. bool NeedsGlobalCtor = false;
  2606. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  2607. const VarDecl *InitDecl;
  2608. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2609. Optional<ConstantEmitter> emitter;
  2610. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  2611. // as part of their declaration." Sema has already checked for
  2612. // error cases, so we just need to set Init to UndefValue.
  2613. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  2614. D->hasAttr<CUDASharedAttr>())
  2615. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  2616. else if (!InitExpr) {
  2617. // This is a tentative definition; tentative definitions are
  2618. // implicitly initialized with { 0 }.
  2619. //
  2620. // Note that tentative definitions are only emitted at the end of
  2621. // a translation unit, so they should never have incomplete
  2622. // type. In addition, EmitTentativeDefinition makes sure that we
  2623. // never attempt to emit a tentative definition if a real one
  2624. // exists. A use may still exists, however, so we still may need
  2625. // to do a RAUW.
  2626. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  2627. Init = EmitNullConstant(D->getType());
  2628. } else {
  2629. initializedGlobalDecl = GlobalDecl(D);
  2630. emitter.emplace(*this);
  2631. Init = emitter->tryEmitForInitializer(*InitDecl);
  2632. if (!Init) {
  2633. QualType T = InitExpr->getType();
  2634. if (D->getType()->isReferenceType())
  2635. T = D->getType();
  2636. if (getLangOpts().CPlusPlus) {
  2637. Init = EmitNullConstant(T);
  2638. NeedsGlobalCtor = true;
  2639. } else {
  2640. ErrorUnsupported(D, "static initializer");
  2641. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  2642. }
  2643. } else {
  2644. // We don't need an initializer, so remove the entry for the delayed
  2645. // initializer position (just in case this entry was delayed) if we
  2646. // also don't need to register a destructor.
  2647. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  2648. DelayedCXXInitPosition.erase(D);
  2649. }
  2650. }
  2651. llvm::Type* InitType = Init->getType();
  2652. llvm::Constant *Entry =
  2653. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  2654. // Strip off a bitcast if we got one back.
  2655. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2656. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  2657. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  2658. // All zero index gep.
  2659. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  2660. Entry = CE->getOperand(0);
  2661. }
  2662. // Entry is now either a Function or GlobalVariable.
  2663. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  2664. // We have a definition after a declaration with the wrong type.
  2665. // We must make a new GlobalVariable* and update everything that used OldGV
  2666. // (a declaration or tentative definition) with the new GlobalVariable*
  2667. // (which will be a definition).
  2668. //
  2669. // This happens if there is a prototype for a global (e.g.
  2670. // "extern int x[];") and then a definition of a different type (e.g.
  2671. // "int x[10];"). This also happens when an initializer has a different type
  2672. // from the type of the global (this happens with unions).
  2673. if (!GV || GV->getType()->getElementType() != InitType ||
  2674. GV->getType()->getAddressSpace() !=
  2675. getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
  2676. // Move the old entry aside so that we'll create a new one.
  2677. Entry->setName(StringRef());
  2678. // Make a new global with the correct type, this is now guaranteed to work.
  2679. GV = cast<llvm::GlobalVariable>(
  2680. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  2681. // Replace all uses of the old global with the new global
  2682. llvm::Constant *NewPtrForOldDecl =
  2683. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2684. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2685. // Erase the old global, since it is no longer used.
  2686. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  2687. }
  2688. MaybeHandleStaticInExternC(D, GV);
  2689. if (D->hasAttr<AnnotateAttr>())
  2690. AddGlobalAnnotations(D, GV);
  2691. // Set the llvm linkage type as appropriate.
  2692. llvm::GlobalValue::LinkageTypes Linkage =
  2693. getLLVMLinkageVarDefinition(D, GV->isConstant());
  2694. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  2695. // the device. [...]"
  2696. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  2697. // __device__, declares a variable that: [...]
  2698. // Is accessible from all the threads within the grid and from the host
  2699. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  2700. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  2701. if (GV && LangOpts.CUDA) {
  2702. if (LangOpts.CUDAIsDevice) {
  2703. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  2704. GV->setExternallyInitialized(true);
  2705. } else {
  2706. // Host-side shadows of external declarations of device-side
  2707. // global variables become internal definitions. These have to
  2708. // be internal in order to prevent name conflicts with global
  2709. // host variables with the same name in a different TUs.
  2710. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  2711. Linkage = llvm::GlobalValue::InternalLinkage;
  2712. // Shadow variables and their properties must be registered
  2713. // with CUDA runtime.
  2714. unsigned Flags = 0;
  2715. if (!D->hasDefinition())
  2716. Flags |= CGCUDARuntime::ExternDeviceVar;
  2717. if (D->hasAttr<CUDAConstantAttr>())
  2718. Flags |= CGCUDARuntime::ConstantDeviceVar;
  2719. getCUDARuntime().registerDeviceVar(*GV, Flags);
  2720. } else if (D->hasAttr<CUDASharedAttr>())
  2721. // __shared__ variables are odd. Shadows do get created, but
  2722. // they are not registered with the CUDA runtime, so they
  2723. // can't really be used to access their device-side
  2724. // counterparts. It's not clear yet whether it's nvcc's bug or
  2725. // a feature, but we've got to do the same for compatibility.
  2726. Linkage = llvm::GlobalValue::InternalLinkage;
  2727. }
  2728. }
  2729. GV->setInitializer(Init);
  2730. if (emitter) emitter->finalize(GV);
  2731. // If it is safe to mark the global 'constant', do so now.
  2732. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  2733. isTypeConstant(D->getType(), true));
  2734. // If it is in a read-only section, mark it 'constant'.
  2735. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  2736. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  2737. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  2738. GV->setConstant(true);
  2739. }
  2740. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2741. // On Darwin, if the normal linkage of a C++ thread_local variable is
  2742. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  2743. // copies within a linkage unit; otherwise, the backing variable has
  2744. // internal linkage and all accesses should just be calls to the
  2745. // Itanium-specified entry point, which has the normal linkage of the
  2746. // variable. This is to preserve the ability to change the implementation
  2747. // behind the scenes.
  2748. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  2749. Context.getTargetInfo().getTriple().isOSDarwin() &&
  2750. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  2751. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  2752. Linkage = llvm::GlobalValue::InternalLinkage;
  2753. GV->setLinkage(Linkage);
  2754. if (D->hasAttr<DLLImportAttr>())
  2755. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  2756. else if (D->hasAttr<DLLExportAttr>())
  2757. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  2758. else
  2759. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  2760. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  2761. // common vars aren't constant even if declared const.
  2762. GV->setConstant(false);
  2763. // Tentative definition of global variables may be initialized with
  2764. // non-zero null pointers. In this case they should have weak linkage
  2765. // since common linkage must have zero initializer and must not have
  2766. // explicit section therefore cannot have non-zero initial value.
  2767. if (!GV->getInitializer()->isNullValue())
  2768. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  2769. }
  2770. setNonAliasAttributes(D, GV);
  2771. if (D->getTLSKind() && !GV->isThreadLocal()) {
  2772. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2773. CXXThreadLocals.push_back(D);
  2774. setTLSMode(GV, *D);
  2775. }
  2776. maybeSetTrivialComdat(*D, *GV);
  2777. // Emit the initializer function if necessary.
  2778. if (NeedsGlobalCtor || NeedsGlobalDtor)
  2779. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  2780. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  2781. // Emit global variable debug information.
  2782. if (CGDebugInfo *DI = getModuleDebugInfo())
  2783. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  2784. DI->EmitGlobalVariable(GV, D);
  2785. }
  2786. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  2787. CodeGenModule &CGM, const VarDecl *D,
  2788. bool NoCommon) {
  2789. // Don't give variables common linkage if -fno-common was specified unless it
  2790. // was overridden by a NoCommon attribute.
  2791. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  2792. return true;
  2793. // C11 6.9.2/2:
  2794. // A declaration of an identifier for an object that has file scope without
  2795. // an initializer, and without a storage-class specifier or with the
  2796. // storage-class specifier static, constitutes a tentative definition.
  2797. if (D->getInit() || D->hasExternalStorage())
  2798. return true;
  2799. // A variable cannot be both common and exist in a section.
  2800. if (D->hasAttr<SectionAttr>())
  2801. return true;
  2802. // A variable cannot be both common and exist in a section.
  2803. // We dont try to determine which is the right section in the front-end.
  2804. // If no specialized section name is applicable, it will resort to default.
  2805. if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
  2806. D->hasAttr<PragmaClangDataSectionAttr>() ||
  2807. D->hasAttr<PragmaClangRodataSectionAttr>())
  2808. return true;
  2809. // Thread local vars aren't considered common linkage.
  2810. if (D->getTLSKind())
  2811. return true;
  2812. // Tentative definitions marked with WeakImportAttr are true definitions.
  2813. if (D->hasAttr<WeakImportAttr>())
  2814. return true;
  2815. // A variable cannot be both common and exist in a comdat.
  2816. if (shouldBeInCOMDAT(CGM, *D))
  2817. return true;
  2818. // Declarations with a required alignment do not have common linkage in MSVC
  2819. // mode.
  2820. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2821. if (D->hasAttr<AlignedAttr>())
  2822. return true;
  2823. QualType VarType = D->getType();
  2824. if (Context.isAlignmentRequired(VarType))
  2825. return true;
  2826. if (const auto *RT = VarType->getAs<RecordType>()) {
  2827. const RecordDecl *RD = RT->getDecl();
  2828. for (const FieldDecl *FD : RD->fields()) {
  2829. if (FD->isBitField())
  2830. continue;
  2831. if (FD->hasAttr<AlignedAttr>())
  2832. return true;
  2833. if (Context.isAlignmentRequired(FD->getType()))
  2834. return true;
  2835. }
  2836. }
  2837. }
  2838. return false;
  2839. }
  2840. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  2841. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  2842. if (Linkage == GVA_Internal)
  2843. return llvm::Function::InternalLinkage;
  2844. if (D->hasAttr<WeakAttr>()) {
  2845. if (IsConstantVariable)
  2846. return llvm::GlobalVariable::WeakODRLinkage;
  2847. else
  2848. return llvm::GlobalVariable::WeakAnyLinkage;
  2849. }
  2850. // We are guaranteed to have a strong definition somewhere else,
  2851. // so we can use available_externally linkage.
  2852. if (Linkage == GVA_AvailableExternally)
  2853. return llvm::GlobalValue::AvailableExternallyLinkage;
  2854. // Note that Apple's kernel linker doesn't support symbol
  2855. // coalescing, so we need to avoid linkonce and weak linkages there.
  2856. // Normally, this means we just map to internal, but for explicit
  2857. // instantiations we'll map to external.
  2858. // In C++, the compiler has to emit a definition in every translation unit
  2859. // that references the function. We should use linkonce_odr because
  2860. // a) if all references in this translation unit are optimized away, we
  2861. // don't need to codegen it. b) if the function persists, it needs to be
  2862. // merged with other definitions. c) C++ has the ODR, so we know the
  2863. // definition is dependable.
  2864. if (Linkage == GVA_DiscardableODR)
  2865. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2866. : llvm::Function::InternalLinkage;
  2867. // An explicit instantiation of a template has weak linkage, since
  2868. // explicit instantiations can occur in multiple translation units
  2869. // and must all be equivalent. However, we are not allowed to
  2870. // throw away these explicit instantiations.
  2871. //
  2872. // We don't currently support CUDA device code spread out across multiple TUs,
  2873. // so say that CUDA templates are either external (for kernels) or internal.
  2874. // This lets llvm perform aggressive inter-procedural optimizations.
  2875. if (Linkage == GVA_StrongODR) {
  2876. if (Context.getLangOpts().AppleKext)
  2877. return llvm::Function::ExternalLinkage;
  2878. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  2879. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  2880. : llvm::Function::InternalLinkage;
  2881. return llvm::Function::WeakODRLinkage;
  2882. }
  2883. // C++ doesn't have tentative definitions and thus cannot have common
  2884. // linkage.
  2885. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2886. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2887. CodeGenOpts.NoCommon))
  2888. return llvm::GlobalVariable::CommonLinkage;
  2889. // selectany symbols are externally visible, so use weak instead of
  2890. // linkonce. MSVC optimizes away references to const selectany globals, so
  2891. // all definitions should be the same and ODR linkage should be used.
  2892. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2893. if (D->hasAttr<SelectAnyAttr>())
  2894. return llvm::GlobalVariable::WeakODRLinkage;
  2895. // Otherwise, we have strong external linkage.
  2896. assert(Linkage == GVA_StrongExternal);
  2897. return llvm::GlobalVariable::ExternalLinkage;
  2898. }
  2899. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2900. const VarDecl *VD, bool IsConstant) {
  2901. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2902. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2903. }
  2904. /// Replace the uses of a function that was declared with a non-proto type.
  2905. /// We want to silently drop extra arguments from call sites
  2906. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2907. llvm::Function *newFn) {
  2908. // Fast path.
  2909. if (old->use_empty()) return;
  2910. llvm::Type *newRetTy = newFn->getReturnType();
  2911. SmallVector<llvm::Value*, 4> newArgs;
  2912. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  2913. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2914. ui != ue; ) {
  2915. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2916. llvm::User *user = use->getUser();
  2917. // Recognize and replace uses of bitcasts. Most calls to
  2918. // unprototyped functions will use bitcasts.
  2919. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2920. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2921. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2922. continue;
  2923. }
  2924. // Recognize calls to the function.
  2925. llvm::CallSite callSite(user);
  2926. if (!callSite) continue;
  2927. if (!callSite.isCallee(&*use)) continue;
  2928. // If the return types don't match exactly, then we can't
  2929. // transform this call unless it's dead.
  2930. if (callSite->getType() != newRetTy && !callSite->use_empty())
  2931. continue;
  2932. // Get the call site's attribute list.
  2933. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  2934. llvm::AttributeList oldAttrs = callSite.getAttributes();
  2935. // If the function was passed too few arguments, don't transform.
  2936. unsigned newNumArgs = newFn->arg_size();
  2937. if (callSite.arg_size() < newNumArgs) continue;
  2938. // If extra arguments were passed, we silently drop them.
  2939. // If any of the types mismatch, we don't transform.
  2940. unsigned argNo = 0;
  2941. bool dontTransform = false;
  2942. for (llvm::Argument &A : newFn->args()) {
  2943. if (callSite.getArgument(argNo)->getType() != A.getType()) {
  2944. dontTransform = true;
  2945. break;
  2946. }
  2947. // Add any parameter attributes.
  2948. newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
  2949. argNo++;
  2950. }
  2951. if (dontTransform)
  2952. continue;
  2953. // Okay, we can transform this. Create the new call instruction and copy
  2954. // over the required information.
  2955. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  2956. // Copy over any operand bundles.
  2957. callSite.getOperandBundlesAsDefs(newBundles);
  2958. llvm::CallSite newCall;
  2959. if (callSite.isCall()) {
  2960. newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
  2961. callSite.getInstruction());
  2962. } else {
  2963. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  2964. newCall = llvm::InvokeInst::Create(newFn,
  2965. oldInvoke->getNormalDest(),
  2966. oldInvoke->getUnwindDest(),
  2967. newArgs, newBundles, "",
  2968. callSite.getInstruction());
  2969. }
  2970. newArgs.clear(); // for the next iteration
  2971. if (!newCall->getType()->isVoidTy())
  2972. newCall->takeName(callSite.getInstruction());
  2973. newCall.setAttributes(llvm::AttributeList::get(
  2974. newFn->getContext(), oldAttrs.getFnAttributes(),
  2975. oldAttrs.getRetAttributes(), newArgAttrs));
  2976. newCall.setCallingConv(callSite.getCallingConv());
  2977. // Finally, remove the old call, replacing any uses with the new one.
  2978. if (!callSite->use_empty())
  2979. callSite->replaceAllUsesWith(newCall.getInstruction());
  2980. // Copy debug location attached to CI.
  2981. if (callSite->getDebugLoc())
  2982. newCall->setDebugLoc(callSite->getDebugLoc());
  2983. callSite->eraseFromParent();
  2984. }
  2985. }
  2986. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  2987. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  2988. /// existing call uses of the old function in the module, this adjusts them to
  2989. /// call the new function directly.
  2990. ///
  2991. /// This is not just a cleanup: the always_inline pass requires direct calls to
  2992. /// functions to be able to inline them. If there is a bitcast in the way, it
  2993. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  2994. /// run at -O0.
  2995. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2996. llvm::Function *NewFn) {
  2997. // If we're redefining a global as a function, don't transform it.
  2998. if (!isa<llvm::Function>(Old)) return;
  2999. replaceUsesOfNonProtoConstant(Old, NewFn);
  3000. }
  3001. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  3002. auto DK = VD->isThisDeclarationADefinition();
  3003. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  3004. return;
  3005. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  3006. // If we have a definition, this might be a deferred decl. If the
  3007. // instantiation is explicit, make sure we emit it at the end.
  3008. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  3009. GetAddrOfGlobalVar(VD);
  3010. EmitTopLevelDecl(VD);
  3011. }
  3012. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  3013. llvm::GlobalValue *GV) {
  3014. const auto *D = cast<FunctionDecl>(GD.getDecl());
  3015. // Compute the function info and LLVM type.
  3016. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  3017. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  3018. // Get or create the prototype for the function.
  3019. if (!GV || (GV->getType()->getElementType() != Ty))
  3020. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  3021. /*DontDefer=*/true,
  3022. ForDefinition));
  3023. // Already emitted.
  3024. if (!GV->isDeclaration())
  3025. return;
  3026. // We need to set linkage and visibility on the function before
  3027. // generating code for it because various parts of IR generation
  3028. // want to propagate this information down (e.g. to local static
  3029. // declarations).
  3030. auto *Fn = cast<llvm::Function>(GV);
  3031. setFunctionLinkage(GD, Fn);
  3032. setFunctionDLLStorageClass(GD, Fn);
  3033. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  3034. setGVProperties(Fn, D);
  3035. MaybeHandleStaticInExternC(D, Fn);
  3036. maybeSetTrivialComdat(*D, *Fn);
  3037. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  3038. setFunctionDefinitionAttributes(D, Fn);
  3039. SetLLVMFunctionAttributesForDefinition(D, Fn);
  3040. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  3041. AddGlobalCtor(Fn, CA->getPriority());
  3042. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  3043. AddGlobalDtor(Fn, DA->getPriority());
  3044. if (D->hasAttr<AnnotateAttr>())
  3045. AddGlobalAnnotations(D, Fn);
  3046. }
  3047. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  3048. const auto *D = cast<ValueDecl>(GD.getDecl());
  3049. const AliasAttr *AA = D->getAttr<AliasAttr>();
  3050. assert(AA && "Not an alias?");
  3051. StringRef MangledName = getMangledName(GD);
  3052. if (AA->getAliasee() == MangledName) {
  3053. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3054. return;
  3055. }
  3056. // If there is a definition in the module, then it wins over the alias.
  3057. // This is dubious, but allow it to be safe. Just ignore the alias.
  3058. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3059. if (Entry && !Entry->isDeclaration())
  3060. return;
  3061. Aliases.push_back(GD);
  3062. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3063. // Create a reference to the named value. This ensures that it is emitted
  3064. // if a deferred decl.
  3065. llvm::Constant *Aliasee;
  3066. if (isa<llvm::FunctionType>(DeclTy))
  3067. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  3068. /*ForVTable=*/false);
  3069. else
  3070. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  3071. llvm::PointerType::getUnqual(DeclTy),
  3072. /*D=*/nullptr);
  3073. // Create the new alias itself, but don't set a name yet.
  3074. auto *GA = llvm::GlobalAlias::create(
  3075. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  3076. if (Entry) {
  3077. if (GA->getAliasee() == Entry) {
  3078. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3079. return;
  3080. }
  3081. assert(Entry->isDeclaration());
  3082. // If there is a declaration in the module, then we had an extern followed
  3083. // by the alias, as in:
  3084. // extern int test6();
  3085. // ...
  3086. // int test6() __attribute__((alias("test7")));
  3087. //
  3088. // Remove it and replace uses of it with the alias.
  3089. GA->takeName(Entry);
  3090. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  3091. Entry->getType()));
  3092. Entry->eraseFromParent();
  3093. } else {
  3094. GA->setName(MangledName);
  3095. }
  3096. // Set attributes which are particular to an alias; this is a
  3097. // specialization of the attributes which may be set on a global
  3098. // variable/function.
  3099. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  3100. D->isWeakImported()) {
  3101. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  3102. }
  3103. if (const auto *VD = dyn_cast<VarDecl>(D))
  3104. if (VD->getTLSKind())
  3105. setTLSMode(GA, *VD);
  3106. setAliasAttributes(D, GA);
  3107. }
  3108. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  3109. const auto *D = cast<ValueDecl>(GD.getDecl());
  3110. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  3111. assert(IFA && "Not an ifunc?");
  3112. StringRef MangledName = getMangledName(GD);
  3113. if (IFA->getResolver() == MangledName) {
  3114. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3115. return;
  3116. }
  3117. // Report an error if some definition overrides ifunc.
  3118. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3119. if (Entry && !Entry->isDeclaration()) {
  3120. GlobalDecl OtherGD;
  3121. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  3122. DiagnosedConflictingDefinitions.insert(GD).second) {
  3123. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
  3124. Diags.Report(OtherGD.getDecl()->getLocation(),
  3125. diag::note_previous_definition);
  3126. }
  3127. return;
  3128. }
  3129. Aliases.push_back(GD);
  3130. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3131. llvm::Constant *Resolver =
  3132. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  3133. /*ForVTable=*/false);
  3134. llvm::GlobalIFunc *GIF =
  3135. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  3136. "", Resolver, &getModule());
  3137. if (Entry) {
  3138. if (GIF->getResolver() == Entry) {
  3139. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3140. return;
  3141. }
  3142. assert(Entry->isDeclaration());
  3143. // If there is a declaration in the module, then we had an extern followed
  3144. // by the ifunc, as in:
  3145. // extern int test();
  3146. // ...
  3147. // int test() __attribute__((ifunc("resolver")));
  3148. //
  3149. // Remove it and replace uses of it with the ifunc.
  3150. GIF->takeName(Entry);
  3151. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  3152. Entry->getType()));
  3153. Entry->eraseFromParent();
  3154. } else
  3155. GIF->setName(MangledName);
  3156. SetCommonAttributes(D, GIF);
  3157. }
  3158. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  3159. ArrayRef<llvm::Type*> Tys) {
  3160. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  3161. Tys);
  3162. }
  3163. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  3164. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  3165. const StringLiteral *Literal, bool TargetIsLSB,
  3166. bool &IsUTF16, unsigned &StringLength) {
  3167. StringRef String = Literal->getString();
  3168. unsigned NumBytes = String.size();
  3169. // Check for simple case.
  3170. if (!Literal->containsNonAsciiOrNull()) {
  3171. StringLength = NumBytes;
  3172. return *Map.insert(std::make_pair(String, nullptr)).first;
  3173. }
  3174. // Otherwise, convert the UTF8 literals into a string of shorts.
  3175. IsUTF16 = true;
  3176. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  3177. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3178. llvm::UTF16 *ToPtr = &ToBuf[0];
  3179. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3180. ToPtr + NumBytes, llvm::strictConversion);
  3181. // ConvertUTF8toUTF16 returns the length in ToPtr.
  3182. StringLength = ToPtr - &ToBuf[0];
  3183. // Add an explicit null.
  3184. *ToPtr = 0;
  3185. return *Map.insert(std::make_pair(
  3186. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  3187. (StringLength + 1) * 2),
  3188. nullptr)).first;
  3189. }
  3190. ConstantAddress
  3191. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  3192. unsigned StringLength = 0;
  3193. bool isUTF16 = false;
  3194. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  3195. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  3196. getDataLayout().isLittleEndian(), isUTF16,
  3197. StringLength);
  3198. if (auto *C = Entry.second)
  3199. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  3200. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  3201. llvm::Constant *Zeros[] = { Zero, Zero };
  3202. // If we don't already have it, get __CFConstantStringClassReference.
  3203. if (!CFConstantStringClassRef) {
  3204. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  3205. Ty = llvm::ArrayType::get(Ty, 0);
  3206. llvm::Constant *GV =
  3207. CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
  3208. if (getTriple().isOSBinFormatCOFF()) {
  3209. IdentifierInfo &II = getContext().Idents.get(GV->getName());
  3210. TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
  3211. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  3212. llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
  3213. const VarDecl *VD = nullptr;
  3214. for (const auto &Result : DC->lookup(&II))
  3215. if ((VD = dyn_cast<VarDecl>(Result)))
  3216. break;
  3217. if (!VD || !VD->hasAttr<DLLExportAttr>()) {
  3218. CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  3219. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3220. } else {
  3221. CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  3222. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3223. }
  3224. }
  3225. // Decay array -> ptr
  3226. CFConstantStringClassRef =
  3227. llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  3228. }
  3229. QualType CFTy = getContext().getCFConstantStringType();
  3230. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  3231. ConstantInitBuilder Builder(*this);
  3232. auto Fields = Builder.beginStruct(STy);
  3233. // Class pointer.
  3234. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  3235. // Flags.
  3236. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  3237. // String pointer.
  3238. llvm::Constant *C = nullptr;
  3239. if (isUTF16) {
  3240. auto Arr = llvm::makeArrayRef(
  3241. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  3242. Entry.first().size() / 2);
  3243. C = llvm::ConstantDataArray::get(VMContext, Arr);
  3244. } else {
  3245. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  3246. }
  3247. // Note: -fwritable-strings doesn't make the backing store strings of
  3248. // CFStrings writable. (See <rdar://problem/10657500>)
  3249. auto *GV =
  3250. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  3251. llvm::GlobalValue::PrivateLinkage, C, ".str");
  3252. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3253. // Don't enforce the target's minimum global alignment, since the only use
  3254. // of the string is via this class initializer.
  3255. CharUnits Align = isUTF16
  3256. ? getContext().getTypeAlignInChars(getContext().ShortTy)
  3257. : getContext().getTypeAlignInChars(getContext().CharTy);
  3258. GV->setAlignment(Align.getQuantity());
  3259. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  3260. // Without it LLVM can merge the string with a non unnamed_addr one during
  3261. // LTO. Doing that changes the section it ends in, which surprises ld64.
  3262. if (getTriple().isOSBinFormatMachO())
  3263. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  3264. : "__TEXT,__cstring,cstring_literals");
  3265. // String.
  3266. llvm::Constant *Str =
  3267. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  3268. if (isUTF16)
  3269. // Cast the UTF16 string to the correct type.
  3270. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  3271. Fields.add(Str);
  3272. // String length.
  3273. auto Ty = getTypes().ConvertType(getContext().LongTy);
  3274. Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
  3275. CharUnits Alignment = getPointerAlign();
  3276. // The struct.
  3277. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  3278. /*isConstant=*/false,
  3279. llvm::GlobalVariable::PrivateLinkage);
  3280. switch (getTriple().getObjectFormat()) {
  3281. case llvm::Triple::UnknownObjectFormat:
  3282. llvm_unreachable("unknown file format");
  3283. case llvm::Triple::COFF:
  3284. case llvm::Triple::ELF:
  3285. case llvm::Triple::Wasm:
  3286. GV->setSection("cfstring");
  3287. break;
  3288. case llvm::Triple::MachO:
  3289. GV->setSection("__DATA,__cfstring");
  3290. break;
  3291. }
  3292. Entry.second = GV;
  3293. return ConstantAddress(GV, Alignment);
  3294. }
  3295. bool CodeGenModule::getExpressionLocationsEnabled() const {
  3296. return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
  3297. }
  3298. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  3299. if (ObjCFastEnumerationStateType.isNull()) {
  3300. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  3301. D->startDefinition();
  3302. QualType FieldTypes[] = {
  3303. Context.UnsignedLongTy,
  3304. Context.getPointerType(Context.getObjCIdType()),
  3305. Context.getPointerType(Context.UnsignedLongTy),
  3306. Context.getConstantArrayType(Context.UnsignedLongTy,
  3307. llvm::APInt(32, 5), ArrayType::Normal, 0)
  3308. };
  3309. for (size_t i = 0; i < 4; ++i) {
  3310. FieldDecl *Field = FieldDecl::Create(Context,
  3311. D,
  3312. SourceLocation(),
  3313. SourceLocation(), nullptr,
  3314. FieldTypes[i], /*TInfo=*/nullptr,
  3315. /*BitWidth=*/nullptr,
  3316. /*Mutable=*/false,
  3317. ICIS_NoInit);
  3318. Field->setAccess(AS_public);
  3319. D->addDecl(Field);
  3320. }
  3321. D->completeDefinition();
  3322. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  3323. }
  3324. return ObjCFastEnumerationStateType;
  3325. }
  3326. llvm::Constant *
  3327. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  3328. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  3329. // Don't emit it as the address of the string, emit the string data itself
  3330. // as an inline array.
  3331. if (E->getCharByteWidth() == 1) {
  3332. SmallString<64> Str(E->getString());
  3333. // Resize the string to the right size, which is indicated by its type.
  3334. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  3335. Str.resize(CAT->getSize().getZExtValue());
  3336. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  3337. }
  3338. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  3339. llvm::Type *ElemTy = AType->getElementType();
  3340. unsigned NumElements = AType->getNumElements();
  3341. // Wide strings have either 2-byte or 4-byte elements.
  3342. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  3343. SmallVector<uint16_t, 32> Elements;
  3344. Elements.reserve(NumElements);
  3345. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3346. Elements.push_back(E->getCodeUnit(i));
  3347. Elements.resize(NumElements);
  3348. return llvm::ConstantDataArray::get(VMContext, Elements);
  3349. }
  3350. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  3351. SmallVector<uint32_t, 32> Elements;
  3352. Elements.reserve(NumElements);
  3353. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3354. Elements.push_back(E->getCodeUnit(i));
  3355. Elements.resize(NumElements);
  3356. return llvm::ConstantDataArray::get(VMContext, Elements);
  3357. }
  3358. static llvm::GlobalVariable *
  3359. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  3360. CodeGenModule &CGM, StringRef GlobalName,
  3361. CharUnits Alignment) {
  3362. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  3363. unsigned AddrSpace = 0;
  3364. if (CGM.getLangOpts().OpenCL)
  3365. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  3366. llvm::Module &M = CGM.getModule();
  3367. // Create a global variable for this string
  3368. auto *GV = new llvm::GlobalVariable(
  3369. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  3370. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  3371. GV->setAlignment(Alignment.getQuantity());
  3372. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3373. if (GV->isWeakForLinker()) {
  3374. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  3375. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  3376. }
  3377. return GV;
  3378. }
  3379. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  3380. /// constant array for the given string literal.
  3381. ConstantAddress
  3382. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  3383. StringRef Name) {
  3384. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  3385. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  3386. llvm::GlobalVariable **Entry = nullptr;
  3387. if (!LangOpts.WritableStrings) {
  3388. Entry = &ConstantStringMap[C];
  3389. if (auto GV = *Entry) {
  3390. if (Alignment.getQuantity() > GV->getAlignment())
  3391. GV->setAlignment(Alignment.getQuantity());
  3392. return ConstantAddress(GV, Alignment);
  3393. }
  3394. }
  3395. SmallString<256> MangledNameBuffer;
  3396. StringRef GlobalVariableName;
  3397. llvm::GlobalValue::LinkageTypes LT;
  3398. // Mangle the string literal if the ABI allows for it. However, we cannot
  3399. // do this if we are compiling with ASan or -fwritable-strings because they
  3400. // rely on strings having normal linkage.
  3401. if (!LangOpts.WritableStrings &&
  3402. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  3403. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  3404. llvm::raw_svector_ostream Out(MangledNameBuffer);
  3405. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  3406. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  3407. GlobalVariableName = MangledNameBuffer;
  3408. } else {
  3409. LT = llvm::GlobalValue::PrivateLinkage;
  3410. GlobalVariableName = Name;
  3411. }
  3412. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  3413. if (Entry)
  3414. *Entry = GV;
  3415. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  3416. QualType());
  3417. return ConstantAddress(GV, Alignment);
  3418. }
  3419. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  3420. /// array for the given ObjCEncodeExpr node.
  3421. ConstantAddress
  3422. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  3423. std::string Str;
  3424. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  3425. return GetAddrOfConstantCString(Str);
  3426. }
  3427. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  3428. /// the literal and a terminating '\0' character.
  3429. /// The result has pointer to array type.
  3430. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  3431. const std::string &Str, const char *GlobalName) {
  3432. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  3433. CharUnits Alignment =
  3434. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  3435. llvm::Constant *C =
  3436. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  3437. // Don't share any string literals if strings aren't constant.
  3438. llvm::GlobalVariable **Entry = nullptr;
  3439. if (!LangOpts.WritableStrings) {
  3440. Entry = &ConstantStringMap[C];
  3441. if (auto GV = *Entry) {
  3442. if (Alignment.getQuantity() > GV->getAlignment())
  3443. GV->setAlignment(Alignment.getQuantity());
  3444. return ConstantAddress(GV, Alignment);
  3445. }
  3446. }
  3447. // Get the default prefix if a name wasn't specified.
  3448. if (!GlobalName)
  3449. GlobalName = ".str";
  3450. // Create a global variable for this.
  3451. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  3452. GlobalName, Alignment);
  3453. if (Entry)
  3454. *Entry = GV;
  3455. return ConstantAddress(GV, Alignment);
  3456. }
  3457. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  3458. const MaterializeTemporaryExpr *E, const Expr *Init) {
  3459. assert((E->getStorageDuration() == SD_Static ||
  3460. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  3461. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  3462. // If we're not materializing a subobject of the temporary, keep the
  3463. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  3464. QualType MaterializedType = Init->getType();
  3465. if (Init == E->GetTemporaryExpr())
  3466. MaterializedType = E->getType();
  3467. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  3468. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  3469. return ConstantAddress(Slot, Align);
  3470. // FIXME: If an externally-visible declaration extends multiple temporaries,
  3471. // we need to give each temporary the same name in every translation unit (and
  3472. // we also need to make the temporaries externally-visible).
  3473. SmallString<256> Name;
  3474. llvm::raw_svector_ostream Out(Name);
  3475. getCXXABI().getMangleContext().mangleReferenceTemporary(
  3476. VD, E->getManglingNumber(), Out);
  3477. APValue *Value = nullptr;
  3478. if (E->getStorageDuration() == SD_Static) {
  3479. // We might have a cached constant initializer for this temporary. Note
  3480. // that this might have a different value from the value computed by
  3481. // evaluating the initializer if the surrounding constant expression
  3482. // modifies the temporary.
  3483. Value = getContext().getMaterializedTemporaryValue(E, false);
  3484. if (Value && Value->isUninit())
  3485. Value = nullptr;
  3486. }
  3487. // Try evaluating it now, it might have a constant initializer.
  3488. Expr::EvalResult EvalResult;
  3489. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  3490. !EvalResult.hasSideEffects())
  3491. Value = &EvalResult.Val;
  3492. LangAS AddrSpace =
  3493. VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
  3494. Optional<ConstantEmitter> emitter;
  3495. llvm::Constant *InitialValue = nullptr;
  3496. bool Constant = false;
  3497. llvm::Type *Type;
  3498. if (Value) {
  3499. // The temporary has a constant initializer, use it.
  3500. emitter.emplace(*this);
  3501. InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
  3502. MaterializedType);
  3503. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  3504. Type = InitialValue->getType();
  3505. } else {
  3506. // No initializer, the initialization will be provided when we
  3507. // initialize the declaration which performed lifetime extension.
  3508. Type = getTypes().ConvertTypeForMem(MaterializedType);
  3509. }
  3510. // Create a global variable for this lifetime-extended temporary.
  3511. llvm::GlobalValue::LinkageTypes Linkage =
  3512. getLLVMLinkageVarDefinition(VD, Constant);
  3513. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  3514. const VarDecl *InitVD;
  3515. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  3516. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  3517. // Temporaries defined inside a class get linkonce_odr linkage because the
  3518. // class can be defined in multipe translation units.
  3519. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  3520. } else {
  3521. // There is no need for this temporary to have external linkage if the
  3522. // VarDecl has external linkage.
  3523. Linkage = llvm::GlobalVariable::InternalLinkage;
  3524. }
  3525. }
  3526. auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  3527. auto *GV = new llvm::GlobalVariable(
  3528. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  3529. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  3530. if (emitter) emitter->finalize(GV);
  3531. setGVProperties(GV, VD);
  3532. GV->setAlignment(Align.getQuantity());
  3533. if (supportsCOMDAT() && GV->isWeakForLinker())
  3534. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3535. if (VD->getTLSKind())
  3536. setTLSMode(GV, *VD);
  3537. llvm::Constant *CV = GV;
  3538. if (AddrSpace != LangAS::Default)
  3539. CV = getTargetCodeGenInfo().performAddrSpaceCast(
  3540. *this, GV, AddrSpace, LangAS::Default,
  3541. Type->getPointerTo(
  3542. getContext().getTargetAddressSpace(LangAS::Default)));
  3543. MaterializedGlobalTemporaryMap[E] = CV;
  3544. return ConstantAddress(CV, Align);
  3545. }
  3546. /// EmitObjCPropertyImplementations - Emit information for synthesized
  3547. /// properties for an implementation.
  3548. void CodeGenModule::EmitObjCPropertyImplementations(const
  3549. ObjCImplementationDecl *D) {
  3550. for (const auto *PID : D->property_impls()) {
  3551. // Dynamic is just for type-checking.
  3552. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  3553. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3554. // Determine which methods need to be implemented, some may have
  3555. // been overridden. Note that ::isPropertyAccessor is not the method
  3556. // we want, that just indicates if the decl came from a
  3557. // property. What we want to know is if the method is defined in
  3558. // this implementation.
  3559. if (!D->getInstanceMethod(PD->getGetterName()))
  3560. CodeGenFunction(*this).GenerateObjCGetter(
  3561. const_cast<ObjCImplementationDecl *>(D), PID);
  3562. if (!PD->isReadOnly() &&
  3563. !D->getInstanceMethod(PD->getSetterName()))
  3564. CodeGenFunction(*this).GenerateObjCSetter(
  3565. const_cast<ObjCImplementationDecl *>(D), PID);
  3566. }
  3567. }
  3568. }
  3569. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  3570. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  3571. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  3572. ivar; ivar = ivar->getNextIvar())
  3573. if (ivar->getType().isDestructedType())
  3574. return true;
  3575. return false;
  3576. }
  3577. static bool AllTrivialInitializers(CodeGenModule &CGM,
  3578. ObjCImplementationDecl *D) {
  3579. CodeGenFunction CGF(CGM);
  3580. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  3581. E = D->init_end(); B != E; ++B) {
  3582. CXXCtorInitializer *CtorInitExp = *B;
  3583. Expr *Init = CtorInitExp->getInit();
  3584. if (!CGF.isTrivialInitializer(Init))
  3585. return false;
  3586. }
  3587. return true;
  3588. }
  3589. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  3590. /// for an implementation.
  3591. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  3592. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  3593. if (needsDestructMethod(D)) {
  3594. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  3595. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3596. ObjCMethodDecl *DTORMethod =
  3597. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  3598. cxxSelector, getContext().VoidTy, nullptr, D,
  3599. /*isInstance=*/true, /*isVariadic=*/false,
  3600. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  3601. /*isDefined=*/false, ObjCMethodDecl::Required);
  3602. D->addInstanceMethod(DTORMethod);
  3603. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  3604. D->setHasDestructors(true);
  3605. }
  3606. // If the implementation doesn't have any ivar initializers, we don't need
  3607. // a .cxx_construct.
  3608. if (D->getNumIvarInitializers() == 0 ||
  3609. AllTrivialInitializers(*this, D))
  3610. return;
  3611. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  3612. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3613. // The constructor returns 'self'.
  3614. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  3615. D->getLocation(),
  3616. D->getLocation(),
  3617. cxxSelector,
  3618. getContext().getObjCIdType(),
  3619. nullptr, D, /*isInstance=*/true,
  3620. /*isVariadic=*/false,
  3621. /*isPropertyAccessor=*/true,
  3622. /*isImplicitlyDeclared=*/true,
  3623. /*isDefined=*/false,
  3624. ObjCMethodDecl::Required);
  3625. D->addInstanceMethod(CTORMethod);
  3626. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  3627. D->setHasNonZeroConstructors(true);
  3628. }
  3629. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  3630. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  3631. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  3632. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  3633. ErrorUnsupported(LSD, "linkage spec");
  3634. return;
  3635. }
  3636. EmitDeclContext(LSD);
  3637. }
  3638. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  3639. for (auto *I : DC->decls()) {
  3640. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  3641. // are themselves considered "top-level", so EmitTopLevelDecl on an
  3642. // ObjCImplDecl does not recursively visit them. We need to do that in
  3643. // case they're nested inside another construct (LinkageSpecDecl /
  3644. // ExportDecl) that does stop them from being considered "top-level".
  3645. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  3646. for (auto *M : OID->methods())
  3647. EmitTopLevelDecl(M);
  3648. }
  3649. EmitTopLevelDecl(I);
  3650. }
  3651. }
  3652. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  3653. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  3654. // Ignore dependent declarations.
  3655. if (D->isTemplated())
  3656. return;
  3657. switch (D->getKind()) {
  3658. case Decl::CXXConversion:
  3659. case Decl::CXXMethod:
  3660. case Decl::Function:
  3661. EmitGlobal(cast<FunctionDecl>(D));
  3662. // Always provide some coverage mapping
  3663. // even for the functions that aren't emitted.
  3664. AddDeferredUnusedCoverageMapping(D);
  3665. break;
  3666. case Decl::CXXDeductionGuide:
  3667. // Function-like, but does not result in code emission.
  3668. break;
  3669. case Decl::Var:
  3670. case Decl::Decomposition:
  3671. case Decl::VarTemplateSpecialization:
  3672. EmitGlobal(cast<VarDecl>(D));
  3673. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  3674. for (auto *B : DD->bindings())
  3675. if (auto *HD = B->getHoldingVar())
  3676. EmitGlobal(HD);
  3677. break;
  3678. // Indirect fields from global anonymous structs and unions can be
  3679. // ignored; only the actual variable requires IR gen support.
  3680. case Decl::IndirectField:
  3681. break;
  3682. // C++ Decls
  3683. case Decl::Namespace:
  3684. EmitDeclContext(cast<NamespaceDecl>(D));
  3685. break;
  3686. case Decl::ClassTemplateSpecialization: {
  3687. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3688. if (DebugInfo &&
  3689. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3690. Spec->hasDefinition())
  3691. DebugInfo->completeTemplateDefinition(*Spec);
  3692. } LLVM_FALLTHROUGH;
  3693. case Decl::CXXRecord:
  3694. if (DebugInfo) {
  3695. if (auto *ES = D->getASTContext().getExternalSource())
  3696. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  3697. DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
  3698. }
  3699. // Emit any static data members, they may be definitions.
  3700. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  3701. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  3702. EmitTopLevelDecl(I);
  3703. break;
  3704. // No code generation needed.
  3705. case Decl::UsingShadow:
  3706. case Decl::ClassTemplate:
  3707. case Decl::VarTemplate:
  3708. case Decl::VarTemplatePartialSpecialization:
  3709. case Decl::FunctionTemplate:
  3710. case Decl::TypeAliasTemplate:
  3711. case Decl::Block:
  3712. case Decl::Empty:
  3713. break;
  3714. case Decl::Using: // using X; [C++]
  3715. if (CGDebugInfo *DI = getModuleDebugInfo())
  3716. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  3717. return;
  3718. case Decl::NamespaceAlias:
  3719. if (CGDebugInfo *DI = getModuleDebugInfo())
  3720. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  3721. return;
  3722. case Decl::UsingDirective: // using namespace X; [C++]
  3723. if (CGDebugInfo *DI = getModuleDebugInfo())
  3724. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  3725. return;
  3726. case Decl::CXXConstructor:
  3727. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  3728. break;
  3729. case Decl::CXXDestructor:
  3730. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  3731. break;
  3732. case Decl::StaticAssert:
  3733. // Nothing to do.
  3734. break;
  3735. // Objective-C Decls
  3736. // Forward declarations, no (immediate) code generation.
  3737. case Decl::ObjCInterface:
  3738. case Decl::ObjCCategory:
  3739. break;
  3740. case Decl::ObjCProtocol: {
  3741. auto *Proto = cast<ObjCProtocolDecl>(D);
  3742. if (Proto->isThisDeclarationADefinition())
  3743. ObjCRuntime->GenerateProtocol(Proto);
  3744. break;
  3745. }
  3746. case Decl::ObjCCategoryImpl:
  3747. // Categories have properties but don't support synthesize so we
  3748. // can ignore them here.
  3749. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  3750. break;
  3751. case Decl::ObjCImplementation: {
  3752. auto *OMD = cast<ObjCImplementationDecl>(D);
  3753. EmitObjCPropertyImplementations(OMD);
  3754. EmitObjCIvarInitializations(OMD);
  3755. ObjCRuntime->GenerateClass(OMD);
  3756. // Emit global variable debug information.
  3757. if (CGDebugInfo *DI = getModuleDebugInfo())
  3758. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3759. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  3760. OMD->getClassInterface()), OMD->getLocation());
  3761. break;
  3762. }
  3763. case Decl::ObjCMethod: {
  3764. auto *OMD = cast<ObjCMethodDecl>(D);
  3765. // If this is not a prototype, emit the body.
  3766. if (OMD->getBody())
  3767. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  3768. break;
  3769. }
  3770. case Decl::ObjCCompatibleAlias:
  3771. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  3772. break;
  3773. case Decl::PragmaComment: {
  3774. const auto *PCD = cast<PragmaCommentDecl>(D);
  3775. switch (PCD->getCommentKind()) {
  3776. case PCK_Unknown:
  3777. llvm_unreachable("unexpected pragma comment kind");
  3778. case PCK_Linker:
  3779. AppendLinkerOptions(PCD->getArg());
  3780. break;
  3781. case PCK_Lib:
  3782. if (getTarget().getTriple().isOSBinFormatELF() &&
  3783. !getTarget().getTriple().isPS4())
  3784. AddELFLibDirective(PCD->getArg());
  3785. else
  3786. AddDependentLib(PCD->getArg());
  3787. break;
  3788. case PCK_Compiler:
  3789. case PCK_ExeStr:
  3790. case PCK_User:
  3791. break; // We ignore all of these.
  3792. }
  3793. break;
  3794. }
  3795. case Decl::PragmaDetectMismatch: {
  3796. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  3797. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  3798. break;
  3799. }
  3800. case Decl::LinkageSpec:
  3801. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  3802. break;
  3803. case Decl::FileScopeAsm: {
  3804. // File-scope asm is ignored during device-side CUDA compilation.
  3805. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3806. break;
  3807. // File-scope asm is ignored during device-side OpenMP compilation.
  3808. if (LangOpts.OpenMPIsDevice)
  3809. break;
  3810. auto *AD = cast<FileScopeAsmDecl>(D);
  3811. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3812. break;
  3813. }
  3814. case Decl::Import: {
  3815. auto *Import = cast<ImportDecl>(D);
  3816. // If we've already imported this module, we're done.
  3817. if (!ImportedModules.insert(Import->getImportedModule()))
  3818. break;
  3819. // Emit debug information for direct imports.
  3820. if (!Import->getImportedOwningModule()) {
  3821. if (CGDebugInfo *DI = getModuleDebugInfo())
  3822. DI->EmitImportDecl(*Import);
  3823. }
  3824. // Find all of the submodules and emit the module initializers.
  3825. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  3826. SmallVector<clang::Module *, 16> Stack;
  3827. Visited.insert(Import->getImportedModule());
  3828. Stack.push_back(Import->getImportedModule());
  3829. while (!Stack.empty()) {
  3830. clang::Module *Mod = Stack.pop_back_val();
  3831. if (!EmittedModuleInitializers.insert(Mod).second)
  3832. continue;
  3833. for (auto *D : Context.getModuleInitializers(Mod))
  3834. EmitTopLevelDecl(D);
  3835. // Visit the submodules of this module.
  3836. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  3837. SubEnd = Mod->submodule_end();
  3838. Sub != SubEnd; ++Sub) {
  3839. // Skip explicit children; they need to be explicitly imported to emit
  3840. // the initializers.
  3841. if ((*Sub)->IsExplicit)
  3842. continue;
  3843. if (Visited.insert(*Sub).second)
  3844. Stack.push_back(*Sub);
  3845. }
  3846. }
  3847. break;
  3848. }
  3849. case Decl::Export:
  3850. EmitDeclContext(cast<ExportDecl>(D));
  3851. break;
  3852. case Decl::OMPThreadPrivate:
  3853. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3854. break;
  3855. case Decl::OMPDeclareReduction:
  3856. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  3857. break;
  3858. default:
  3859. // Make sure we handled everything we should, every other kind is a
  3860. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3861. // function. Need to recode Decl::Kind to do that easily.
  3862. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3863. break;
  3864. }
  3865. }
  3866. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3867. // Do we need to generate coverage mapping?
  3868. if (!CodeGenOpts.CoverageMapping)
  3869. return;
  3870. switch (D->getKind()) {
  3871. case Decl::CXXConversion:
  3872. case Decl::CXXMethod:
  3873. case Decl::Function:
  3874. case Decl::ObjCMethod:
  3875. case Decl::CXXConstructor:
  3876. case Decl::CXXDestructor: {
  3877. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  3878. return;
  3879. SourceManager &SM = getContext().getSourceManager();
  3880. if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
  3881. return;
  3882. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3883. if (I == DeferredEmptyCoverageMappingDecls.end())
  3884. DeferredEmptyCoverageMappingDecls[D] = true;
  3885. break;
  3886. }
  3887. default:
  3888. break;
  3889. };
  3890. }
  3891. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3892. // Do we need to generate coverage mapping?
  3893. if (!CodeGenOpts.CoverageMapping)
  3894. return;
  3895. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3896. if (Fn->isTemplateInstantiation())
  3897. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3898. }
  3899. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3900. if (I == DeferredEmptyCoverageMappingDecls.end())
  3901. DeferredEmptyCoverageMappingDecls[D] = false;
  3902. else
  3903. I->second = false;
  3904. }
  3905. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3906. // We call takeVector() here to avoid use-after-free.
  3907. // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
  3908. // we deserialize function bodies to emit coverage info for them, and that
  3909. // deserializes more declarations. How should we handle that case?
  3910. for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
  3911. if (!Entry.second)
  3912. continue;
  3913. const Decl *D = Entry.first;
  3914. switch (D->getKind()) {
  3915. case Decl::CXXConversion:
  3916. case Decl::CXXMethod:
  3917. case Decl::Function:
  3918. case Decl::ObjCMethod: {
  3919. CodeGenPGO PGO(*this);
  3920. GlobalDecl GD(cast<FunctionDecl>(D));
  3921. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3922. getFunctionLinkage(GD));
  3923. break;
  3924. }
  3925. case Decl::CXXConstructor: {
  3926. CodeGenPGO PGO(*this);
  3927. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3928. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3929. getFunctionLinkage(GD));
  3930. break;
  3931. }
  3932. case Decl::CXXDestructor: {
  3933. CodeGenPGO PGO(*this);
  3934. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  3935. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3936. getFunctionLinkage(GD));
  3937. break;
  3938. }
  3939. default:
  3940. break;
  3941. };
  3942. }
  3943. }
  3944. /// Turns the given pointer into a constant.
  3945. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  3946. const void *Ptr) {
  3947. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  3948. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  3949. return llvm::ConstantInt::get(i64, PtrInt);
  3950. }
  3951. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  3952. llvm::NamedMDNode *&GlobalMetadata,
  3953. GlobalDecl D,
  3954. llvm::GlobalValue *Addr) {
  3955. if (!GlobalMetadata)
  3956. GlobalMetadata =
  3957. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  3958. // TODO: should we report variant information for ctors/dtors?
  3959. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  3960. llvm::ConstantAsMetadata::get(GetPointerConstant(
  3961. CGM.getLLVMContext(), D.getDecl()))};
  3962. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  3963. }
  3964. /// For each function which is declared within an extern "C" region and marked
  3965. /// as 'used', but has internal linkage, create an alias from the unmangled
  3966. /// name to the mangled name if possible. People expect to be able to refer
  3967. /// to such functions with an unmangled name from inline assembly within the
  3968. /// same translation unit.
  3969. void CodeGenModule::EmitStaticExternCAliases() {
  3970. // Don't do anything if we're generating CUDA device code -- the NVPTX
  3971. // assembly target doesn't support aliases.
  3972. if (Context.getTargetInfo().getTriple().isNVPTX())
  3973. return;
  3974. for (auto &I : StaticExternCValues) {
  3975. IdentifierInfo *Name = I.first;
  3976. llvm::GlobalValue *Val = I.second;
  3977. if (Val && !getModule().getNamedValue(Name->getName()))
  3978. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  3979. }
  3980. }
  3981. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  3982. GlobalDecl &Result) const {
  3983. auto Res = Manglings.find(MangledName);
  3984. if (Res == Manglings.end())
  3985. return false;
  3986. Result = Res->getValue();
  3987. return true;
  3988. }
  3989. /// Emits metadata nodes associating all the global values in the
  3990. /// current module with the Decls they came from. This is useful for
  3991. /// projects using IR gen as a subroutine.
  3992. ///
  3993. /// Since there's currently no way to associate an MDNode directly
  3994. /// with an llvm::GlobalValue, we create a global named metadata
  3995. /// with the name 'clang.global.decl.ptrs'.
  3996. void CodeGenModule::EmitDeclMetadata() {
  3997. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3998. for (auto &I : MangledDeclNames) {
  3999. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  4000. // Some mangled names don't necessarily have an associated GlobalValue
  4001. // in this module, e.g. if we mangled it for DebugInfo.
  4002. if (Addr)
  4003. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  4004. }
  4005. }
  4006. /// Emits metadata nodes for all the local variables in the current
  4007. /// function.
  4008. void CodeGenFunction::EmitDeclMetadata() {
  4009. if (LocalDeclMap.empty()) return;
  4010. llvm::LLVMContext &Context = getLLVMContext();
  4011. // Find the unique metadata ID for this name.
  4012. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  4013. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4014. for (auto &I : LocalDeclMap) {
  4015. const Decl *D = I.first;
  4016. llvm::Value *Addr = I.second.getPointer();
  4017. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  4018. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  4019. Alloca->setMetadata(
  4020. DeclPtrKind, llvm::MDNode::get(
  4021. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  4022. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  4023. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  4024. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  4025. }
  4026. }
  4027. }
  4028. void CodeGenModule::EmitVersionIdentMetadata() {
  4029. llvm::NamedMDNode *IdentMetadata =
  4030. TheModule.getOrInsertNamedMetadata("llvm.ident");
  4031. std::string Version = getClangFullVersion();
  4032. llvm::LLVMContext &Ctx = TheModule.getContext();
  4033. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  4034. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  4035. }
  4036. void CodeGenModule::EmitTargetMetadata() {
  4037. // Warning, new MangledDeclNames may be appended within this loop.
  4038. // We rely on MapVector insertions adding new elements to the end
  4039. // of the container.
  4040. // FIXME: Move this loop into the one target that needs it, and only
  4041. // loop over those declarations for which we couldn't emit the target
  4042. // metadata when we emitted the declaration.
  4043. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  4044. auto Val = *(MangledDeclNames.begin() + I);
  4045. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  4046. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  4047. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  4048. }
  4049. }
  4050. void CodeGenModule::EmitCoverageFile() {
  4051. if (getCodeGenOpts().CoverageDataFile.empty() &&
  4052. getCodeGenOpts().CoverageNotesFile.empty())
  4053. return;
  4054. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  4055. if (!CUNode)
  4056. return;
  4057. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  4058. llvm::LLVMContext &Ctx = TheModule.getContext();
  4059. auto *CoverageDataFile =
  4060. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  4061. auto *CoverageNotesFile =
  4062. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  4063. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  4064. llvm::MDNode *CU = CUNode->getOperand(i);
  4065. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  4066. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  4067. }
  4068. }
  4069. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  4070. // Sema has checked that all uuid strings are of the form
  4071. // "12345678-1234-1234-1234-1234567890ab".
  4072. assert(Uuid.size() == 36);
  4073. for (unsigned i = 0; i < 36; ++i) {
  4074. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  4075. else assert(isHexDigit(Uuid[i]));
  4076. }
  4077. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  4078. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  4079. llvm::Constant *Field3[8];
  4080. for (unsigned Idx = 0; Idx < 8; ++Idx)
  4081. Field3[Idx] = llvm::ConstantInt::get(
  4082. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  4083. llvm::Constant *Fields[4] = {
  4084. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  4085. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  4086. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  4087. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  4088. };
  4089. return llvm::ConstantStruct::getAnon(Fields);
  4090. }
  4091. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  4092. bool ForEH) {
  4093. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  4094. // FIXME: should we even be calling this method if RTTI is disabled
  4095. // and it's not for EH?
  4096. if (!ForEH && !getLangOpts().RTTI)
  4097. return llvm::Constant::getNullValue(Int8PtrTy);
  4098. if (ForEH && Ty->isObjCObjectPointerType() &&
  4099. LangOpts.ObjCRuntime.isGNUFamily())
  4100. return ObjCRuntime->GetEHType(Ty);
  4101. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  4102. }
  4103. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  4104. // Do not emit threadprivates in simd-only mode.
  4105. if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
  4106. return;
  4107. for (auto RefExpr : D->varlists()) {
  4108. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  4109. bool PerformInit =
  4110. VD->getAnyInitializer() &&
  4111. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  4112. /*ForRef=*/false);
  4113. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  4114. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  4115. VD, Addr, RefExpr->getLocStart(), PerformInit))
  4116. CXXGlobalInits.push_back(InitFunction);
  4117. }
  4118. }
  4119. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  4120. llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
  4121. if (InternalId)
  4122. return InternalId;
  4123. if (isExternallyVisible(T->getLinkage())) {
  4124. std::string OutName;
  4125. llvm::raw_string_ostream Out(OutName);
  4126. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4127. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4128. } else {
  4129. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4130. llvm::ArrayRef<llvm::Metadata *>());
  4131. }
  4132. return InternalId;
  4133. }
  4134. // Generalize pointer types to a void pointer with the qualifiers of the
  4135. // originally pointed-to type, e.g. 'const char *' and 'char * const *'
  4136. // generalize to 'const void *' while 'char *' and 'const char **' generalize to
  4137. // 'void *'.
  4138. static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
  4139. if (!Ty->isPointerType())
  4140. return Ty;
  4141. return Ctx.getPointerType(
  4142. QualType(Ctx.VoidTy).withCVRQualifiers(
  4143. Ty->getPointeeType().getCVRQualifiers()));
  4144. }
  4145. // Apply type generalization to a FunctionType's return and argument types
  4146. static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
  4147. if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
  4148. SmallVector<QualType, 8> GeneralizedParams;
  4149. for (auto &Param : FnType->param_types())
  4150. GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
  4151. return Ctx.getFunctionType(
  4152. GeneralizeType(Ctx, FnType->getReturnType()),
  4153. GeneralizedParams, FnType->getExtProtoInfo());
  4154. }
  4155. if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
  4156. return Ctx.getFunctionNoProtoType(
  4157. GeneralizeType(Ctx, FnType->getReturnType()));
  4158. llvm_unreachable("Encountered unknown FunctionType");
  4159. }
  4160. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
  4161. T = GeneralizeFunctionType(getContext(), T);
  4162. llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
  4163. if (InternalId)
  4164. return InternalId;
  4165. if (isExternallyVisible(T->getLinkage())) {
  4166. std::string OutName;
  4167. llvm::raw_string_ostream Out(OutName);
  4168. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4169. Out << ".generalized";
  4170. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4171. } else {
  4172. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4173. llvm::ArrayRef<llvm::Metadata *>());
  4174. }
  4175. return InternalId;
  4176. }
  4177. /// Returns whether this module needs the "all-vtables" type identifier.
  4178. bool CodeGenModule::NeedAllVtablesTypeId() const {
  4179. // Returns true if at least one of vtable-based CFI checkers is enabled and
  4180. // is not in the trapping mode.
  4181. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  4182. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  4183. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  4184. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  4185. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  4186. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  4187. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  4188. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  4189. }
  4190. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  4191. CharUnits Offset,
  4192. const CXXRecordDecl *RD) {
  4193. llvm::Metadata *MD =
  4194. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  4195. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4196. if (CodeGenOpts.SanitizeCfiCrossDso)
  4197. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  4198. VTable->addTypeMetadata(Offset.getQuantity(),
  4199. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  4200. if (NeedAllVtablesTypeId()) {
  4201. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  4202. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4203. }
  4204. }
  4205. // Fills in the supplied string map with the set of target features for the
  4206. // passed in function.
  4207. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  4208. const FunctionDecl *FD) {
  4209. StringRef TargetCPU = Target.getTargetOpts().CPU;
  4210. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  4211. // If we have a TargetAttr build up the feature map based on that.
  4212. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  4213. ParsedAttr.Features.erase(
  4214. llvm::remove_if(ParsedAttr.Features,
  4215. [&](const std::string &Feat) {
  4216. return !Target.isValidFeatureName(
  4217. StringRef{Feat}.substr(1));
  4218. }),
  4219. ParsedAttr.Features.end());
  4220. // Make a copy of the features as passed on the command line into the
  4221. // beginning of the additional features from the function to override.
  4222. ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
  4223. Target.getTargetOpts().FeaturesAsWritten.begin(),
  4224. Target.getTargetOpts().FeaturesAsWritten.end());
  4225. if (ParsedAttr.Architecture != "" &&
  4226. Target.isValidCPUName(ParsedAttr.Architecture))
  4227. TargetCPU = ParsedAttr.Architecture;
  4228. // Now populate the feature map, first with the TargetCPU which is either
  4229. // the default or a new one from the target attribute string. Then we'll use
  4230. // the passed in features (FeaturesAsWritten) along with the new ones from
  4231. // the attribute.
  4232. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4233. ParsedAttr.Features);
  4234. } else {
  4235. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4236. Target.getTargetOpts().Features);
  4237. }
  4238. }
  4239. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  4240. if (!SanStats)
  4241. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  4242. return *SanStats;
  4243. }
  4244. llvm::Value *
  4245. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  4246. CodeGenFunction &CGF) {
  4247. llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
  4248. auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
  4249. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  4250. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  4251. "__translate_sampler_initializer"),
  4252. {C});
  4253. }