CodeGenModule.cpp 206 KB

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