CodeGenFunction.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  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-function state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenFunction.h"
  13. #include "CGBlocks.h"
  14. #include "CGCleanup.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "TargetInfo.h"
  22. #include "clang/AST/ASTContext.h"
  23. #include "clang/AST/ASTLambda.h"
  24. #include "clang/AST/Decl.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/AST/StmtObjC.h"
  28. #include "clang/Basic/Builtins.h"
  29. #include "clang/Basic/CodeGenOptions.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/CodeGen/CGFunctionInfo.h"
  32. #include "clang/Frontend/FrontendDiagnostic.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/MDBuilder.h"
  37. #include "llvm/IR/Operator.h"
  38. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  39. using namespace clang;
  40. using namespace CodeGen;
  41. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  42. /// markers.
  43. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  44. const LangOptions &LangOpts) {
  45. if (CGOpts.DisableLifetimeMarkers)
  46. return false;
  47. // Disable lifetime markers in msan builds.
  48. // FIXME: Remove this when msan works with lifetime markers.
  49. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  50. return false;
  51. // Asan uses markers for use-after-scope checks.
  52. if (CGOpts.SanitizeAddressUseAfterScope)
  53. return true;
  54. // For now, only in optimized builds.
  55. return CGOpts.OptimizationLevel != 0;
  56. }
  57. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  58. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  59. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  60. CGBuilderInserterTy(this)),
  61. SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
  62. PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers(
  63. CGM.getCodeGenOpts(), CGM.getLangOpts())) {
  64. if (!suppressNewContext)
  65. CGM.getCXXABI().getMangleContext().startNewFunction();
  66. llvm::FastMathFlags FMF;
  67. if (CGM.getLangOpts().FastMath)
  68. FMF.setFast();
  69. if (CGM.getLangOpts().FiniteMathOnly) {
  70. FMF.setNoNaNs();
  71. FMF.setNoInfs();
  72. }
  73. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  74. FMF.setNoNaNs();
  75. }
  76. if (CGM.getCodeGenOpts().NoSignedZeros) {
  77. FMF.setNoSignedZeros();
  78. }
  79. if (CGM.getCodeGenOpts().ReciprocalMath) {
  80. FMF.setAllowReciprocal();
  81. }
  82. if (CGM.getCodeGenOpts().Reassociate) {
  83. FMF.setAllowReassoc();
  84. }
  85. Builder.setFastMathFlags(FMF);
  86. }
  87. CodeGenFunction::~CodeGenFunction() {
  88. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  89. // If there are any unclaimed block infos, go ahead and destroy them
  90. // now. This can happen if IR-gen gets clever and skips evaluating
  91. // something.
  92. if (FirstBlockInfo)
  93. destroyBlockInfos(FirstBlockInfo);
  94. if (getLangOpts().OpenMP && CurFn)
  95. CGM.getOpenMPRuntime().functionFinished(*this);
  96. }
  97. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  98. LValueBaseInfo *BaseInfo,
  99. TBAAAccessInfo *TBAAInfo) {
  100. return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
  101. /* forPointeeType= */ true);
  102. }
  103. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  104. LValueBaseInfo *BaseInfo,
  105. TBAAAccessInfo *TBAAInfo,
  106. bool forPointeeType) {
  107. if (TBAAInfo)
  108. *TBAAInfo = CGM.getTBAAAccessInfo(T);
  109. // Honor alignment typedef attributes even on incomplete types.
  110. // We also honor them straight for C++ class types, even as pointees;
  111. // there's an expressivity gap here.
  112. if (auto TT = T->getAs<TypedefType>()) {
  113. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  114. if (BaseInfo)
  115. *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
  116. return getContext().toCharUnitsFromBits(Align);
  117. }
  118. }
  119. if (BaseInfo)
  120. *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
  121. CharUnits Alignment;
  122. if (T->isIncompleteType()) {
  123. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  124. } else {
  125. // For C++ class pointees, we don't know whether we're pointing at a
  126. // base or a complete object, so we generally need to use the
  127. // non-virtual alignment.
  128. const CXXRecordDecl *RD;
  129. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  130. Alignment = CGM.getClassPointerAlignment(RD);
  131. } else {
  132. Alignment = getContext().getTypeAlignInChars(T);
  133. if (T.getQualifiers().hasUnaligned())
  134. Alignment = CharUnits::One();
  135. }
  136. // Cap to the global maximum type alignment unless the alignment
  137. // was somehow explicit on the type.
  138. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  139. if (Alignment.getQuantity() > MaxAlign &&
  140. !getContext().isAlignmentRequired(T))
  141. Alignment = CharUnits::fromQuantity(MaxAlign);
  142. }
  143. }
  144. return Alignment;
  145. }
  146. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  147. LValueBaseInfo BaseInfo;
  148. TBAAAccessInfo TBAAInfo;
  149. CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
  150. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
  151. TBAAInfo);
  152. }
  153. /// Given a value of type T* that may not be to a complete object,
  154. /// construct an l-value with the natural pointee alignment of T.
  155. LValue
  156. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  157. LValueBaseInfo BaseInfo;
  158. TBAAAccessInfo TBAAInfo;
  159. CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
  160. /* forPointeeType= */ true);
  161. return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
  162. }
  163. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  164. return CGM.getTypes().ConvertTypeForMem(T);
  165. }
  166. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  167. return CGM.getTypes().ConvertType(T);
  168. }
  169. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  170. type = type.getCanonicalType();
  171. while (true) {
  172. switch (type->getTypeClass()) {
  173. #define TYPE(name, parent)
  174. #define ABSTRACT_TYPE(name, parent)
  175. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  176. #define DEPENDENT_TYPE(name, parent) case Type::name:
  177. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  178. #include "clang/AST/TypeNodes.def"
  179. llvm_unreachable("non-canonical or dependent type in IR-generation");
  180. case Type::Auto:
  181. case Type::DeducedTemplateSpecialization:
  182. llvm_unreachable("undeduced type in IR-generation");
  183. // Various scalar types.
  184. case Type::Builtin:
  185. case Type::Pointer:
  186. case Type::BlockPointer:
  187. case Type::LValueReference:
  188. case Type::RValueReference:
  189. case Type::MemberPointer:
  190. case Type::Vector:
  191. case Type::ExtVector:
  192. case Type::FunctionProto:
  193. case Type::FunctionNoProto:
  194. case Type::Enum:
  195. case Type::ObjCObjectPointer:
  196. case Type::Pipe:
  197. return TEK_Scalar;
  198. // Complexes.
  199. case Type::Complex:
  200. return TEK_Complex;
  201. // Arrays, records, and Objective-C objects.
  202. case Type::ConstantArray:
  203. case Type::IncompleteArray:
  204. case Type::VariableArray:
  205. case Type::Record:
  206. case Type::ObjCObject:
  207. case Type::ObjCInterface:
  208. return TEK_Aggregate;
  209. // We operate on atomic values according to their underlying type.
  210. case Type::Atomic:
  211. type = cast<AtomicType>(type)->getValueType();
  212. continue;
  213. }
  214. llvm_unreachable("unknown type kind!");
  215. }
  216. }
  217. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  218. // For cleanliness, we try to avoid emitting the return block for
  219. // simple cases.
  220. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  221. if (CurBB) {
  222. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  223. // We have a valid insert point, reuse it if it is empty or there are no
  224. // explicit jumps to the return block.
  225. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  226. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  227. delete ReturnBlock.getBlock();
  228. ReturnBlock = JumpDest();
  229. } else
  230. EmitBlock(ReturnBlock.getBlock());
  231. return llvm::DebugLoc();
  232. }
  233. // Otherwise, if the return block is the target of a single direct
  234. // branch then we can just put the code in that block instead. This
  235. // cleans up functions which started with a unified return block.
  236. if (ReturnBlock.getBlock()->hasOneUse()) {
  237. llvm::BranchInst *BI =
  238. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  239. if (BI && BI->isUnconditional() &&
  240. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  241. // Record/return the DebugLoc of the simple 'return' expression to be used
  242. // later by the actual 'ret' instruction.
  243. llvm::DebugLoc Loc = BI->getDebugLoc();
  244. Builder.SetInsertPoint(BI->getParent());
  245. BI->eraseFromParent();
  246. delete ReturnBlock.getBlock();
  247. ReturnBlock = JumpDest();
  248. return Loc;
  249. }
  250. }
  251. // FIXME: We are at an unreachable point, there is no reason to emit the block
  252. // unless it has uses. However, we still need a place to put the debug
  253. // region.end for now.
  254. EmitBlock(ReturnBlock.getBlock());
  255. return llvm::DebugLoc();
  256. }
  257. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  258. if (!BB) return;
  259. if (!BB->use_empty())
  260. return CGF.CurFn->getBasicBlockList().push_back(BB);
  261. delete BB;
  262. }
  263. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  264. assert(BreakContinueStack.empty() &&
  265. "mismatched push/pop in break/continue stack!");
  266. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  267. && NumSimpleReturnExprs == NumReturnExprs
  268. && ReturnBlock.getBlock()->use_empty();
  269. // Usually the return expression is evaluated before the cleanup
  270. // code. If the function contains only a simple return statement,
  271. // such as a constant, the location before the cleanup code becomes
  272. // the last useful breakpoint in the function, because the simple
  273. // return expression will be evaluated after the cleanup code. To be
  274. // safe, set the debug location for cleanup code to the location of
  275. // the return statement. Otherwise the cleanup code should be at the
  276. // end of the function's lexical scope.
  277. //
  278. // If there are multiple branches to the return block, the branch
  279. // instructions will get the location of the return statements and
  280. // all will be fine.
  281. if (CGDebugInfo *DI = getDebugInfo()) {
  282. if (OnlySimpleReturnStmts)
  283. DI->EmitLocation(Builder, LastStopPoint);
  284. else
  285. DI->EmitLocation(Builder, EndLoc);
  286. }
  287. // Pop any cleanups that might have been associated with the
  288. // parameters. Do this in whatever block we're currently in; it's
  289. // important to do this before we enter the return block or return
  290. // edges will be *really* confused.
  291. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  292. bool HasOnlyLifetimeMarkers =
  293. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  294. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  295. if (HasCleanups) {
  296. // Make sure the line table doesn't jump back into the body for
  297. // the ret after it's been at EndLoc.
  298. if (CGDebugInfo *DI = getDebugInfo())
  299. if (OnlySimpleReturnStmts)
  300. DI->EmitLocation(Builder, EndLoc);
  301. PopCleanupBlocks(PrologueCleanupDepth);
  302. }
  303. // Emit function epilog (to return).
  304. llvm::DebugLoc Loc = EmitReturnBlock();
  305. if (ShouldInstrumentFunction()) {
  306. if (CGM.getCodeGenOpts().InstrumentFunctions)
  307. CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
  308. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  309. CurFn->addFnAttr("instrument-function-exit-inlined",
  310. "__cyg_profile_func_exit");
  311. }
  312. // Emit debug descriptor for function end.
  313. if (CGDebugInfo *DI = getDebugInfo())
  314. DI->EmitFunctionEnd(Builder, CurFn);
  315. // Reset the debug location to that of the simple 'return' expression, if any
  316. // rather than that of the end of the function's scope '}'.
  317. ApplyDebugLocation AL(*this, Loc);
  318. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  319. EmitEndEHSpec(CurCodeDecl);
  320. assert(EHStack.empty() &&
  321. "did not remove all scopes from cleanup stack!");
  322. // If someone did an indirect goto, emit the indirect goto block at the end of
  323. // the function.
  324. if (IndirectBranch) {
  325. EmitBlock(IndirectBranch->getParent());
  326. Builder.ClearInsertionPoint();
  327. }
  328. // If some of our locals escaped, insert a call to llvm.localescape in the
  329. // entry block.
  330. if (!EscapedLocals.empty()) {
  331. // Invert the map from local to index into a simple vector. There should be
  332. // no holes.
  333. SmallVector<llvm::Value *, 4> EscapeArgs;
  334. EscapeArgs.resize(EscapedLocals.size());
  335. for (auto &Pair : EscapedLocals)
  336. EscapeArgs[Pair.second] = Pair.first;
  337. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  338. &CGM.getModule(), llvm::Intrinsic::localescape);
  339. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  340. }
  341. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  342. llvm::Instruction *Ptr = AllocaInsertPt;
  343. AllocaInsertPt = nullptr;
  344. Ptr->eraseFromParent();
  345. // If someone took the address of a label but never did an indirect goto, we
  346. // made a zero entry PHI node, which is illegal, zap it now.
  347. if (IndirectBranch) {
  348. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  349. if (PN->getNumIncomingValues() == 0) {
  350. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  351. PN->eraseFromParent();
  352. }
  353. }
  354. EmitIfUsed(*this, EHResumeBlock);
  355. EmitIfUsed(*this, TerminateLandingPad);
  356. EmitIfUsed(*this, TerminateHandler);
  357. EmitIfUsed(*this, UnreachableBlock);
  358. for (const auto &FuncletAndParent : TerminateFunclets)
  359. EmitIfUsed(*this, FuncletAndParent.second);
  360. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  361. EmitDeclMetadata();
  362. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  363. I = DeferredReplacements.begin(),
  364. E = DeferredReplacements.end();
  365. I != E; ++I) {
  366. I->first->replaceAllUsesWith(I->second);
  367. I->first->eraseFromParent();
  368. }
  369. // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
  370. // PHIs if the current function is a coroutine. We don't do it for all
  371. // functions as it may result in slight increase in numbers of instructions
  372. // if compiled with no optimizations. We do it for coroutine as the lifetime
  373. // of CleanupDestSlot alloca make correct coroutine frame building very
  374. // difficult.
  375. if (NormalCleanupDest.isValid() && isCoroutine()) {
  376. llvm::DominatorTree DT(*CurFn);
  377. llvm::PromoteMemToReg(
  378. cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
  379. NormalCleanupDest = Address::invalid();
  380. }
  381. // Scan function arguments for vector width.
  382. for (llvm::Argument &A : CurFn->args())
  383. if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
  384. LargestVectorWidth = std::max(LargestVectorWidth,
  385. VT->getPrimitiveSizeInBits());
  386. // Update vector width based on return type.
  387. if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
  388. LargestVectorWidth = std::max(LargestVectorWidth,
  389. VT->getPrimitiveSizeInBits());
  390. // Add the required-vector-width attribute. This contains the max width from:
  391. // 1. min-vector-width attribute used in the source program.
  392. // 2. Any builtins used that have a vector width specified.
  393. // 3. Values passed in and out of inline assembly.
  394. // 4. Width of vector arguments and return types for this function.
  395. // 5. Width of vector aguments and return types for functions called by this
  396. // function.
  397. CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
  398. // If we generated an unreachable return block, delete it now.
  399. if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
  400. Builder.ClearInsertionPoint();
  401. ReturnBlock.getBlock()->eraseFromParent();
  402. }
  403. if (ReturnValue.isValid()) {
  404. auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
  405. if (RetAlloca && RetAlloca->use_empty()) {
  406. RetAlloca->eraseFromParent();
  407. ReturnValue = Address::invalid();
  408. }
  409. }
  410. }
  411. /// ShouldInstrumentFunction - Return true if the current function should be
  412. /// instrumented with __cyg_profile_func_* calls
  413. bool CodeGenFunction::ShouldInstrumentFunction() {
  414. if (!CGM.getCodeGenOpts().InstrumentFunctions &&
  415. !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
  416. !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  417. return false;
  418. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  419. return false;
  420. return true;
  421. }
  422. /// ShouldXRayInstrument - Return true if the current function should be
  423. /// instrumented with XRay nop sleds.
  424. bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
  425. return CGM.getCodeGenOpts().XRayInstrumentFunctions;
  426. }
  427. /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
  428. /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
  429. bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
  430. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  431. (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
  432. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  433. XRayInstrKind::Custom);
  434. }
  435. bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
  436. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  437. (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
  438. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  439. XRayInstrKind::Typed);
  440. }
  441. llvm::Constant *
  442. CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
  443. llvm::Constant *Addr) {
  444. // Addresses stored in prologue data can't require run-time fixups and must
  445. // be PC-relative. Run-time fixups are undesirable because they necessitate
  446. // writable text segments, which are unsafe. And absolute addresses are
  447. // undesirable because they break PIE mode.
  448. // Add a layer of indirection through a private global. Taking its address
  449. // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
  450. auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
  451. /*isConstant=*/true,
  452. llvm::GlobalValue::PrivateLinkage, Addr);
  453. // Create a PC-relative address.
  454. auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
  455. auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
  456. auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
  457. return (IntPtrTy == Int32Ty)
  458. ? PCRelAsInt
  459. : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
  460. }
  461. llvm::Value *
  462. CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
  463. llvm::Value *EncodedAddr) {
  464. // Reconstruct the address of the global.
  465. auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
  466. auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
  467. auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
  468. auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
  469. // Load the original pointer through the global.
  470. return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
  471. "decoded_addr");
  472. }
  473. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  474. llvm::Function *Fn)
  475. {
  476. if (!FD->hasAttr<OpenCLKernelAttr>())
  477. return;
  478. llvm::LLVMContext &Context = getLLVMContext();
  479. CGM.GenOpenCLArgMetadata(Fn, FD, this);
  480. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  481. QualType HintQTy = A->getTypeHint();
  482. const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
  483. bool IsSignedInteger =
  484. HintQTy->isSignedIntegerType() ||
  485. (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
  486. llvm::Metadata *AttrMDArgs[] = {
  487. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  488. CGM.getTypes().ConvertType(A->getTypeHint()))),
  489. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  490. llvm::IntegerType::get(Context, 32),
  491. llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
  492. Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
  493. }
  494. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  495. llvm::Metadata *AttrMDArgs[] = {
  496. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  497. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  498. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  499. Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
  500. }
  501. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  502. llvm::Metadata *AttrMDArgs[] = {
  503. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  504. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  505. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  506. Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
  507. }
  508. if (const OpenCLIntelReqdSubGroupSizeAttr *A =
  509. FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  510. llvm::Metadata *AttrMDArgs[] = {
  511. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
  512. Fn->setMetadata("intel_reqd_sub_group_size",
  513. llvm::MDNode::get(Context, AttrMDArgs));
  514. }
  515. }
  516. /// Determine whether the function F ends with a return stmt.
  517. static bool endsWithReturn(const Decl* F) {
  518. const Stmt *Body = nullptr;
  519. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  520. Body = FD->getBody();
  521. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  522. Body = OMD->getBody();
  523. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  524. auto LastStmt = CS->body_rbegin();
  525. if (LastStmt != CS->body_rend())
  526. return isa<ReturnStmt>(*LastStmt);
  527. }
  528. return false;
  529. }
  530. void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
  531. if (SanOpts.has(SanitizerKind::Thread)) {
  532. Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
  533. Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
  534. }
  535. }
  536. static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
  537. auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  538. if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
  539. !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
  540. (MD->getNumParams() != 1 && MD->getNumParams() != 2))
  541. return false;
  542. if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
  543. return false;
  544. if (MD->getNumParams() == 2) {
  545. auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
  546. if (!PT || !PT->isVoidPointerType() ||
  547. !PT->getPointeeType().isConstQualified())
  548. return false;
  549. }
  550. return true;
  551. }
  552. /// Return the UBSan prologue signature for \p FD if one is available.
  553. static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
  554. const FunctionDecl *FD) {
  555. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  556. if (!MD->isStatic())
  557. return nullptr;
  558. return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
  559. }
  560. void CodeGenFunction::StartFunction(GlobalDecl GD,
  561. QualType RetTy,
  562. llvm::Function *Fn,
  563. const CGFunctionInfo &FnInfo,
  564. const FunctionArgList &Args,
  565. SourceLocation Loc,
  566. SourceLocation StartLoc) {
  567. assert(!CurFn &&
  568. "Do not use a CodeGenFunction object for more than one function");
  569. const Decl *D = GD.getDecl();
  570. DidCallStackSave = false;
  571. CurCodeDecl = D;
  572. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  573. if (FD->usesSEHTry())
  574. CurSEHParent = FD;
  575. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  576. FnRetTy = RetTy;
  577. CurFn = Fn;
  578. CurFnInfo = &FnInfo;
  579. assert(CurFn->isDeclaration() && "Function already has body?");
  580. // If this function has been blacklisted for any of the enabled sanitizers,
  581. // disable the sanitizer for the function.
  582. do {
  583. #define SANITIZER(NAME, ID) \
  584. if (SanOpts.empty()) \
  585. break; \
  586. if (SanOpts.has(SanitizerKind::ID)) \
  587. if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \
  588. SanOpts.set(SanitizerKind::ID, false);
  589. #include "clang/Basic/Sanitizers.def"
  590. #undef SANITIZER
  591. } while (0);
  592. if (D) {
  593. // Apply the no_sanitize* attributes to SanOpts.
  594. for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
  595. SanitizerMask mask = Attr->getMask();
  596. SanOpts.Mask &= ~mask;
  597. if (mask & SanitizerKind::Address)
  598. SanOpts.set(SanitizerKind::KernelAddress, false);
  599. if (mask & SanitizerKind::KernelAddress)
  600. SanOpts.set(SanitizerKind::Address, false);
  601. if (mask & SanitizerKind::HWAddress)
  602. SanOpts.set(SanitizerKind::KernelHWAddress, false);
  603. if (mask & SanitizerKind::KernelHWAddress)
  604. SanOpts.set(SanitizerKind::HWAddress, false);
  605. }
  606. }
  607. // Apply sanitizer attributes to the function.
  608. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  609. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  610. if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
  611. Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
  612. if (SanOpts.has(SanitizerKind::MemTag))
  613. Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
  614. if (SanOpts.has(SanitizerKind::Thread))
  615. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  616. if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
  617. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  618. if (SanOpts.has(SanitizerKind::SafeStack))
  619. Fn->addFnAttr(llvm::Attribute::SafeStack);
  620. if (SanOpts.has(SanitizerKind::ShadowCallStack))
  621. Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
  622. // Apply fuzzing attribute to the function.
  623. if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
  624. Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
  625. // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
  626. // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
  627. if (SanOpts.has(SanitizerKind::Thread)) {
  628. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  629. IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
  630. if (OMD->getMethodFamily() == OMF_dealloc ||
  631. OMD->getMethodFamily() == OMF_initialize ||
  632. (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
  633. markAsIgnoreThreadCheckingAtRuntime(Fn);
  634. }
  635. }
  636. }
  637. // Ignore unrelated casts in STL allocate() since the allocator must cast
  638. // from void* to T* before object initialization completes. Don't match on the
  639. // namespace because not all allocators are in std::
  640. if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  641. if (matchesStlAllocatorFn(D, getContext()))
  642. SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
  643. }
  644. // Ignore null checks in coroutine functions since the coroutines passes
  645. // are not aware of how to move the extra UBSan instructions across the split
  646. // coroutine boundaries.
  647. if (D && SanOpts.has(SanitizerKind::Null))
  648. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  649. if (FD->getBody() &&
  650. FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
  651. SanOpts.Mask &= ~SanitizerKind::Null;
  652. // Apply xray attributes to the function (as a string, for now)
  653. if (D) {
  654. if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
  655. if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  656. XRayInstrKind::Function)) {
  657. if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction())
  658. Fn->addFnAttr("function-instrument", "xray-always");
  659. if (XRayAttr->neverXRayInstrument())
  660. Fn->addFnAttr("function-instrument", "xray-never");
  661. if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
  662. if (ShouldXRayInstrumentFunction())
  663. Fn->addFnAttr("xray-log-args",
  664. llvm::utostr(LogArgs->getArgumentCount()));
  665. }
  666. } else {
  667. if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
  668. Fn->addFnAttr(
  669. "xray-instruction-threshold",
  670. llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
  671. }
  672. }
  673. // Add no-jump-tables value.
  674. Fn->addFnAttr("no-jump-tables",
  675. llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
  676. // Add profile-sample-accurate value.
  677. if (CGM.getCodeGenOpts().ProfileSampleAccurate)
  678. Fn->addFnAttr("profile-sample-accurate");
  679. if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
  680. Fn->addFnAttr("cfi-canonical-jump-table");
  681. if (getLangOpts().OpenCL) {
  682. // Add metadata for a kernel function.
  683. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  684. EmitOpenCLKernelMetadata(FD, Fn);
  685. }
  686. // If we are checking function types, emit a function type signature as
  687. // prologue data.
  688. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  689. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  690. if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
  691. // Remove any (C++17) exception specifications, to allow calling e.g. a
  692. // noexcept function through a non-noexcept pointer.
  693. auto ProtoTy =
  694. getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
  695. EST_None);
  696. llvm::Constant *FTRTTIConst =
  697. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  698. llvm::Constant *FTRTTIConstEncoded =
  699. EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
  700. llvm::Constant *PrologueStructElems[] = {PrologueSig,
  701. FTRTTIConstEncoded};
  702. llvm::Constant *PrologueStructConst =
  703. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  704. Fn->setPrologueData(PrologueStructConst);
  705. }
  706. }
  707. }
  708. // If we're checking nullability, we need to know whether we can check the
  709. // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
  710. if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
  711. auto Nullability = FnRetTy->getNullability(getContext());
  712. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  713. if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  714. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
  715. RetValNullabilityPrecondition =
  716. llvm::ConstantInt::getTrue(getLLVMContext());
  717. }
  718. }
  719. // If we're in C++ mode and the function name is "main", it is guaranteed
  720. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  721. // used within a program").
  722. if (getLangOpts().CPlusPlus)
  723. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  724. if (FD->isMain())
  725. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  726. // If a custom alignment is used, force realigning to this alignment on
  727. // any main function which certainly will need it.
  728. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  729. if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
  730. CGM.getCodeGenOpts().StackAlignment)
  731. Fn->addFnAttr("stackrealign");
  732. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  733. // Create a marker to make it easy to insert allocas into the entryblock
  734. // later. Don't create this with the builder, because we don't want it
  735. // folded.
  736. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  737. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  738. ReturnBlock = getJumpDestInCurrentScope("return");
  739. Builder.SetInsertPoint(EntryBB);
  740. // If we're checking the return value, allocate space for a pointer to a
  741. // precise source location of the checked return statement.
  742. if (requiresReturnValueCheck()) {
  743. ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
  744. InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
  745. }
  746. // Emit subprogram debug descriptor.
  747. if (CGDebugInfo *DI = getDebugInfo()) {
  748. // Reconstruct the type from the argument list so that implicit parameters,
  749. // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
  750. // convention.
  751. CallingConv CC = CallingConv::CC_C;
  752. if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  753. if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
  754. CC = SrcFnTy->getCallConv();
  755. SmallVector<QualType, 16> ArgTypes;
  756. for (const VarDecl *VD : Args)
  757. ArgTypes.push_back(VD->getType());
  758. QualType FnType = getContext().getFunctionType(
  759. RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  760. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
  761. Builder);
  762. }
  763. if (ShouldInstrumentFunction()) {
  764. if (CGM.getCodeGenOpts().InstrumentFunctions)
  765. CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
  766. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  767. CurFn->addFnAttr("instrument-function-entry-inlined",
  768. "__cyg_profile_func_enter");
  769. if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  770. CurFn->addFnAttr("instrument-function-entry-inlined",
  771. "__cyg_profile_func_enter_bare");
  772. }
  773. // Since emitting the mcount call here impacts optimizations such as function
  774. // inlining, we just add an attribute to insert a mcount call in backend.
  775. // The attribute "counting-function" is set to mcount function name which is
  776. // architecture dependent.
  777. if (CGM.getCodeGenOpts().InstrumentForProfiling) {
  778. // Calls to fentry/mcount should not be generated if function has
  779. // the no_instrument_function attribute.
  780. if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
  781. if (CGM.getCodeGenOpts().CallFEntry)
  782. Fn->addFnAttr("fentry-call", "true");
  783. else {
  784. Fn->addFnAttr("instrument-function-entry-inlined",
  785. getTarget().getMCountName());
  786. }
  787. }
  788. }
  789. if (RetTy->isVoidType()) {
  790. // Void type; nothing to return.
  791. ReturnValue = Address::invalid();
  792. // Count the implicit return.
  793. if (!endsWithReturn(D))
  794. ++NumReturnExprs;
  795. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
  796. // Indirect return; emit returned value directly into sret slot.
  797. // This reduces code size, and affects correctness in C++.
  798. auto AI = CurFn->arg_begin();
  799. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  800. ++AI;
  801. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  802. if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
  803. ReturnValuePointer =
  804. CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
  805. Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
  806. ReturnValue.getPointer(), Int8PtrTy),
  807. ReturnValuePointer);
  808. }
  809. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  810. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  811. // Load the sret pointer from the argument struct and return into that.
  812. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  813. llvm::Function::arg_iterator EI = CurFn->arg_end();
  814. --EI;
  815. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  816. ReturnValuePointer = Address(Addr, getPointerAlign());
  817. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  818. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  819. } else {
  820. ReturnValue = CreateIRTemp(RetTy, "retval");
  821. // Tell the epilog emitter to autorelease the result. We do this
  822. // now so that various specialized functions can suppress it
  823. // during their IR-generation.
  824. if (getLangOpts().ObjCAutoRefCount &&
  825. !CurFnInfo->isReturnsRetained() &&
  826. RetTy->isObjCRetainableType())
  827. AutoreleaseResult = true;
  828. }
  829. EmitStartEHSpec(CurCodeDecl);
  830. PrologueCleanupDepth = EHStack.stable_begin();
  831. // Emit OpenMP specific initialization of the device functions.
  832. if (getLangOpts().OpenMP && CurCodeDecl)
  833. CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
  834. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  835. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  836. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  837. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  838. if (MD->getParent()->isLambda() &&
  839. MD->getOverloadedOperator() == OO_Call) {
  840. // We're in a lambda; figure out the captures.
  841. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  842. LambdaThisCaptureField);
  843. if (LambdaThisCaptureField) {
  844. // If the lambda captures the object referred to by '*this' - either by
  845. // value or by reference, make sure CXXThisValue points to the correct
  846. // object.
  847. // Get the lvalue for the field (which is a copy of the enclosing object
  848. // or contains the address of the enclosing object).
  849. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  850. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  851. // If the enclosing object was captured by value, just use its address.
  852. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  853. } else {
  854. // Load the lvalue pointed to by the field, since '*this' was captured
  855. // by reference.
  856. CXXThisValue =
  857. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  858. }
  859. }
  860. for (auto *FD : MD->getParent()->fields()) {
  861. if (FD->hasCapturedVLAType()) {
  862. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  863. SourceLocation()).getScalarVal();
  864. auto VAT = FD->getCapturedVLAType();
  865. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  866. }
  867. }
  868. } else {
  869. // Not in a lambda; just use 'this' from the method.
  870. // FIXME: Should we generate a new load for each use of 'this'? The
  871. // fast register allocator would be happier...
  872. CXXThisValue = CXXABIThisValue;
  873. }
  874. // Check the 'this' pointer once per function, if it's available.
  875. if (CXXABIThisValue) {
  876. SanitizerSet SkippedChecks;
  877. SkippedChecks.set(SanitizerKind::ObjectSize, true);
  878. QualType ThisTy = MD->getThisType();
  879. // If this is the call operator of a lambda with no capture-default, it
  880. // may have a static invoker function, which may call this operator with
  881. // a null 'this' pointer.
  882. if (isLambdaCallOperator(MD) &&
  883. MD->getParent()->getLambdaCaptureDefault() == LCD_None)
  884. SkippedChecks.set(SanitizerKind::Null, true);
  885. EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
  886. : TCK_MemberCall,
  887. Loc, CXXABIThisValue, ThisTy,
  888. getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
  889. SkippedChecks);
  890. }
  891. }
  892. // If any of the arguments have a variably modified type, make sure to
  893. // emit the type size.
  894. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  895. i != e; ++i) {
  896. const VarDecl *VD = *i;
  897. // Dig out the type as written from ParmVarDecls; it's unclear whether
  898. // the standard (C99 6.9.1p10) requires this, but we're following the
  899. // precedent set by gcc.
  900. QualType Ty;
  901. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  902. Ty = PVD->getOriginalType();
  903. else
  904. Ty = VD->getType();
  905. if (Ty->isVariablyModifiedType())
  906. EmitVariablyModifiedType(Ty);
  907. }
  908. // Emit a location at the end of the prologue.
  909. if (CGDebugInfo *DI = getDebugInfo())
  910. DI->EmitLocation(Builder, StartLoc);
  911. // TODO: Do we need to handle this in two places like we do with
  912. // target-features/target-cpu?
  913. if (CurFuncDecl)
  914. if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
  915. LargestVectorWidth = VecWidth->getVectorWidth();
  916. }
  917. void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
  918. incrementProfileCounter(Body);
  919. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  920. EmitCompoundStmtWithoutScope(*S);
  921. else
  922. EmitStmt(Body);
  923. }
  924. /// When instrumenting to collect profile data, the counts for some blocks
  925. /// such as switch cases need to not include the fall-through counts, so
  926. /// emit a branch around the instrumentation code. When not instrumenting,
  927. /// this just calls EmitBlock().
  928. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  929. const Stmt *S) {
  930. llvm::BasicBlock *SkipCountBB = nullptr;
  931. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  932. // When instrumenting for profiling, the fallthrough to certain
  933. // statements needs to skip over the instrumentation code so that we
  934. // get an accurate count.
  935. SkipCountBB = createBasicBlock("skipcount");
  936. EmitBranch(SkipCountBB);
  937. }
  938. EmitBlock(BB);
  939. uint64_t CurrentCount = getCurrentProfileCount();
  940. incrementProfileCounter(S);
  941. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  942. if (SkipCountBB)
  943. EmitBlock(SkipCountBB);
  944. }
  945. /// Tries to mark the given function nounwind based on the
  946. /// non-existence of any throwing calls within it. We believe this is
  947. /// lightweight enough to do at -O0.
  948. static void TryMarkNoThrow(llvm::Function *F) {
  949. // LLVM treats 'nounwind' on a function as part of the type, so we
  950. // can't do this on functions that can be overwritten.
  951. if (F->isInterposable()) return;
  952. for (llvm::BasicBlock &BB : *F)
  953. for (llvm::Instruction &I : BB)
  954. if (I.mayThrow())
  955. return;
  956. F->setDoesNotThrow();
  957. }
  958. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  959. FunctionArgList &Args) {
  960. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  961. QualType ResTy = FD->getReturnType();
  962. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  963. if (MD && MD->isInstance()) {
  964. if (CGM.getCXXABI().HasThisReturn(GD))
  965. ResTy = MD->getThisType();
  966. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  967. ResTy = CGM.getContext().VoidPtrTy;
  968. CGM.getCXXABI().buildThisParam(*this, Args);
  969. }
  970. // The base version of an inheriting constructor whose constructed base is a
  971. // virtual base is not passed any arguments (because it doesn't actually call
  972. // the inherited constructor).
  973. bool PassedParams = true;
  974. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  975. if (auto Inherited = CD->getInheritedConstructor())
  976. PassedParams =
  977. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  978. if (PassedParams) {
  979. for (auto *Param : FD->parameters()) {
  980. Args.push_back(Param);
  981. if (!Param->hasAttr<PassObjectSizeAttr>())
  982. continue;
  983. auto *Implicit = ImplicitParamDecl::Create(
  984. getContext(), Param->getDeclContext(), Param->getLocation(),
  985. /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
  986. SizeArguments[Param] = Implicit;
  987. Args.push_back(Implicit);
  988. }
  989. }
  990. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  991. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  992. return ResTy;
  993. }
  994. static bool
  995. shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
  996. const ASTContext &Context) {
  997. QualType T = FD->getReturnType();
  998. // Avoid the optimization for functions that return a record type with a
  999. // trivial destructor or another trivially copyable type.
  1000. if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
  1001. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1002. return !ClassDecl->hasTrivialDestructor();
  1003. }
  1004. return !T.isTriviallyCopyableType(Context);
  1005. }
  1006. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1007. const CGFunctionInfo &FnInfo) {
  1008. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1009. CurGD = GD;
  1010. FunctionArgList Args;
  1011. QualType ResTy = BuildFunctionArgList(GD, Args);
  1012. // Check if we should generate debug info for this function.
  1013. if (FD->hasAttr<NoDebugAttr>())
  1014. DebugInfo = nullptr; // disable debug info indefinitely for this function
  1015. // The function might not have a body if we're generating thunks for a
  1016. // function declaration.
  1017. SourceRange BodyRange;
  1018. if (Stmt *Body = FD->getBody())
  1019. BodyRange = Body->getSourceRange();
  1020. else
  1021. BodyRange = FD->getLocation();
  1022. CurEHLocation = BodyRange.getEnd();
  1023. // Use the location of the start of the function to determine where
  1024. // the function definition is located. By default use the location
  1025. // of the declaration as the location for the subprogram. A function
  1026. // may lack a declaration in the source code if it is created by code
  1027. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  1028. SourceLocation Loc = FD->getLocation();
  1029. // If this is a function specialization then use the pattern body
  1030. // as the location for the function.
  1031. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  1032. if (SpecDecl->hasBody(SpecDecl))
  1033. Loc = SpecDecl->getLocation();
  1034. Stmt *Body = FD->getBody();
  1035. // Initialize helper which will detect jumps which can cause invalid lifetime
  1036. // markers.
  1037. if (Body && ShouldEmitLifetimeMarkers)
  1038. Bypasses.Init(Body);
  1039. // Emit the standard function prologue.
  1040. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  1041. // Generate the body of the function.
  1042. PGO.assignRegionCounters(GD, CurFn);
  1043. if (isa<CXXDestructorDecl>(FD))
  1044. EmitDestructorBody(Args);
  1045. else if (isa<CXXConstructorDecl>(FD))
  1046. EmitConstructorBody(Args);
  1047. else if (getLangOpts().CUDA &&
  1048. !getLangOpts().CUDAIsDevice &&
  1049. FD->hasAttr<CUDAGlobalAttr>())
  1050. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  1051. else if (isa<CXXMethodDecl>(FD) &&
  1052. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  1053. // The lambda static invoker function is special, because it forwards or
  1054. // clones the body of the function call operator (but is actually static).
  1055. EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
  1056. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  1057. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  1058. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  1059. // Implicit copy-assignment gets the same special treatment as implicit
  1060. // copy-constructors.
  1061. emitImplicitAssignmentOperatorBody(Args);
  1062. } else if (Body) {
  1063. EmitFunctionBody(Body);
  1064. } else
  1065. llvm_unreachable("no definition for emitted function");
  1066. // C++11 [stmt.return]p2:
  1067. // Flowing off the end of a function [...] results in undefined behavior in
  1068. // a value-returning function.
  1069. // C11 6.9.1p12:
  1070. // If the '}' that terminates a function is reached, and the value of the
  1071. // function call is used by the caller, the behavior is undefined.
  1072. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1073. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1074. bool ShouldEmitUnreachable =
  1075. CGM.getCodeGenOpts().StrictReturn ||
  1076. shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
  1077. if (SanOpts.has(SanitizerKind::Return)) {
  1078. SanitizerScope SanScope(this);
  1079. llvm::Value *IsFalse = Builder.getFalse();
  1080. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1081. SanitizerHandler::MissingReturn,
  1082. EmitCheckSourceLocation(FD->getLocation()), None);
  1083. } else if (ShouldEmitUnreachable) {
  1084. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1085. EmitTrapCall(llvm::Intrinsic::trap);
  1086. }
  1087. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1088. Builder.CreateUnreachable();
  1089. Builder.ClearInsertionPoint();
  1090. }
  1091. }
  1092. // Emit the standard function epilogue.
  1093. FinishFunction(BodyRange.getEnd());
  1094. // If we haven't marked the function nothrow through other means, do
  1095. // a quick pass now to see if we can.
  1096. if (!CurFn->doesNotThrow())
  1097. TryMarkNoThrow(CurFn);
  1098. }
  1099. /// ContainsLabel - Return true if the statement contains a label in it. If
  1100. /// this statement is not executed normally, it not containing a label means
  1101. /// that we can just remove the code.
  1102. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1103. // Null statement, not a label!
  1104. if (!S) return false;
  1105. // If this is a label, we have to emit the code, consider something like:
  1106. // if (0) { ... foo: bar(); } goto foo;
  1107. //
  1108. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1109. // can't jump to one from outside their declared region.
  1110. if (isa<LabelStmt>(S))
  1111. return true;
  1112. // If this is a case/default statement, and we haven't seen a switch, we have
  1113. // to emit the code.
  1114. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1115. return true;
  1116. // If this is a switch statement, we want to ignore cases below it.
  1117. if (isa<SwitchStmt>(S))
  1118. IgnoreCaseStmts = true;
  1119. // Scan subexpressions for verboten labels.
  1120. for (const Stmt *SubStmt : S->children())
  1121. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1122. return true;
  1123. return false;
  1124. }
  1125. /// containsBreak - Return true if the statement contains a break out of it.
  1126. /// If the statement (recursively) contains a switch or loop with a break
  1127. /// inside of it, this is fine.
  1128. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1129. // Null statement, not a label!
  1130. if (!S) return false;
  1131. // If this is a switch or loop that defines its own break scope, then we can
  1132. // include it and anything inside of it.
  1133. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1134. isa<ForStmt>(S))
  1135. return false;
  1136. if (isa<BreakStmt>(S))
  1137. return true;
  1138. // Scan subexpressions for verboten breaks.
  1139. for (const Stmt *SubStmt : S->children())
  1140. if (containsBreak(SubStmt))
  1141. return true;
  1142. return false;
  1143. }
  1144. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1145. if (!S) return false;
  1146. // Some statement kinds add a scope and thus never add a decl to the current
  1147. // scope. Note, this list is longer than the list of statements that might
  1148. // have an unscoped decl nested within them, but this way is conservatively
  1149. // correct even if more statement kinds are added.
  1150. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1151. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1152. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1153. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1154. return false;
  1155. if (isa<DeclStmt>(S))
  1156. return true;
  1157. for (const Stmt *SubStmt : S->children())
  1158. if (mightAddDeclToScope(SubStmt))
  1159. return true;
  1160. return false;
  1161. }
  1162. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1163. /// to a constant, or if it does but contains a label, return false. If it
  1164. /// constant folds return true and set the boolean result in Result.
  1165. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1166. bool &ResultBool,
  1167. bool AllowLabels) {
  1168. llvm::APSInt ResultInt;
  1169. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1170. return false;
  1171. ResultBool = ResultInt.getBoolValue();
  1172. return true;
  1173. }
  1174. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1175. /// to a constant, or if it does but contains a label, return false. If it
  1176. /// constant folds return true and set the folded value.
  1177. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1178. llvm::APSInt &ResultInt,
  1179. bool AllowLabels) {
  1180. // FIXME: Rename and handle conversion of other evaluatable things
  1181. // to bool.
  1182. Expr::EvalResult Result;
  1183. if (!Cond->EvaluateAsInt(Result, getContext()))
  1184. return false; // Not foldable, not integer or not fully evaluatable.
  1185. llvm::APSInt Int = Result.Val.getInt();
  1186. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1187. return false; // Contains a label.
  1188. ResultInt = Int;
  1189. return true;
  1190. }
  1191. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1192. /// statement) to the specified blocks. Based on the condition, this might try
  1193. /// to simplify the codegen of the conditional based on the branch.
  1194. ///
  1195. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1196. llvm::BasicBlock *TrueBlock,
  1197. llvm::BasicBlock *FalseBlock,
  1198. uint64_t TrueCount) {
  1199. Cond = Cond->IgnoreParens();
  1200. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1201. // Handle X && Y in a condition.
  1202. if (CondBOp->getOpcode() == BO_LAnd) {
  1203. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1204. // folded if the case was simple enough.
  1205. bool ConstantBool = false;
  1206. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1207. ConstantBool) {
  1208. // br(1 && X) -> br(X).
  1209. incrementProfileCounter(CondBOp);
  1210. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1211. TrueCount);
  1212. }
  1213. // If we have "X && 1", simplify the code to use an uncond branch.
  1214. // "X && 0" would have been constant folded to 0.
  1215. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1216. ConstantBool) {
  1217. // br(X && 1) -> br(X).
  1218. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1219. TrueCount);
  1220. }
  1221. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1222. // want to jump to the FalseBlock.
  1223. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1224. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1225. // can be propagated to that branch.
  1226. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1227. ConditionalEvaluation eval(*this);
  1228. {
  1229. ApplyDebugLocation DL(*this, Cond);
  1230. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1231. EmitBlock(LHSTrue);
  1232. }
  1233. incrementProfileCounter(CondBOp);
  1234. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1235. // Any temporaries created here are conditional.
  1236. eval.begin(*this);
  1237. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1238. eval.end(*this);
  1239. return;
  1240. }
  1241. if (CondBOp->getOpcode() == BO_LOr) {
  1242. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1243. // folded if the case was simple enough.
  1244. bool ConstantBool = false;
  1245. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1246. !ConstantBool) {
  1247. // br(0 || X) -> br(X).
  1248. incrementProfileCounter(CondBOp);
  1249. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1250. TrueCount);
  1251. }
  1252. // If we have "X || 0", simplify the code to use an uncond branch.
  1253. // "X || 1" would have been constant folded to 1.
  1254. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1255. !ConstantBool) {
  1256. // br(X || 0) -> br(X).
  1257. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1258. TrueCount);
  1259. }
  1260. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1261. // want to jump to the TrueBlock.
  1262. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1263. // We have the count for entry to the RHS and for the whole expression
  1264. // being true, so we can divy up True count between the short circuit and
  1265. // the RHS.
  1266. uint64_t LHSCount =
  1267. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1268. uint64_t RHSCount = TrueCount - LHSCount;
  1269. ConditionalEvaluation eval(*this);
  1270. {
  1271. ApplyDebugLocation DL(*this, Cond);
  1272. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1273. EmitBlock(LHSFalse);
  1274. }
  1275. incrementProfileCounter(CondBOp);
  1276. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1277. // Any temporaries created here are conditional.
  1278. eval.begin(*this);
  1279. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1280. eval.end(*this);
  1281. return;
  1282. }
  1283. }
  1284. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1285. // br(!x, t, f) -> br(x, f, t)
  1286. if (CondUOp->getOpcode() == UO_LNot) {
  1287. // Negate the count.
  1288. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1289. // Negate the condition and swap the destination blocks.
  1290. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1291. FalseCount);
  1292. }
  1293. }
  1294. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1295. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1296. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1297. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1298. ConditionalEvaluation cond(*this);
  1299. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1300. getProfileCount(CondOp));
  1301. // When computing PGO branch weights, we only know the overall count for
  1302. // the true block. This code is essentially doing tail duplication of the
  1303. // naive code-gen, introducing new edges for which counts are not
  1304. // available. Divide the counts proportionally between the LHS and RHS of
  1305. // the conditional operator.
  1306. uint64_t LHSScaledTrueCount = 0;
  1307. if (TrueCount) {
  1308. double LHSRatio =
  1309. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1310. LHSScaledTrueCount = TrueCount * LHSRatio;
  1311. }
  1312. cond.begin(*this);
  1313. EmitBlock(LHSBlock);
  1314. incrementProfileCounter(CondOp);
  1315. {
  1316. ApplyDebugLocation DL(*this, Cond);
  1317. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1318. LHSScaledTrueCount);
  1319. }
  1320. cond.end(*this);
  1321. cond.begin(*this);
  1322. EmitBlock(RHSBlock);
  1323. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1324. TrueCount - LHSScaledTrueCount);
  1325. cond.end(*this);
  1326. return;
  1327. }
  1328. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1329. // Conditional operator handling can give us a throw expression as a
  1330. // condition for a case like:
  1331. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1332. // Fold this to:
  1333. // br(c, throw x, br(y, t, f))
  1334. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1335. return;
  1336. }
  1337. // If the branch has a condition wrapped by __builtin_unpredictable,
  1338. // create metadata that specifies that the branch is unpredictable.
  1339. // Don't bother if not optimizing because that metadata would not be used.
  1340. llvm::MDNode *Unpredictable = nullptr;
  1341. auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
  1342. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1343. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1344. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1345. llvm::MDBuilder MDHelper(getLLVMContext());
  1346. Unpredictable = MDHelper.createUnpredictable();
  1347. }
  1348. }
  1349. // Create branch weights based on the number of times we get here and the
  1350. // number of times the condition should be true.
  1351. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1352. llvm::MDNode *Weights =
  1353. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1354. // Emit the code with the fully general case.
  1355. llvm::Value *CondV;
  1356. {
  1357. ApplyDebugLocation DL(*this, Cond);
  1358. CondV = EvaluateExprAsBool(Cond);
  1359. }
  1360. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1361. }
  1362. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1363. /// specified stmt yet.
  1364. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1365. CGM.ErrorUnsupported(S, Type);
  1366. }
  1367. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1368. /// variable-length array whose elements have a non-zero bit-pattern.
  1369. ///
  1370. /// \param baseType the inner-most element type of the array
  1371. /// \param src - a char* pointing to the bit-pattern for a single
  1372. /// base element of the array
  1373. /// \param sizeInChars - the total size of the VLA, in chars
  1374. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1375. Address dest, Address src,
  1376. llvm::Value *sizeInChars) {
  1377. CGBuilderTy &Builder = CGF.Builder;
  1378. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1379. llvm::Value *baseSizeInChars
  1380. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1381. Address begin =
  1382. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1383. llvm::Value *end =
  1384. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1385. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1386. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1387. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1388. // Make a loop over the VLA. C99 guarantees that the VLA element
  1389. // count must be nonzero.
  1390. CGF.EmitBlock(loopBB);
  1391. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1392. cur->addIncoming(begin.getPointer(), originBB);
  1393. CharUnits curAlign =
  1394. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1395. // memcpy the individual element bit-pattern.
  1396. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1397. /*volatile*/ false);
  1398. // Go to the next element.
  1399. llvm::Value *next =
  1400. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1401. // Leave if that's the end of the VLA.
  1402. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1403. Builder.CreateCondBr(done, contBB, loopBB);
  1404. cur->addIncoming(next, loopBB);
  1405. CGF.EmitBlock(contBB);
  1406. }
  1407. void
  1408. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1409. // Ignore empty classes in C++.
  1410. if (getLangOpts().CPlusPlus) {
  1411. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1412. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1413. return;
  1414. }
  1415. }
  1416. // Cast the dest ptr to the appropriate i8 pointer type.
  1417. if (DestPtr.getElementType() != Int8Ty)
  1418. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1419. // Get size and alignment info for this aggregate.
  1420. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1421. llvm::Value *SizeVal;
  1422. const VariableArrayType *vla;
  1423. // Don't bother emitting a zero-byte memset.
  1424. if (size.isZero()) {
  1425. // But note that getTypeInfo returns 0 for a VLA.
  1426. if (const VariableArrayType *vlaType =
  1427. dyn_cast_or_null<VariableArrayType>(
  1428. getContext().getAsArrayType(Ty))) {
  1429. auto VlaSize = getVLASize(vlaType);
  1430. SizeVal = VlaSize.NumElts;
  1431. CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1432. if (!eltSize.isOne())
  1433. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1434. vla = vlaType;
  1435. } else {
  1436. return;
  1437. }
  1438. } else {
  1439. SizeVal = CGM.getSize(size);
  1440. vla = nullptr;
  1441. }
  1442. // If the type contains a pointer to data member we can't memset it to zero.
  1443. // Instead, create a null constant and copy it to the destination.
  1444. // TODO: there are other patterns besides zero that we can usefully memset,
  1445. // like -1, which happens to be the pattern used by member-pointers.
  1446. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1447. // For a VLA, emit a single element, then splat that over the VLA.
  1448. if (vla) Ty = getContext().getBaseElementType(vla);
  1449. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1450. llvm::GlobalVariable *NullVariable =
  1451. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1452. /*isConstant=*/true,
  1453. llvm::GlobalVariable::PrivateLinkage,
  1454. NullConstant, Twine());
  1455. CharUnits NullAlign = DestPtr.getAlignment();
  1456. NullVariable->setAlignment(NullAlign.getQuantity());
  1457. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1458. NullAlign);
  1459. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1460. // Get and call the appropriate llvm.memcpy overload.
  1461. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1462. return;
  1463. }
  1464. // Otherwise, just memset the whole thing to zero. This is legal
  1465. // because in LLVM, all default initializers (other than the ones we just
  1466. // handled above) are guaranteed to have a bit pattern of all zeros.
  1467. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1468. }
  1469. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1470. // Make sure that there is a block for the indirect goto.
  1471. if (!IndirectBranch)
  1472. GetIndirectGotoBlock();
  1473. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1474. // Make sure the indirect branch includes all of the address-taken blocks.
  1475. IndirectBranch->addDestination(BB);
  1476. return llvm::BlockAddress::get(CurFn, BB);
  1477. }
  1478. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1479. // If we already made the indirect branch for indirect goto, return its block.
  1480. if (IndirectBranch) return IndirectBranch->getParent();
  1481. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1482. // Create the PHI node that indirect gotos will add entries to.
  1483. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1484. "indirect.goto.dest");
  1485. // Create the indirect branch instruction.
  1486. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1487. return IndirectBranch->getParent();
  1488. }
  1489. /// Computes the length of an array in elements, as well as the base
  1490. /// element type and a properly-typed first element pointer.
  1491. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1492. QualType &baseType,
  1493. Address &addr) {
  1494. const ArrayType *arrayType = origArrayType;
  1495. // If it's a VLA, we have to load the stored size. Note that
  1496. // this is the size of the VLA in bytes, not its size in elements.
  1497. llvm::Value *numVLAElements = nullptr;
  1498. if (isa<VariableArrayType>(arrayType)) {
  1499. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
  1500. // Walk into all VLAs. This doesn't require changes to addr,
  1501. // which has type T* where T is the first non-VLA element type.
  1502. do {
  1503. QualType elementType = arrayType->getElementType();
  1504. arrayType = getContext().getAsArrayType(elementType);
  1505. // If we only have VLA components, 'addr' requires no adjustment.
  1506. if (!arrayType) {
  1507. baseType = elementType;
  1508. return numVLAElements;
  1509. }
  1510. } while (isa<VariableArrayType>(arrayType));
  1511. // We get out here only if we find a constant array type
  1512. // inside the VLA.
  1513. }
  1514. // We have some number of constant-length arrays, so addr should
  1515. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1516. // down to the first element of addr.
  1517. SmallVector<llvm::Value*, 8> gepIndices;
  1518. // GEP down to the array type.
  1519. llvm::ConstantInt *zero = Builder.getInt32(0);
  1520. gepIndices.push_back(zero);
  1521. uint64_t countFromCLAs = 1;
  1522. QualType eltType;
  1523. llvm::ArrayType *llvmArrayType =
  1524. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1525. while (llvmArrayType) {
  1526. assert(isa<ConstantArrayType>(arrayType));
  1527. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1528. == llvmArrayType->getNumElements());
  1529. gepIndices.push_back(zero);
  1530. countFromCLAs *= llvmArrayType->getNumElements();
  1531. eltType = arrayType->getElementType();
  1532. llvmArrayType =
  1533. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1534. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1535. assert((!llvmArrayType || arrayType) &&
  1536. "LLVM and Clang types are out-of-synch");
  1537. }
  1538. if (arrayType) {
  1539. // From this point onwards, the Clang array type has been emitted
  1540. // as some other type (probably a packed struct). Compute the array
  1541. // size, and just emit the 'begin' expression as a bitcast.
  1542. while (arrayType) {
  1543. countFromCLAs *=
  1544. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1545. eltType = arrayType->getElementType();
  1546. arrayType = getContext().getAsArrayType(eltType);
  1547. }
  1548. llvm::Type *baseType = ConvertType(eltType);
  1549. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1550. } else {
  1551. // Create the actual GEP.
  1552. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1553. gepIndices, "array.begin"),
  1554. addr.getAlignment());
  1555. }
  1556. baseType = eltType;
  1557. llvm::Value *numElements
  1558. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1559. // If we had any VLA dimensions, factor them in.
  1560. if (numVLAElements)
  1561. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1562. return numElements;
  1563. }
  1564. CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
  1565. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1566. assert(vla && "type was not a variable array type!");
  1567. return getVLASize(vla);
  1568. }
  1569. CodeGenFunction::VlaSizePair
  1570. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1571. // The number of elements so far; always size_t.
  1572. llvm::Value *numElements = nullptr;
  1573. QualType elementType;
  1574. do {
  1575. elementType = type->getElementType();
  1576. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1577. assert(vlaSize && "no size for VLA!");
  1578. assert(vlaSize->getType() == SizeTy);
  1579. if (!numElements) {
  1580. numElements = vlaSize;
  1581. } else {
  1582. // It's undefined behavior if this wraps around, so mark it that way.
  1583. // FIXME: Teach -fsanitize=undefined to trap this.
  1584. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1585. }
  1586. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1587. return { numElements, elementType };
  1588. }
  1589. CodeGenFunction::VlaSizePair
  1590. CodeGenFunction::getVLAElements1D(QualType type) {
  1591. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1592. assert(vla && "type was not a variable array type!");
  1593. return getVLAElements1D(vla);
  1594. }
  1595. CodeGenFunction::VlaSizePair
  1596. CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
  1597. llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
  1598. assert(VlaSize && "no size for VLA!");
  1599. assert(VlaSize->getType() == SizeTy);
  1600. return { VlaSize, Vla->getElementType() };
  1601. }
  1602. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1603. assert(type->isVariablyModifiedType() &&
  1604. "Must pass variably modified type to EmitVLASizes!");
  1605. EnsureInsertPoint();
  1606. // We're going to walk down into the type and look for VLA
  1607. // expressions.
  1608. do {
  1609. assert(type->isVariablyModifiedType());
  1610. const Type *ty = type.getTypePtr();
  1611. switch (ty->getTypeClass()) {
  1612. #define TYPE(Class, Base)
  1613. #define ABSTRACT_TYPE(Class, Base)
  1614. #define NON_CANONICAL_TYPE(Class, Base)
  1615. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1616. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1617. #include "clang/AST/TypeNodes.def"
  1618. llvm_unreachable("unexpected dependent type!");
  1619. // These types are never variably-modified.
  1620. case Type::Builtin:
  1621. case Type::Complex:
  1622. case Type::Vector:
  1623. case Type::ExtVector:
  1624. case Type::Record:
  1625. case Type::Enum:
  1626. case Type::Elaborated:
  1627. case Type::TemplateSpecialization:
  1628. case Type::ObjCTypeParam:
  1629. case Type::ObjCObject:
  1630. case Type::ObjCInterface:
  1631. case Type::ObjCObjectPointer:
  1632. llvm_unreachable("type class is never variably-modified!");
  1633. case Type::Adjusted:
  1634. type = cast<AdjustedType>(ty)->getAdjustedType();
  1635. break;
  1636. case Type::Decayed:
  1637. type = cast<DecayedType>(ty)->getPointeeType();
  1638. break;
  1639. case Type::Pointer:
  1640. type = cast<PointerType>(ty)->getPointeeType();
  1641. break;
  1642. case Type::BlockPointer:
  1643. type = cast<BlockPointerType>(ty)->getPointeeType();
  1644. break;
  1645. case Type::LValueReference:
  1646. case Type::RValueReference:
  1647. type = cast<ReferenceType>(ty)->getPointeeType();
  1648. break;
  1649. case Type::MemberPointer:
  1650. type = cast<MemberPointerType>(ty)->getPointeeType();
  1651. break;
  1652. case Type::ConstantArray:
  1653. case Type::IncompleteArray:
  1654. // Losing element qualification here is fine.
  1655. type = cast<ArrayType>(ty)->getElementType();
  1656. break;
  1657. case Type::VariableArray: {
  1658. // Losing element qualification here is fine.
  1659. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1660. // Unknown size indication requires no size computation.
  1661. // Otherwise, evaluate and record it.
  1662. if (const Expr *size = vat->getSizeExpr()) {
  1663. // It's possible that we might have emitted this already,
  1664. // e.g. with a typedef and a pointer to it.
  1665. llvm::Value *&entry = VLASizeMap[size];
  1666. if (!entry) {
  1667. llvm::Value *Size = EmitScalarExpr(size);
  1668. // C11 6.7.6.2p5:
  1669. // If the size is an expression that is not an integer constant
  1670. // expression [...] each time it is evaluated it shall have a value
  1671. // greater than zero.
  1672. if (SanOpts.has(SanitizerKind::VLABound) &&
  1673. size->getType()->isSignedIntegerType()) {
  1674. SanitizerScope SanScope(this);
  1675. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1676. llvm::Constant *StaticArgs[] = {
  1677. EmitCheckSourceLocation(size->getBeginLoc()),
  1678. EmitCheckTypeDescriptor(size->getType())};
  1679. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1680. SanitizerKind::VLABound),
  1681. SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
  1682. }
  1683. // Always zexting here would be wrong if it weren't
  1684. // undefined behavior to have a negative bound.
  1685. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1686. }
  1687. }
  1688. type = vat->getElementType();
  1689. break;
  1690. }
  1691. case Type::FunctionProto:
  1692. case Type::FunctionNoProto:
  1693. type = cast<FunctionType>(ty)->getReturnType();
  1694. break;
  1695. case Type::Paren:
  1696. case Type::TypeOf:
  1697. case Type::UnaryTransform:
  1698. case Type::Attributed:
  1699. case Type::SubstTemplateTypeParm:
  1700. case Type::PackExpansion:
  1701. case Type::MacroQualified:
  1702. // Keep walking after single level desugaring.
  1703. type = type.getSingleStepDesugaredType(getContext());
  1704. break;
  1705. case Type::Typedef:
  1706. case Type::Decltype:
  1707. case Type::Auto:
  1708. case Type::DeducedTemplateSpecialization:
  1709. // Stop walking: nothing to do.
  1710. return;
  1711. case Type::TypeOfExpr:
  1712. // Stop walking: emit typeof expression.
  1713. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1714. return;
  1715. case Type::Atomic:
  1716. type = cast<AtomicType>(ty)->getValueType();
  1717. break;
  1718. case Type::Pipe:
  1719. type = cast<PipeType>(ty)->getElementType();
  1720. break;
  1721. }
  1722. } while (type->isVariablyModifiedType());
  1723. }
  1724. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1725. if (getContext().getBuiltinVaListType()->isArrayType())
  1726. return EmitPointerWithAlignment(E);
  1727. return EmitLValue(E).getAddress();
  1728. }
  1729. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1730. return EmitLValue(E).getAddress();
  1731. }
  1732. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1733. const APValue &Init) {
  1734. assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
  1735. if (CGDebugInfo *Dbg = getDebugInfo())
  1736. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1737. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1738. }
  1739. CodeGenFunction::PeepholeProtection
  1740. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1741. // At the moment, the only aggressive peephole we do in IR gen
  1742. // is trunc(zext) folding, but if we add more, we can easily
  1743. // extend this protection.
  1744. if (!rvalue.isScalar()) return PeepholeProtection();
  1745. llvm::Value *value = rvalue.getScalarVal();
  1746. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1747. // Just make an extra bitcast.
  1748. assert(HaveInsertPoint());
  1749. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1750. Builder.GetInsertBlock());
  1751. PeepholeProtection protection;
  1752. protection.Inst = inst;
  1753. return protection;
  1754. }
  1755. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1756. if (!protection.Inst) return;
  1757. // In theory, we could try to duplicate the peepholes now, but whatever.
  1758. protection.Inst->eraseFromParent();
  1759. }
  1760. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1761. QualType Ty, SourceLocation Loc,
  1762. SourceLocation AssumptionLoc,
  1763. llvm::Value *Alignment,
  1764. llvm::Value *OffsetValue) {
  1765. llvm::Value *TheCheck;
  1766. llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
  1767. CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
  1768. if (SanOpts.has(SanitizerKind::Alignment)) {
  1769. EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  1770. OffsetValue, TheCheck, Assumption);
  1771. }
  1772. }
  1773. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1774. QualType Ty, SourceLocation Loc,
  1775. SourceLocation AssumptionLoc,
  1776. unsigned Alignment,
  1777. llvm::Value *OffsetValue) {
  1778. llvm::Value *TheCheck;
  1779. llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
  1780. CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
  1781. if (SanOpts.has(SanitizerKind::Alignment)) {
  1782. llvm::Value *AlignmentVal = llvm::ConstantInt::get(IntPtrTy, Alignment);
  1783. EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, AlignmentVal,
  1784. OffsetValue, TheCheck, Assumption);
  1785. }
  1786. }
  1787. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1788. const Expr *E,
  1789. SourceLocation AssumptionLoc,
  1790. unsigned Alignment,
  1791. llvm::Value *OffsetValue) {
  1792. if (auto *CE = dyn_cast<CastExpr>(E))
  1793. E = CE->getSubExprAsWritten();
  1794. QualType Ty = E->getType();
  1795. SourceLocation Loc = E->getExprLoc();
  1796. EmitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  1797. OffsetValue);
  1798. }
  1799. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
  1800. llvm::Value *AnnotatedVal,
  1801. StringRef AnnotationStr,
  1802. SourceLocation Location) {
  1803. llvm::Value *Args[4] = {
  1804. AnnotatedVal,
  1805. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1806. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1807. CGM.EmitAnnotationLineNo(Location)
  1808. };
  1809. return Builder.CreateCall(AnnotationFn, Args);
  1810. }
  1811. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1812. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1813. // FIXME We create a new bitcast for every annotation because that's what
  1814. // llvm-gcc was doing.
  1815. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1816. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1817. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1818. I->getAnnotation(), D->getLocation());
  1819. }
  1820. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1821. Address Addr) {
  1822. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1823. llvm::Value *V = Addr.getPointer();
  1824. llvm::Type *VTy = V->getType();
  1825. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1826. CGM.Int8PtrTy);
  1827. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1828. // FIXME Always emit the cast inst so we can differentiate between
  1829. // annotation on the first field of a struct and annotation on the struct
  1830. // itself.
  1831. if (VTy != CGM.Int8PtrTy)
  1832. V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
  1833. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1834. V = Builder.CreateBitCast(V, VTy);
  1835. }
  1836. return Address(V, Addr.getAlignment());
  1837. }
  1838. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1839. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1840. : CGF(CGF) {
  1841. assert(!CGF->IsSanitizerScope);
  1842. CGF->IsSanitizerScope = true;
  1843. }
  1844. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1845. CGF->IsSanitizerScope = false;
  1846. }
  1847. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1848. const llvm::Twine &Name,
  1849. llvm::BasicBlock *BB,
  1850. llvm::BasicBlock::iterator InsertPt) const {
  1851. LoopStack.InsertHelper(I);
  1852. if (IsSanitizerScope)
  1853. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1854. }
  1855. void CGBuilderInserter::InsertHelper(
  1856. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1857. llvm::BasicBlock::iterator InsertPt) const {
  1858. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1859. if (CGF)
  1860. CGF->InsertHelper(I, Name, BB, InsertPt);
  1861. }
  1862. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1863. CodeGenModule &CGM, const FunctionDecl *FD,
  1864. std::string &FirstMissing) {
  1865. // If there aren't any required features listed then go ahead and return.
  1866. if (ReqFeatures.empty())
  1867. return false;
  1868. // Now build up the set of caller features and verify that all the required
  1869. // features are there.
  1870. llvm::StringMap<bool> CallerFeatureMap;
  1871. CGM.getFunctionFeatureMap(CallerFeatureMap, GlobalDecl().getWithDecl(FD));
  1872. // If we have at least one of the features in the feature list return
  1873. // true, otherwise return false.
  1874. return std::all_of(
  1875. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  1876. SmallVector<StringRef, 1> OrFeatures;
  1877. Feature.split(OrFeatures, '|');
  1878. return llvm::any_of(OrFeatures, [&](StringRef Feature) {
  1879. if (!CallerFeatureMap.lookup(Feature)) {
  1880. FirstMissing = Feature.str();
  1881. return false;
  1882. }
  1883. return true;
  1884. });
  1885. });
  1886. }
  1887. // Emits an error if we don't have a valid set of target features for the
  1888. // called function.
  1889. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  1890. const FunctionDecl *TargetDecl) {
  1891. return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
  1892. }
  1893. // Emits an error if we don't have a valid set of target features for the
  1894. // called function.
  1895. void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
  1896. const FunctionDecl *TargetDecl) {
  1897. // Early exit if this is an indirect call.
  1898. if (!TargetDecl)
  1899. return;
  1900. // Get the current enclosing function if it exists. If it doesn't
  1901. // we can't check the target features anyhow.
  1902. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
  1903. if (!FD)
  1904. return;
  1905. // Grab the required features for the call. For a builtin this is listed in
  1906. // the td file with the default cpu, for an always_inline function this is any
  1907. // listed cpu and any listed features.
  1908. unsigned BuiltinID = TargetDecl->getBuiltinID();
  1909. std::string MissingFeature;
  1910. if (BuiltinID) {
  1911. SmallVector<StringRef, 1> ReqFeatures;
  1912. const char *FeatureList =
  1913. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1914. // Return if the builtin doesn't have any required features.
  1915. if (!FeatureList || StringRef(FeatureList) == "")
  1916. return;
  1917. StringRef(FeatureList).split(ReqFeatures, ',');
  1918. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1919. CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
  1920. << TargetDecl->getDeclName()
  1921. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1922. } else if (TargetDecl->hasAttr<TargetAttr>() ||
  1923. TargetDecl->hasAttr<CPUSpecificAttr>()) {
  1924. // Get the required features for the callee.
  1925. const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
  1926. TargetAttr::ParsedTargetAttr ParsedAttr = CGM.filterFunctionTargetAttrs(TD);
  1927. SmallVector<StringRef, 1> ReqFeatures;
  1928. llvm::StringMap<bool> CalleeFeatureMap;
  1929. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  1930. for (const auto &F : ParsedAttr.Features) {
  1931. if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
  1932. ReqFeatures.push_back(StringRef(F).substr(1));
  1933. }
  1934. for (const auto &F : CalleeFeatureMap) {
  1935. // Only positive features are "required".
  1936. if (F.getValue())
  1937. ReqFeatures.push_back(F.getKey());
  1938. }
  1939. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1940. CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
  1941. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  1942. }
  1943. }
  1944. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  1945. if (!CGM.getCodeGenOpts().SanitizeStats)
  1946. return;
  1947. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  1948. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  1949. CGM.getSanStats().create(IRB, SSK);
  1950. }
  1951. llvm::Value *
  1952. CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
  1953. llvm::Value *Condition = nullptr;
  1954. if (!RO.Conditions.Architecture.empty())
  1955. Condition = EmitX86CpuIs(RO.Conditions.Architecture);
  1956. if (!RO.Conditions.Features.empty()) {
  1957. llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
  1958. Condition =
  1959. Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
  1960. }
  1961. return Condition;
  1962. }
  1963. static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
  1964. llvm::Function *Resolver,
  1965. CGBuilderTy &Builder,
  1966. llvm::Function *FuncToReturn,
  1967. bool SupportsIFunc) {
  1968. if (SupportsIFunc) {
  1969. Builder.CreateRet(FuncToReturn);
  1970. return;
  1971. }
  1972. llvm::SmallVector<llvm::Value *, 10> Args;
  1973. llvm::for_each(Resolver->args(),
  1974. [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
  1975. llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
  1976. Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
  1977. if (Resolver->getReturnType()->isVoidTy())
  1978. Builder.CreateRetVoid();
  1979. else
  1980. Builder.CreateRet(Result);
  1981. }
  1982. void CodeGenFunction::EmitMultiVersionResolver(
  1983. llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
  1984. assert((getContext().getTargetInfo().getTriple().getArch() ==
  1985. llvm::Triple::x86 ||
  1986. getContext().getTargetInfo().getTriple().getArch() ==
  1987. llvm::Triple::x86_64) &&
  1988. "Only implemented for x86 targets");
  1989. bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
  1990. // Main function's basic block.
  1991. llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
  1992. Builder.SetInsertPoint(CurBlock);
  1993. EmitX86CpuInit();
  1994. for (const MultiVersionResolverOption &RO : Options) {
  1995. Builder.SetInsertPoint(CurBlock);
  1996. llvm::Value *Condition = FormResolverCondition(RO);
  1997. // The 'default' or 'generic' case.
  1998. if (!Condition) {
  1999. assert(&RO == Options.end() - 1 &&
  2000. "Default or Generic case must be last");
  2001. CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
  2002. SupportsIFunc);
  2003. return;
  2004. }
  2005. llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
  2006. CGBuilderTy RetBuilder(*this, RetBlock);
  2007. CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
  2008. SupportsIFunc);
  2009. CurBlock = createBasicBlock("resolver_else", Resolver);
  2010. Builder.CreateCondBr(Condition, RetBlock, CurBlock);
  2011. }
  2012. // If no generic/default, emit an unreachable.
  2013. Builder.SetInsertPoint(CurBlock);
  2014. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2015. TrapCall->setDoesNotReturn();
  2016. TrapCall->setDoesNotThrow();
  2017. Builder.CreateUnreachable();
  2018. Builder.ClearInsertionPoint();
  2019. }
  2020. // Loc - where the diagnostic will point, where in the source code this
  2021. // alignment has failed.
  2022. // SecondaryLoc - if present (will be present if sufficiently different from
  2023. // Loc), the diagnostic will additionally point a "Note:" to this location.
  2024. // It should be the location where the __attribute__((assume_aligned))
  2025. // was written e.g.
  2026. void CodeGenFunction::EmitAlignmentAssumptionCheck(
  2027. llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
  2028. SourceLocation SecondaryLoc, llvm::Value *Alignment,
  2029. llvm::Value *OffsetValue, llvm::Value *TheCheck,
  2030. llvm::Instruction *Assumption) {
  2031. assert(Assumption && isa<llvm::CallInst>(Assumption) &&
  2032. cast<llvm::CallInst>(Assumption)->getCalledValue() ==
  2033. llvm::Intrinsic::getDeclaration(
  2034. Builder.GetInsertBlock()->getParent()->getParent(),
  2035. llvm::Intrinsic::assume) &&
  2036. "Assumption should be a call to llvm.assume().");
  2037. assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
  2038. "Assumption should be the last instruction of the basic block, "
  2039. "since the basic block is still being generated.");
  2040. if (!SanOpts.has(SanitizerKind::Alignment))
  2041. return;
  2042. // Don't check pointers to volatile data. The behavior here is implementation-
  2043. // defined.
  2044. if (Ty->getPointeeType().isVolatileQualified())
  2045. return;
  2046. // We need to temorairly remove the assumption so we can insert the
  2047. // sanitizer check before it, else the check will be dropped by optimizations.
  2048. Assumption->removeFromParent();
  2049. {
  2050. SanitizerScope SanScope(this);
  2051. if (!OffsetValue)
  2052. OffsetValue = Builder.getInt1(0); // no offset.
  2053. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
  2054. EmitCheckSourceLocation(SecondaryLoc),
  2055. EmitCheckTypeDescriptor(Ty)};
  2056. llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
  2057. EmitCheckValue(Alignment),
  2058. EmitCheckValue(OffsetValue)};
  2059. EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
  2060. SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
  2061. }
  2062. // We are now in the (new, empty) "cont" basic block.
  2063. // Reintroduce the assumption.
  2064. Builder.Insert(Assumption);
  2065. // FIXME: Assumption still has it's original basic block as it's Parent.
  2066. }
  2067. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  2068. if (CGDebugInfo *DI = getDebugInfo())
  2069. return DI->SourceLocToDebugLoc(Location);
  2070. return llvm::DebugLoc();
  2071. }