CodeGenModule.cpp 218 KB

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