CodeGenFunction.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This coordinates the per-function state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGBlocks.h"
  15. #include "CGCleanup.h"
  16. #include "CGCUDARuntime.h"
  17. #include "CGCXXABI.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGOpenMPRuntime.h"
  20. #include "CodeGenModule.h"
  21. #include "CodeGenPGO.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/Decl.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/Basic/Builtins.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/CodeGen/CGFunctionInfo.h"
  30. #include "clang/Frontend/CodeGenOptions.h"
  31. #include "clang/Sema/SemaDiagnostic.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/Intrinsics.h"
  34. #include "llvm/IR/MDBuilder.h"
  35. #include "llvm/IR/Operator.h"
  36. using namespace clang;
  37. using namespace CodeGen;
  38. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  39. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  40. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  41. CGBuilderInserterTy(this)),
  42. CurFn(nullptr), ReturnValue(Address::invalid()),
  43. CapturedStmtInfo(nullptr),
  44. SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
  45. CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
  46. IsOutlinedSEHHelper(false),
  47. BlockInfo(nullptr), BlockPointer(nullptr),
  48. LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
  49. NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
  50. ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
  51. DebugInfo(CGM.getModuleDebugInfo()),
  52. DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
  53. PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
  54. CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
  55. NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
  56. CXXABIThisValue(nullptr), CXXThisValue(nullptr),
  57. CXXStructorImplicitParamDecl(nullptr),
  58. CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
  59. CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
  60. TerminateHandler(nullptr), TrapBB(nullptr) {
  61. if (!suppressNewContext)
  62. CGM.getCXXABI().getMangleContext().startNewFunction();
  63. llvm::FastMathFlags FMF;
  64. if (CGM.getLangOpts().FastMath)
  65. FMF.setUnsafeAlgebra();
  66. if (CGM.getLangOpts().FiniteMathOnly) {
  67. FMF.setNoNaNs();
  68. FMF.setNoInfs();
  69. }
  70. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  71. FMF.setNoNaNs();
  72. }
  73. if (CGM.getCodeGenOpts().NoSignedZeros) {
  74. FMF.setNoSignedZeros();
  75. }
  76. if (CGM.getCodeGenOpts().ReciprocalMath) {
  77. FMF.setAllowReciprocal();
  78. }
  79. Builder.setFastMathFlags(FMF);
  80. }
  81. CodeGenFunction::~CodeGenFunction() {
  82. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  83. // If there are any unclaimed block infos, go ahead and destroy them
  84. // now. This can happen if IR-gen gets clever and skips evaluating
  85. // something.
  86. if (FirstBlockInfo)
  87. destroyBlockInfos(FirstBlockInfo);
  88. if (getLangOpts().OpenMP) {
  89. CGM.getOpenMPRuntime().functionFinished(*this);
  90. }
  91. }
  92. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  93. AlignmentSource *Source) {
  94. return getNaturalTypeAlignment(T->getPointeeType(), Source,
  95. /*forPointee*/ true);
  96. }
  97. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  98. AlignmentSource *Source,
  99. bool forPointeeType) {
  100. // Honor alignment typedef attributes even on incomplete types.
  101. // We also honor them straight for C++ class types, even as pointees;
  102. // there's an expressivity gap here.
  103. if (auto TT = T->getAs<TypedefType>()) {
  104. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  105. if (Source) *Source = AlignmentSource::AttributedType;
  106. return getContext().toCharUnitsFromBits(Align);
  107. }
  108. }
  109. if (Source) *Source = AlignmentSource::Type;
  110. CharUnits Alignment;
  111. if (T->isIncompleteType()) {
  112. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  113. } else {
  114. // For C++ class pointees, we don't know whether we're pointing at a
  115. // base or a complete object, so we generally need to use the
  116. // non-virtual alignment.
  117. const CXXRecordDecl *RD;
  118. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  119. Alignment = CGM.getClassPointerAlignment(RD);
  120. } else {
  121. Alignment = getContext().getTypeAlignInChars(T);
  122. }
  123. // Cap to the global maximum type alignment unless the alignment
  124. // was somehow explicit on the type.
  125. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  126. if (Alignment.getQuantity() > MaxAlign &&
  127. !getContext().isAlignmentRequired(T))
  128. Alignment = CharUnits::fromQuantity(MaxAlign);
  129. }
  130. }
  131. return Alignment;
  132. }
  133. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  134. AlignmentSource AlignSource;
  135. CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
  136. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
  137. CGM.getTBAAInfo(T));
  138. }
  139. /// Given a value of type T* that may not be to a complete object,
  140. /// construct an l-value with the natural pointee alignment of T.
  141. LValue
  142. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  143. AlignmentSource AlignSource;
  144. CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
  145. return MakeAddrLValue(Address(V, Align), T, AlignSource);
  146. }
  147. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  148. return CGM.getTypes().ConvertTypeForMem(T);
  149. }
  150. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  151. return CGM.getTypes().ConvertType(T);
  152. }
  153. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  154. type = type.getCanonicalType();
  155. while (true) {
  156. switch (type->getTypeClass()) {
  157. #define TYPE(name, parent)
  158. #define ABSTRACT_TYPE(name, parent)
  159. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  160. #define DEPENDENT_TYPE(name, parent) case Type::name:
  161. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  162. #include "clang/AST/TypeNodes.def"
  163. llvm_unreachable("non-canonical or dependent type in IR-generation");
  164. case Type::Auto:
  165. llvm_unreachable("undeduced auto type in IR-generation");
  166. // Various scalar types.
  167. case Type::Builtin:
  168. case Type::Pointer:
  169. case Type::BlockPointer:
  170. case Type::LValueReference:
  171. case Type::RValueReference:
  172. case Type::MemberPointer:
  173. case Type::Vector:
  174. case Type::ExtVector:
  175. case Type::FunctionProto:
  176. case Type::FunctionNoProto:
  177. case Type::Enum:
  178. case Type::ObjCObjectPointer:
  179. case Type::Pipe:
  180. return TEK_Scalar;
  181. // Complexes.
  182. case Type::Complex:
  183. return TEK_Complex;
  184. // Arrays, records, and Objective-C objects.
  185. case Type::ConstantArray:
  186. case Type::IncompleteArray:
  187. case Type::VariableArray:
  188. case Type::Record:
  189. case Type::ObjCObject:
  190. case Type::ObjCInterface:
  191. return TEK_Aggregate;
  192. // We operate on atomic values according to their underlying type.
  193. case Type::Atomic:
  194. type = cast<AtomicType>(type)->getValueType();
  195. continue;
  196. }
  197. llvm_unreachable("unknown type kind!");
  198. }
  199. }
  200. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  201. // For cleanliness, we try to avoid emitting the return block for
  202. // simple cases.
  203. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  204. if (CurBB) {
  205. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  206. // We have a valid insert point, reuse it if it is empty or there are no
  207. // explicit jumps to the return block.
  208. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  209. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  210. delete ReturnBlock.getBlock();
  211. } else
  212. EmitBlock(ReturnBlock.getBlock());
  213. return llvm::DebugLoc();
  214. }
  215. // Otherwise, if the return block is the target of a single direct
  216. // branch then we can just put the code in that block instead. This
  217. // cleans up functions which started with a unified return block.
  218. if (ReturnBlock.getBlock()->hasOneUse()) {
  219. llvm::BranchInst *BI =
  220. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  221. if (BI && BI->isUnconditional() &&
  222. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  223. // Record/return the DebugLoc of the simple 'return' expression to be used
  224. // later by the actual 'ret' instruction.
  225. llvm::DebugLoc Loc = BI->getDebugLoc();
  226. Builder.SetInsertPoint(BI->getParent());
  227. BI->eraseFromParent();
  228. delete ReturnBlock.getBlock();
  229. return Loc;
  230. }
  231. }
  232. // FIXME: We are at an unreachable point, there is no reason to emit the block
  233. // unless it has uses. However, we still need a place to put the debug
  234. // region.end for now.
  235. EmitBlock(ReturnBlock.getBlock());
  236. return llvm::DebugLoc();
  237. }
  238. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  239. if (!BB) return;
  240. if (!BB->use_empty())
  241. return CGF.CurFn->getBasicBlockList().push_back(BB);
  242. delete BB;
  243. }
  244. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  245. assert(BreakContinueStack.empty() &&
  246. "mismatched push/pop in break/continue stack!");
  247. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  248. && NumSimpleReturnExprs == NumReturnExprs
  249. && ReturnBlock.getBlock()->use_empty();
  250. // Usually the return expression is evaluated before the cleanup
  251. // code. If the function contains only a simple return statement,
  252. // such as a constant, the location before the cleanup code becomes
  253. // the last useful breakpoint in the function, because the simple
  254. // return expression will be evaluated after the cleanup code. To be
  255. // safe, set the debug location for cleanup code to the location of
  256. // the return statement. Otherwise the cleanup code should be at the
  257. // end of the function's lexical scope.
  258. //
  259. // If there are multiple branches to the return block, the branch
  260. // instructions will get the location of the return statements and
  261. // all will be fine.
  262. if (CGDebugInfo *DI = getDebugInfo()) {
  263. if (OnlySimpleReturnStmts)
  264. DI->EmitLocation(Builder, LastStopPoint);
  265. else
  266. DI->EmitLocation(Builder, EndLoc);
  267. }
  268. // Pop any cleanups that might have been associated with the
  269. // parameters. Do this in whatever block we're currently in; it's
  270. // important to do this before we enter the return block or return
  271. // edges will be *really* confused.
  272. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  273. bool HasOnlyLifetimeMarkers =
  274. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  275. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  276. if (HasCleanups) {
  277. // Make sure the line table doesn't jump back into the body for
  278. // the ret after it's been at EndLoc.
  279. if (CGDebugInfo *DI = getDebugInfo())
  280. if (OnlySimpleReturnStmts)
  281. DI->EmitLocation(Builder, EndLoc);
  282. PopCleanupBlocks(PrologueCleanupDepth);
  283. }
  284. // Emit function epilog (to return).
  285. llvm::DebugLoc Loc = EmitReturnBlock();
  286. if (ShouldInstrumentFunction())
  287. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  288. // Emit debug descriptor for function end.
  289. if (CGDebugInfo *DI = getDebugInfo())
  290. DI->EmitFunctionEnd(Builder);
  291. // Reset the debug location to that of the simple 'return' expression, if any
  292. // rather than that of the end of the function's scope '}'.
  293. ApplyDebugLocation AL(*this, Loc);
  294. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  295. EmitEndEHSpec(CurCodeDecl);
  296. assert(EHStack.empty() &&
  297. "did not remove all scopes from cleanup stack!");
  298. // If someone did an indirect goto, emit the indirect goto block at the end of
  299. // the function.
  300. if (IndirectBranch) {
  301. EmitBlock(IndirectBranch->getParent());
  302. Builder.ClearInsertionPoint();
  303. }
  304. // If some of our locals escaped, insert a call to llvm.localescape in the
  305. // entry block.
  306. if (!EscapedLocals.empty()) {
  307. // Invert the map from local to index into a simple vector. There should be
  308. // no holes.
  309. SmallVector<llvm::Value *, 4> EscapeArgs;
  310. EscapeArgs.resize(EscapedLocals.size());
  311. for (auto &Pair : EscapedLocals)
  312. EscapeArgs[Pair.second] = Pair.first;
  313. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  314. &CGM.getModule(), llvm::Intrinsic::localescape);
  315. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  316. }
  317. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  318. llvm::Instruction *Ptr = AllocaInsertPt;
  319. AllocaInsertPt = nullptr;
  320. Ptr->eraseFromParent();
  321. // If someone took the address of a label but never did an indirect goto, we
  322. // made a zero entry PHI node, which is illegal, zap it now.
  323. if (IndirectBranch) {
  324. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  325. if (PN->getNumIncomingValues() == 0) {
  326. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  327. PN->eraseFromParent();
  328. }
  329. }
  330. EmitIfUsed(*this, EHResumeBlock);
  331. EmitIfUsed(*this, TerminateLandingPad);
  332. EmitIfUsed(*this, TerminateHandler);
  333. EmitIfUsed(*this, UnreachableBlock);
  334. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  335. EmitDeclMetadata();
  336. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  337. I = DeferredReplacements.begin(),
  338. E = DeferredReplacements.end();
  339. I != E; ++I) {
  340. I->first->replaceAllUsesWith(I->second);
  341. I->first->eraseFromParent();
  342. }
  343. }
  344. /// ShouldInstrumentFunction - Return true if the current function should be
  345. /// instrumented with __cyg_profile_func_* calls
  346. bool CodeGenFunction::ShouldInstrumentFunction() {
  347. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  348. return false;
  349. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  350. return false;
  351. return true;
  352. }
  353. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  354. /// instrumentation function with the current function and the call site, if
  355. /// function instrumentation is enabled.
  356. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  357. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  358. llvm::PointerType *PointerTy = Int8PtrTy;
  359. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  360. llvm::FunctionType *FunctionTy =
  361. llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
  362. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  363. llvm::CallInst *CallSite = Builder.CreateCall(
  364. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  365. llvm::ConstantInt::get(Int32Ty, 0),
  366. "callsite");
  367. llvm::Value *args[] = {
  368. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  369. CallSite
  370. };
  371. EmitNounwindRuntimeCall(F, args);
  372. }
  373. void CodeGenFunction::EmitMCountInstrumentation() {
  374. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  375. llvm::Constant *MCountFn =
  376. CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
  377. EmitNounwindRuntimeCall(MCountFn);
  378. }
  379. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  380. // information in the program executable. The argument information stored
  381. // includes the argument name, its type, the address and access qualifiers used.
  382. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  383. CodeGenModule &CGM, llvm::LLVMContext &Context,
  384. SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
  385. CGBuilderTy &Builder, ASTContext &ASTCtx) {
  386. // Create MDNodes that represent the kernel arg metadata.
  387. // Each MDNode is a list in the form of "key", N number of values which is
  388. // the same number of values as their are kernel arguments.
  389. const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
  390. // MDNode for the kernel argument address space qualifiers.
  391. SmallVector<llvm::Metadata *, 8> addressQuals;
  392. addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
  393. // MDNode for the kernel argument access qualifiers (images only).
  394. SmallVector<llvm::Metadata *, 8> accessQuals;
  395. accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
  396. // MDNode for the kernel argument type names.
  397. SmallVector<llvm::Metadata *, 8> argTypeNames;
  398. argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
  399. // MDNode for the kernel argument base type names.
  400. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  401. argBaseTypeNames.push_back(
  402. llvm::MDString::get(Context, "kernel_arg_base_type"));
  403. // MDNode for the kernel argument type qualifiers.
  404. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  405. argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
  406. // MDNode for the kernel argument names.
  407. SmallVector<llvm::Metadata *, 8> argNames;
  408. argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
  409. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  410. const ParmVarDecl *parm = FD->getParamDecl(i);
  411. QualType ty = parm->getType();
  412. std::string typeQuals;
  413. if (ty->isPointerType()) {
  414. QualType pointeeTy = ty->getPointeeType();
  415. // Get address qualifier.
  416. addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
  417. ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
  418. // Get argument type name.
  419. std::string typeName =
  420. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  421. // Turn "unsigned type" to "utype"
  422. std::string::size_type pos = typeName.find("unsigned");
  423. if (pointeeTy.isCanonical() && pos != std::string::npos)
  424. typeName.erase(pos+1, 8);
  425. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  426. std::string baseTypeName =
  427. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  428. Policy) +
  429. "*";
  430. // Turn "unsigned type" to "utype"
  431. pos = baseTypeName.find("unsigned");
  432. if (pos != std::string::npos)
  433. baseTypeName.erase(pos+1, 8);
  434. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  435. // Get argument type qualifiers:
  436. if (ty.isRestrictQualified())
  437. typeQuals = "restrict";
  438. if (pointeeTy.isConstQualified() ||
  439. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  440. typeQuals += typeQuals.empty() ? "const" : " const";
  441. if (pointeeTy.isVolatileQualified())
  442. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  443. } else {
  444. uint32_t AddrSpc = 0;
  445. bool isPipe = ty->isPipeType();
  446. if (ty->isImageType() || isPipe)
  447. AddrSpc =
  448. CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
  449. addressQuals.push_back(
  450. llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
  451. // Get argument type name.
  452. std::string typeName;
  453. if (isPipe)
  454. typeName = cast<PipeType>(ty)->getElementType().getAsString(Policy);
  455. else
  456. typeName = ty.getUnqualifiedType().getAsString(Policy);
  457. // Turn "unsigned type" to "utype"
  458. std::string::size_type pos = typeName.find("unsigned");
  459. if (ty.isCanonical() && pos != std::string::npos)
  460. typeName.erase(pos+1, 8);
  461. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  462. std::string baseTypeName;
  463. if (isPipe)
  464. baseTypeName =
  465. cast<PipeType>(ty)->getElementType().getCanonicalType().getAsString(Policy);
  466. else
  467. baseTypeName =
  468. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  469. // Turn "unsigned type" to "utype"
  470. pos = baseTypeName.find("unsigned");
  471. if (pos != std::string::npos)
  472. baseTypeName.erase(pos+1, 8);
  473. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  474. // Get argument type qualifiers:
  475. if (ty.isConstQualified())
  476. typeQuals = "const";
  477. if (ty.isVolatileQualified())
  478. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  479. if (isPipe)
  480. typeQuals = "pipe";
  481. }
  482. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  483. // Get image and pipe access qualifier:
  484. if (ty->isImageType()|| ty->isPipeType()) {
  485. const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
  486. if (A && A->isWriteOnly())
  487. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  488. else if (A && A->isReadWrite())
  489. accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
  490. else
  491. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  492. } else
  493. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  494. // Get argument name.
  495. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  496. }
  497. kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
  498. kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
  499. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
  500. kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
  501. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
  502. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  503. kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
  504. }
  505. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  506. llvm::Function *Fn)
  507. {
  508. if (!FD->hasAttr<OpenCLKernelAttr>())
  509. return;
  510. llvm::LLVMContext &Context = getLLVMContext();
  511. SmallVector<llvm::Metadata *, 5> kernelMDArgs;
  512. kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
  513. GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
  514. getContext());
  515. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  516. QualType hintQTy = A->getTypeHint();
  517. const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
  518. bool isSignedInteger =
  519. hintQTy->isSignedIntegerType() ||
  520. (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
  521. llvm::Metadata *attrMDArgs[] = {
  522. llvm::MDString::get(Context, "vec_type_hint"),
  523. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  524. CGM.getTypes().ConvertType(A->getTypeHint()))),
  525. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  526. llvm::IntegerType::get(Context, 32),
  527. llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
  528. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  529. }
  530. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  531. llvm::Metadata *attrMDArgs[] = {
  532. llvm::MDString::get(Context, "work_group_size_hint"),
  533. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  534. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  535. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  536. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  537. }
  538. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  539. llvm::Metadata *attrMDArgs[] = {
  540. llvm::MDString::get(Context, "reqd_work_group_size"),
  541. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  542. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  543. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  544. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  545. }
  546. llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
  547. llvm::NamedMDNode *OpenCLKernelMetadata =
  548. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  549. OpenCLKernelMetadata->addOperand(kernelMDNode);
  550. }
  551. /// Determine whether the function F ends with a return stmt.
  552. static bool endsWithReturn(const Decl* F) {
  553. const Stmt *Body = nullptr;
  554. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  555. Body = FD->getBody();
  556. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  557. Body = OMD->getBody();
  558. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  559. auto LastStmt = CS->body_rbegin();
  560. if (LastStmt != CS->body_rend())
  561. return isa<ReturnStmt>(*LastStmt);
  562. }
  563. return false;
  564. }
  565. void CodeGenFunction::StartFunction(GlobalDecl GD,
  566. QualType RetTy,
  567. llvm::Function *Fn,
  568. const CGFunctionInfo &FnInfo,
  569. const FunctionArgList &Args,
  570. SourceLocation Loc,
  571. SourceLocation StartLoc) {
  572. assert(!CurFn &&
  573. "Do not use a CodeGenFunction object for more than one function");
  574. const Decl *D = GD.getDecl();
  575. DidCallStackSave = false;
  576. CurCodeDecl = D;
  577. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  578. if (FD->usesSEHTry())
  579. CurSEHParent = FD;
  580. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  581. FnRetTy = RetTy;
  582. CurFn = Fn;
  583. CurFnInfo = &FnInfo;
  584. assert(CurFn->isDeclaration() && "Function already has body?");
  585. if (CGM.isInSanitizerBlacklist(Fn, Loc))
  586. SanOpts.clear();
  587. if (D) {
  588. // Apply the no_sanitize* attributes to SanOpts.
  589. for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
  590. SanOpts.Mask &= ~Attr->getMask();
  591. }
  592. // Apply sanitizer attributes to the function.
  593. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  594. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  595. if (SanOpts.has(SanitizerKind::Thread))
  596. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  597. if (SanOpts.has(SanitizerKind::Memory))
  598. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  599. if (SanOpts.has(SanitizerKind::SafeStack))
  600. Fn->addFnAttr(llvm::Attribute::SafeStack);
  601. // Pass inline keyword to optimizer if it appears explicitly on any
  602. // declaration. Also, in the case of -fno-inline attach NoInline
  603. // attribute to all function that are not marked AlwaysInline.
  604. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  605. if (!CGM.getCodeGenOpts().NoInline) {
  606. for (auto RI : FD->redecls())
  607. if (RI->isInlineSpecified()) {
  608. Fn->addFnAttr(llvm::Attribute::InlineHint);
  609. break;
  610. }
  611. } else if (!FD->hasAttr<AlwaysInlineAttr>())
  612. Fn->addFnAttr(llvm::Attribute::NoInline);
  613. }
  614. // Add no-jump-tables value.
  615. Fn->addFnAttr("no-jump-tables",
  616. llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
  617. if (getLangOpts().OpenCL) {
  618. // Add metadata for a kernel function.
  619. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  620. EmitOpenCLKernelMetadata(FD, Fn);
  621. }
  622. // If we are checking function types, emit a function type signature as
  623. // prologue data.
  624. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  625. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  626. if (llvm::Constant *PrologueSig =
  627. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  628. llvm::Constant *FTRTTIConst =
  629. CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
  630. llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
  631. llvm::Constant *PrologueStructConst =
  632. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  633. Fn->setPrologueData(PrologueStructConst);
  634. }
  635. }
  636. }
  637. // If we're in C++ mode and the function name is "main", it is guaranteed
  638. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  639. // used within a program").
  640. if (getLangOpts().CPlusPlus)
  641. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  642. if (FD->isMain())
  643. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  644. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  645. // Create a marker to make it easy to insert allocas into the entryblock
  646. // later. Don't create this with the builder, because we don't want it
  647. // folded.
  648. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  649. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  650. ReturnBlock = getJumpDestInCurrentScope("return");
  651. Builder.SetInsertPoint(EntryBB);
  652. // Emit subprogram debug descriptor.
  653. if (CGDebugInfo *DI = getDebugInfo()) {
  654. SmallVector<QualType, 16> ArgTypes;
  655. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  656. i != e; ++i) {
  657. ArgTypes.push_back((*i)->getType());
  658. }
  659. QualType FnType =
  660. getContext().getFunctionType(RetTy, ArgTypes,
  661. FunctionProtoType::ExtProtoInfo());
  662. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
  663. }
  664. if (ShouldInstrumentFunction())
  665. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  666. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  667. EmitMCountInstrumentation();
  668. if (RetTy->isVoidType()) {
  669. // Void type; nothing to return.
  670. ReturnValue = Address::invalid();
  671. // Count the implicit return.
  672. if (!endsWithReturn(D))
  673. ++NumReturnExprs;
  674. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  675. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  676. // Indirect aggregate return; emit returned value directly into sret slot.
  677. // This reduces code size, and affects correctness in C++.
  678. auto AI = CurFn->arg_begin();
  679. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  680. ++AI;
  681. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  682. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  683. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  684. // Load the sret pointer from the argument struct and return into that.
  685. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  686. llvm::Function::arg_iterator EI = CurFn->arg_end();
  687. --EI;
  688. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  689. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  690. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  691. } else {
  692. ReturnValue = CreateIRTemp(RetTy, "retval");
  693. // Tell the epilog emitter to autorelease the result. We do this
  694. // now so that various specialized functions can suppress it
  695. // during their IR-generation.
  696. if (getLangOpts().ObjCAutoRefCount &&
  697. !CurFnInfo->isReturnsRetained() &&
  698. RetTy->isObjCRetainableType())
  699. AutoreleaseResult = true;
  700. }
  701. EmitStartEHSpec(CurCodeDecl);
  702. PrologueCleanupDepth = EHStack.stable_begin();
  703. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  704. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  705. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  706. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  707. if (MD->getParent()->isLambda() &&
  708. MD->getOverloadedOperator() == OO_Call) {
  709. // We're in a lambda; figure out the captures.
  710. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  711. LambdaThisCaptureField);
  712. if (LambdaThisCaptureField) {
  713. // If the lambda captures the object referred to by '*this' - either by
  714. // value or by reference, make sure CXXThisValue points to the correct
  715. // object.
  716. // Get the lvalue for the field (which is a copy of the enclosing object
  717. // or contains the address of the enclosing object).
  718. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  719. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  720. // If the enclosing object was captured by value, just use its address.
  721. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  722. } else {
  723. // Load the lvalue pointed to by the field, since '*this' was captured
  724. // by reference.
  725. CXXThisValue =
  726. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  727. }
  728. }
  729. for (auto *FD : MD->getParent()->fields()) {
  730. if (FD->hasCapturedVLAType()) {
  731. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  732. SourceLocation()).getScalarVal();
  733. auto VAT = FD->getCapturedVLAType();
  734. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  735. }
  736. }
  737. } else {
  738. // Not in a lambda; just use 'this' from the method.
  739. // FIXME: Should we generate a new load for each use of 'this'? The
  740. // fast register allocator would be happier...
  741. CXXThisValue = CXXABIThisValue;
  742. }
  743. }
  744. // If any of the arguments have a variably modified type, make sure to
  745. // emit the type size.
  746. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  747. i != e; ++i) {
  748. const VarDecl *VD = *i;
  749. // Dig out the type as written from ParmVarDecls; it's unclear whether
  750. // the standard (C99 6.9.1p10) requires this, but we're following the
  751. // precedent set by gcc.
  752. QualType Ty;
  753. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  754. Ty = PVD->getOriginalType();
  755. else
  756. Ty = VD->getType();
  757. if (Ty->isVariablyModifiedType())
  758. EmitVariablyModifiedType(Ty);
  759. }
  760. // Emit a location at the end of the prologue.
  761. if (CGDebugInfo *DI = getDebugInfo())
  762. DI->EmitLocation(Builder, StartLoc);
  763. }
  764. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  765. const Stmt *Body) {
  766. incrementProfileCounter(Body);
  767. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  768. EmitCompoundStmtWithoutScope(*S);
  769. else
  770. EmitStmt(Body);
  771. }
  772. /// When instrumenting to collect profile data, the counts for some blocks
  773. /// such as switch cases need to not include the fall-through counts, so
  774. /// emit a branch around the instrumentation code. When not instrumenting,
  775. /// this just calls EmitBlock().
  776. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  777. const Stmt *S) {
  778. llvm::BasicBlock *SkipCountBB = nullptr;
  779. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  780. // When instrumenting for profiling, the fallthrough to certain
  781. // statements needs to skip over the instrumentation code so that we
  782. // get an accurate count.
  783. SkipCountBB = createBasicBlock("skipcount");
  784. EmitBranch(SkipCountBB);
  785. }
  786. EmitBlock(BB);
  787. uint64_t CurrentCount = getCurrentProfileCount();
  788. incrementProfileCounter(S);
  789. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  790. if (SkipCountBB)
  791. EmitBlock(SkipCountBB);
  792. }
  793. /// Tries to mark the given function nounwind based on the
  794. /// non-existence of any throwing calls within it. We believe this is
  795. /// lightweight enough to do at -O0.
  796. static void TryMarkNoThrow(llvm::Function *F) {
  797. // LLVM treats 'nounwind' on a function as part of the type, so we
  798. // can't do this on functions that can be overwritten.
  799. if (F->isInterposable()) return;
  800. for (llvm::BasicBlock &BB : *F)
  801. for (llvm::Instruction &I : BB)
  802. if (I.mayThrow())
  803. return;
  804. F->setDoesNotThrow();
  805. }
  806. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  807. const CGFunctionInfo &FnInfo) {
  808. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  809. // Check if we should generate debug info for this function.
  810. if (FD->hasAttr<NoDebugAttr>())
  811. DebugInfo = nullptr; // disable debug info indefinitely for this function
  812. FunctionArgList Args;
  813. QualType ResTy = FD->getReturnType();
  814. CurGD = GD;
  815. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  816. if (MD && MD->isInstance()) {
  817. if (CGM.getCXXABI().HasThisReturn(GD))
  818. ResTy = MD->getThisType(getContext());
  819. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  820. ResTy = CGM.getContext().VoidPtrTy;
  821. CGM.getCXXABI().buildThisParam(*this, Args);
  822. }
  823. for (auto *Param : FD->params()) {
  824. Args.push_back(Param);
  825. if (!Param->hasAttr<PassObjectSizeAttr>())
  826. continue;
  827. IdentifierInfo *NoID = nullptr;
  828. auto *Implicit = ImplicitParamDecl::Create(
  829. getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
  830. getContext().getSizeType());
  831. SizeArguments[Param] = Implicit;
  832. Args.push_back(Implicit);
  833. }
  834. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  835. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  836. SourceRange BodyRange;
  837. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  838. CurEHLocation = BodyRange.getEnd();
  839. // Use the location of the start of the function to determine where
  840. // the function definition is located. By default use the location
  841. // of the declaration as the location for the subprogram. A function
  842. // may lack a declaration in the source code if it is created by code
  843. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  844. SourceLocation Loc = FD->getLocation();
  845. // If this is a function specialization then use the pattern body
  846. // as the location for the function.
  847. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  848. if (SpecDecl->hasBody(SpecDecl))
  849. Loc = SpecDecl->getLocation();
  850. // Emit the standard function prologue.
  851. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  852. // Generate the body of the function.
  853. PGO.assignRegionCounters(GD, CurFn);
  854. if (isa<CXXDestructorDecl>(FD))
  855. EmitDestructorBody(Args);
  856. else if (isa<CXXConstructorDecl>(FD))
  857. EmitConstructorBody(Args);
  858. else if (getLangOpts().CUDA &&
  859. !getLangOpts().CUDAIsDevice &&
  860. FD->hasAttr<CUDAGlobalAttr>())
  861. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  862. else if (isa<CXXConversionDecl>(FD) &&
  863. cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
  864. // The lambda conversion to block pointer is special; the semantics can't be
  865. // expressed in the AST, so IRGen needs to special-case it.
  866. EmitLambdaToBlockPointerBody(Args);
  867. } else if (isa<CXXMethodDecl>(FD) &&
  868. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  869. // The lambda static invoker function is special, because it forwards or
  870. // clones the body of the function call operator (but is actually static).
  871. EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
  872. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  873. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  874. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  875. // Implicit copy-assignment gets the same special treatment as implicit
  876. // copy-constructors.
  877. emitImplicitAssignmentOperatorBody(Args);
  878. } else if (Stmt *Body = FD->getBody()) {
  879. EmitFunctionBody(Args, Body);
  880. } else
  881. llvm_unreachable("no definition for emitted function");
  882. // C++11 [stmt.return]p2:
  883. // Flowing off the end of a function [...] results in undefined behavior in
  884. // a value-returning function.
  885. // C11 6.9.1p12:
  886. // If the '}' that terminates a function is reached, and the value of the
  887. // function call is used by the caller, the behavior is undefined.
  888. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  889. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  890. if (SanOpts.has(SanitizerKind::Return)) {
  891. SanitizerScope SanScope(this);
  892. llvm::Value *IsFalse = Builder.getFalse();
  893. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  894. "missing_return", EmitCheckSourceLocation(FD->getLocation()),
  895. None);
  896. } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  897. EmitTrapCall(llvm::Intrinsic::trap);
  898. }
  899. Builder.CreateUnreachable();
  900. Builder.ClearInsertionPoint();
  901. }
  902. // Emit the standard function epilogue.
  903. FinishFunction(BodyRange.getEnd());
  904. // If we haven't marked the function nothrow through other means, do
  905. // a quick pass now to see if we can.
  906. if (!CurFn->doesNotThrow())
  907. TryMarkNoThrow(CurFn);
  908. }
  909. /// ContainsLabel - Return true if the statement contains a label in it. If
  910. /// this statement is not executed normally, it not containing a label means
  911. /// that we can just remove the code.
  912. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  913. // Null statement, not a label!
  914. if (!S) return false;
  915. // If this is a label, we have to emit the code, consider something like:
  916. // if (0) { ... foo: bar(); } goto foo;
  917. //
  918. // TODO: If anyone cared, we could track __label__'s, since we know that you
  919. // can't jump to one from outside their declared region.
  920. if (isa<LabelStmt>(S))
  921. return true;
  922. // If this is a case/default statement, and we haven't seen a switch, we have
  923. // to emit the code.
  924. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  925. return true;
  926. // If this is a switch statement, we want to ignore cases below it.
  927. if (isa<SwitchStmt>(S))
  928. IgnoreCaseStmts = true;
  929. // Scan subexpressions for verboten labels.
  930. for (const Stmt *SubStmt : S->children())
  931. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  932. return true;
  933. return false;
  934. }
  935. /// containsBreak - Return true if the statement contains a break out of it.
  936. /// If the statement (recursively) contains a switch or loop with a break
  937. /// inside of it, this is fine.
  938. bool CodeGenFunction::containsBreak(const Stmt *S) {
  939. // Null statement, not a label!
  940. if (!S) return false;
  941. // If this is a switch or loop that defines its own break scope, then we can
  942. // include it and anything inside of it.
  943. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  944. isa<ForStmt>(S))
  945. return false;
  946. if (isa<BreakStmt>(S))
  947. return true;
  948. // Scan subexpressions for verboten breaks.
  949. for (const Stmt *SubStmt : S->children())
  950. if (containsBreak(SubStmt))
  951. return true;
  952. return false;
  953. }
  954. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  955. /// to a constant, or if it does but contains a label, return false. If it
  956. /// constant folds return true and set the boolean result in Result.
  957. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  958. bool &ResultBool) {
  959. llvm::APSInt ResultInt;
  960. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  961. return false;
  962. ResultBool = ResultInt.getBoolValue();
  963. return true;
  964. }
  965. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  966. /// to a constant, or if it does but contains a label, return false. If it
  967. /// constant folds return true and set the folded value.
  968. bool CodeGenFunction::
  969. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
  970. // FIXME: Rename and handle conversion of other evaluatable things
  971. // to bool.
  972. llvm::APSInt Int;
  973. if (!Cond->EvaluateAsInt(Int, getContext()))
  974. return false; // Not foldable, not integer or not fully evaluatable.
  975. if (CodeGenFunction::ContainsLabel(Cond))
  976. return false; // Contains a label.
  977. ResultInt = Int;
  978. return true;
  979. }
  980. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  981. /// statement) to the specified blocks. Based on the condition, this might try
  982. /// to simplify the codegen of the conditional based on the branch.
  983. ///
  984. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  985. llvm::BasicBlock *TrueBlock,
  986. llvm::BasicBlock *FalseBlock,
  987. uint64_t TrueCount) {
  988. Cond = Cond->IgnoreParens();
  989. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  990. // Handle X && Y in a condition.
  991. if (CondBOp->getOpcode() == BO_LAnd) {
  992. // If we have "1 && X", simplify the code. "0 && X" would have constant
  993. // folded if the case was simple enough.
  994. bool ConstantBool = false;
  995. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  996. ConstantBool) {
  997. // br(1 && X) -> br(X).
  998. incrementProfileCounter(CondBOp);
  999. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1000. TrueCount);
  1001. }
  1002. // If we have "X && 1", simplify the code to use an uncond branch.
  1003. // "X && 0" would have been constant folded to 0.
  1004. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1005. ConstantBool) {
  1006. // br(X && 1) -> br(X).
  1007. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1008. TrueCount);
  1009. }
  1010. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1011. // want to jump to the FalseBlock.
  1012. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1013. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1014. // can be propagated to that branch.
  1015. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1016. ConditionalEvaluation eval(*this);
  1017. {
  1018. ApplyDebugLocation DL(*this, Cond);
  1019. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1020. EmitBlock(LHSTrue);
  1021. }
  1022. incrementProfileCounter(CondBOp);
  1023. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1024. // Any temporaries created here are conditional.
  1025. eval.begin(*this);
  1026. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1027. eval.end(*this);
  1028. return;
  1029. }
  1030. if (CondBOp->getOpcode() == BO_LOr) {
  1031. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1032. // folded if the case was simple enough.
  1033. bool ConstantBool = false;
  1034. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1035. !ConstantBool) {
  1036. // br(0 || X) -> br(X).
  1037. incrementProfileCounter(CondBOp);
  1038. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1039. TrueCount);
  1040. }
  1041. // If we have "X || 0", simplify the code to use an uncond branch.
  1042. // "X || 1" would have been constant folded to 1.
  1043. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1044. !ConstantBool) {
  1045. // br(X || 0) -> br(X).
  1046. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1047. TrueCount);
  1048. }
  1049. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1050. // want to jump to the TrueBlock.
  1051. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1052. // We have the count for entry to the RHS and for the whole expression
  1053. // being true, so we can divy up True count between the short circuit and
  1054. // the RHS.
  1055. uint64_t LHSCount =
  1056. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1057. uint64_t RHSCount = TrueCount - LHSCount;
  1058. ConditionalEvaluation eval(*this);
  1059. {
  1060. ApplyDebugLocation DL(*this, Cond);
  1061. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1062. EmitBlock(LHSFalse);
  1063. }
  1064. incrementProfileCounter(CondBOp);
  1065. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1066. // Any temporaries created here are conditional.
  1067. eval.begin(*this);
  1068. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1069. eval.end(*this);
  1070. return;
  1071. }
  1072. }
  1073. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1074. // br(!x, t, f) -> br(x, f, t)
  1075. if (CondUOp->getOpcode() == UO_LNot) {
  1076. // Negate the count.
  1077. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1078. // Negate the condition and swap the destination blocks.
  1079. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1080. FalseCount);
  1081. }
  1082. }
  1083. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1084. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1085. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1086. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1087. ConditionalEvaluation cond(*this);
  1088. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1089. getProfileCount(CondOp));
  1090. // When computing PGO branch weights, we only know the overall count for
  1091. // the true block. This code is essentially doing tail duplication of the
  1092. // naive code-gen, introducing new edges for which counts are not
  1093. // available. Divide the counts proportionally between the LHS and RHS of
  1094. // the conditional operator.
  1095. uint64_t LHSScaledTrueCount = 0;
  1096. if (TrueCount) {
  1097. double LHSRatio =
  1098. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1099. LHSScaledTrueCount = TrueCount * LHSRatio;
  1100. }
  1101. cond.begin(*this);
  1102. EmitBlock(LHSBlock);
  1103. incrementProfileCounter(CondOp);
  1104. {
  1105. ApplyDebugLocation DL(*this, Cond);
  1106. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1107. LHSScaledTrueCount);
  1108. }
  1109. cond.end(*this);
  1110. cond.begin(*this);
  1111. EmitBlock(RHSBlock);
  1112. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1113. TrueCount - LHSScaledTrueCount);
  1114. cond.end(*this);
  1115. return;
  1116. }
  1117. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1118. // Conditional operator handling can give us a throw expression as a
  1119. // condition for a case like:
  1120. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1121. // Fold this to:
  1122. // br(c, throw x, br(y, t, f))
  1123. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1124. return;
  1125. }
  1126. // If the branch has a condition wrapped by __builtin_unpredictable,
  1127. // create metadata that specifies that the branch is unpredictable.
  1128. // Don't bother if not optimizing because that metadata would not be used.
  1129. llvm::MDNode *Unpredictable = nullptr;
  1130. if (CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1131. if (const CallExpr *Call = dyn_cast<CallExpr>(Cond)) {
  1132. const Decl *TargetDecl = Call->getCalleeDecl();
  1133. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
  1134. if (FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1135. llvm::MDBuilder MDHelper(getLLVMContext());
  1136. Unpredictable = MDHelper.createUnpredictable();
  1137. }
  1138. }
  1139. }
  1140. }
  1141. // Create branch weights based on the number of times we get here and the
  1142. // number of times the condition should be true.
  1143. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1144. llvm::MDNode *Weights =
  1145. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1146. // Emit the code with the fully general case.
  1147. llvm::Value *CondV;
  1148. {
  1149. ApplyDebugLocation DL(*this, Cond);
  1150. CondV = EvaluateExprAsBool(Cond);
  1151. }
  1152. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1153. }
  1154. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1155. /// specified stmt yet.
  1156. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1157. CGM.ErrorUnsupported(S, Type);
  1158. }
  1159. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1160. /// variable-length array whose elements have a non-zero bit-pattern.
  1161. ///
  1162. /// \param baseType the inner-most element type of the array
  1163. /// \param src - a char* pointing to the bit-pattern for a single
  1164. /// base element of the array
  1165. /// \param sizeInChars - the total size of the VLA, in chars
  1166. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1167. Address dest, Address src,
  1168. llvm::Value *sizeInChars) {
  1169. CGBuilderTy &Builder = CGF.Builder;
  1170. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1171. llvm::Value *baseSizeInChars
  1172. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1173. Address begin =
  1174. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1175. llvm::Value *end =
  1176. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1177. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1178. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1179. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1180. // Make a loop over the VLA. C99 guarantees that the VLA element
  1181. // count must be nonzero.
  1182. CGF.EmitBlock(loopBB);
  1183. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1184. cur->addIncoming(begin.getPointer(), originBB);
  1185. CharUnits curAlign =
  1186. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1187. // memcpy the individual element bit-pattern.
  1188. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1189. /*volatile*/ false);
  1190. // Go to the next element.
  1191. llvm::Value *next =
  1192. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1193. // Leave if that's the end of the VLA.
  1194. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1195. Builder.CreateCondBr(done, contBB, loopBB);
  1196. cur->addIncoming(next, loopBB);
  1197. CGF.EmitBlock(contBB);
  1198. }
  1199. void
  1200. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1201. // Ignore empty classes in C++.
  1202. if (getLangOpts().CPlusPlus) {
  1203. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1204. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1205. return;
  1206. }
  1207. }
  1208. // Cast the dest ptr to the appropriate i8 pointer type.
  1209. if (DestPtr.getElementType() != Int8Ty)
  1210. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1211. // Get size and alignment info for this aggregate.
  1212. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1213. llvm::Value *SizeVal;
  1214. const VariableArrayType *vla;
  1215. // Don't bother emitting a zero-byte memset.
  1216. if (size.isZero()) {
  1217. // But note that getTypeInfo returns 0 for a VLA.
  1218. if (const VariableArrayType *vlaType =
  1219. dyn_cast_or_null<VariableArrayType>(
  1220. getContext().getAsArrayType(Ty))) {
  1221. QualType eltType;
  1222. llvm::Value *numElts;
  1223. std::tie(numElts, eltType) = getVLASize(vlaType);
  1224. SizeVal = numElts;
  1225. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  1226. if (!eltSize.isOne())
  1227. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1228. vla = vlaType;
  1229. } else {
  1230. return;
  1231. }
  1232. } else {
  1233. SizeVal = CGM.getSize(size);
  1234. vla = nullptr;
  1235. }
  1236. // If the type contains a pointer to data member we can't memset it to zero.
  1237. // Instead, create a null constant and copy it to the destination.
  1238. // TODO: there are other patterns besides zero that we can usefully memset,
  1239. // like -1, which happens to be the pattern used by member-pointers.
  1240. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1241. // For a VLA, emit a single element, then splat that over the VLA.
  1242. if (vla) Ty = getContext().getBaseElementType(vla);
  1243. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1244. llvm::GlobalVariable *NullVariable =
  1245. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1246. /*isConstant=*/true,
  1247. llvm::GlobalVariable::PrivateLinkage,
  1248. NullConstant, Twine());
  1249. CharUnits NullAlign = DestPtr.getAlignment();
  1250. NullVariable->setAlignment(NullAlign.getQuantity());
  1251. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1252. NullAlign);
  1253. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1254. // Get and call the appropriate llvm.memcpy overload.
  1255. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1256. return;
  1257. }
  1258. // Otherwise, just memset the whole thing to zero. This is legal
  1259. // because in LLVM, all default initializers (other than the ones we just
  1260. // handled above) are guaranteed to have a bit pattern of all zeros.
  1261. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1262. }
  1263. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1264. // Make sure that there is a block for the indirect goto.
  1265. if (!IndirectBranch)
  1266. GetIndirectGotoBlock();
  1267. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1268. // Make sure the indirect branch includes all of the address-taken blocks.
  1269. IndirectBranch->addDestination(BB);
  1270. return llvm::BlockAddress::get(CurFn, BB);
  1271. }
  1272. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1273. // If we already made the indirect branch for indirect goto, return its block.
  1274. if (IndirectBranch) return IndirectBranch->getParent();
  1275. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1276. // Create the PHI node that indirect gotos will add entries to.
  1277. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1278. "indirect.goto.dest");
  1279. // Create the indirect branch instruction.
  1280. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1281. return IndirectBranch->getParent();
  1282. }
  1283. /// Computes the length of an array in elements, as well as the base
  1284. /// element type and a properly-typed first element pointer.
  1285. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1286. QualType &baseType,
  1287. Address &addr) {
  1288. const ArrayType *arrayType = origArrayType;
  1289. // If it's a VLA, we have to load the stored size. Note that
  1290. // this is the size of the VLA in bytes, not its size in elements.
  1291. llvm::Value *numVLAElements = nullptr;
  1292. if (isa<VariableArrayType>(arrayType)) {
  1293. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  1294. // Walk into all VLAs. This doesn't require changes to addr,
  1295. // which has type T* where T is the first non-VLA element type.
  1296. do {
  1297. QualType elementType = arrayType->getElementType();
  1298. arrayType = getContext().getAsArrayType(elementType);
  1299. // If we only have VLA components, 'addr' requires no adjustment.
  1300. if (!arrayType) {
  1301. baseType = elementType;
  1302. return numVLAElements;
  1303. }
  1304. } while (isa<VariableArrayType>(arrayType));
  1305. // We get out here only if we find a constant array type
  1306. // inside the VLA.
  1307. }
  1308. // We have some number of constant-length arrays, so addr should
  1309. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1310. // down to the first element of addr.
  1311. SmallVector<llvm::Value*, 8> gepIndices;
  1312. // GEP down to the array type.
  1313. llvm::ConstantInt *zero = Builder.getInt32(0);
  1314. gepIndices.push_back(zero);
  1315. uint64_t countFromCLAs = 1;
  1316. QualType eltType;
  1317. llvm::ArrayType *llvmArrayType =
  1318. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1319. while (llvmArrayType) {
  1320. assert(isa<ConstantArrayType>(arrayType));
  1321. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1322. == llvmArrayType->getNumElements());
  1323. gepIndices.push_back(zero);
  1324. countFromCLAs *= llvmArrayType->getNumElements();
  1325. eltType = arrayType->getElementType();
  1326. llvmArrayType =
  1327. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1328. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1329. assert((!llvmArrayType || arrayType) &&
  1330. "LLVM and Clang types are out-of-synch");
  1331. }
  1332. if (arrayType) {
  1333. // From this point onwards, the Clang array type has been emitted
  1334. // as some other type (probably a packed struct). Compute the array
  1335. // size, and just emit the 'begin' expression as a bitcast.
  1336. while (arrayType) {
  1337. countFromCLAs *=
  1338. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1339. eltType = arrayType->getElementType();
  1340. arrayType = getContext().getAsArrayType(eltType);
  1341. }
  1342. llvm::Type *baseType = ConvertType(eltType);
  1343. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1344. } else {
  1345. // Create the actual GEP.
  1346. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1347. gepIndices, "array.begin"),
  1348. addr.getAlignment());
  1349. }
  1350. baseType = eltType;
  1351. llvm::Value *numElements
  1352. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1353. // If we had any VLA dimensions, factor them in.
  1354. if (numVLAElements)
  1355. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1356. return numElements;
  1357. }
  1358. std::pair<llvm::Value*, QualType>
  1359. CodeGenFunction::getVLASize(QualType type) {
  1360. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1361. assert(vla && "type was not a variable array type!");
  1362. return getVLASize(vla);
  1363. }
  1364. std::pair<llvm::Value*, QualType>
  1365. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1366. // The number of elements so far; always size_t.
  1367. llvm::Value *numElements = nullptr;
  1368. QualType elementType;
  1369. do {
  1370. elementType = type->getElementType();
  1371. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1372. assert(vlaSize && "no size for VLA!");
  1373. assert(vlaSize->getType() == SizeTy);
  1374. if (!numElements) {
  1375. numElements = vlaSize;
  1376. } else {
  1377. // It's undefined behavior if this wraps around, so mark it that way.
  1378. // FIXME: Teach -fsanitize=undefined to trap this.
  1379. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1380. }
  1381. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1382. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  1383. }
  1384. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1385. assert(type->isVariablyModifiedType() &&
  1386. "Must pass variably modified type to EmitVLASizes!");
  1387. EnsureInsertPoint();
  1388. // We're going to walk down into the type and look for VLA
  1389. // expressions.
  1390. do {
  1391. assert(type->isVariablyModifiedType());
  1392. const Type *ty = type.getTypePtr();
  1393. switch (ty->getTypeClass()) {
  1394. #define TYPE(Class, Base)
  1395. #define ABSTRACT_TYPE(Class, Base)
  1396. #define NON_CANONICAL_TYPE(Class, Base)
  1397. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1398. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1399. #include "clang/AST/TypeNodes.def"
  1400. llvm_unreachable("unexpected dependent type!");
  1401. // These types are never variably-modified.
  1402. case Type::Builtin:
  1403. case Type::Complex:
  1404. case Type::Vector:
  1405. case Type::ExtVector:
  1406. case Type::Record:
  1407. case Type::Enum:
  1408. case Type::Elaborated:
  1409. case Type::TemplateSpecialization:
  1410. case Type::ObjCObject:
  1411. case Type::ObjCInterface:
  1412. case Type::ObjCObjectPointer:
  1413. llvm_unreachable("type class is never variably-modified!");
  1414. case Type::Adjusted:
  1415. type = cast<AdjustedType>(ty)->getAdjustedType();
  1416. break;
  1417. case Type::Decayed:
  1418. type = cast<DecayedType>(ty)->getPointeeType();
  1419. break;
  1420. case Type::Pointer:
  1421. type = cast<PointerType>(ty)->getPointeeType();
  1422. break;
  1423. case Type::BlockPointer:
  1424. type = cast<BlockPointerType>(ty)->getPointeeType();
  1425. break;
  1426. case Type::LValueReference:
  1427. case Type::RValueReference:
  1428. type = cast<ReferenceType>(ty)->getPointeeType();
  1429. break;
  1430. case Type::MemberPointer:
  1431. type = cast<MemberPointerType>(ty)->getPointeeType();
  1432. break;
  1433. case Type::ConstantArray:
  1434. case Type::IncompleteArray:
  1435. // Losing element qualification here is fine.
  1436. type = cast<ArrayType>(ty)->getElementType();
  1437. break;
  1438. case Type::VariableArray: {
  1439. // Losing element qualification here is fine.
  1440. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1441. // Unknown size indication requires no size computation.
  1442. // Otherwise, evaluate and record it.
  1443. if (const Expr *size = vat->getSizeExpr()) {
  1444. // It's possible that we might have emitted this already,
  1445. // e.g. with a typedef and a pointer to it.
  1446. llvm::Value *&entry = VLASizeMap[size];
  1447. if (!entry) {
  1448. llvm::Value *Size = EmitScalarExpr(size);
  1449. // C11 6.7.6.2p5:
  1450. // If the size is an expression that is not an integer constant
  1451. // expression [...] each time it is evaluated it shall have a value
  1452. // greater than zero.
  1453. if (SanOpts.has(SanitizerKind::VLABound) &&
  1454. size->getType()->isSignedIntegerType()) {
  1455. SanitizerScope SanScope(this);
  1456. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1457. llvm::Constant *StaticArgs[] = {
  1458. EmitCheckSourceLocation(size->getLocStart()),
  1459. EmitCheckTypeDescriptor(size->getType())
  1460. };
  1461. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1462. SanitizerKind::VLABound),
  1463. "vla_bound_not_positive", StaticArgs, Size);
  1464. }
  1465. // Always zexting here would be wrong if it weren't
  1466. // undefined behavior to have a negative bound.
  1467. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1468. }
  1469. }
  1470. type = vat->getElementType();
  1471. break;
  1472. }
  1473. case Type::FunctionProto:
  1474. case Type::FunctionNoProto:
  1475. type = cast<FunctionType>(ty)->getReturnType();
  1476. break;
  1477. case Type::Paren:
  1478. case Type::TypeOf:
  1479. case Type::UnaryTransform:
  1480. case Type::Attributed:
  1481. case Type::SubstTemplateTypeParm:
  1482. case Type::PackExpansion:
  1483. // Keep walking after single level desugaring.
  1484. type = type.getSingleStepDesugaredType(getContext());
  1485. break;
  1486. case Type::Typedef:
  1487. case Type::Decltype:
  1488. case Type::Auto:
  1489. // Stop walking: nothing to do.
  1490. return;
  1491. case Type::TypeOfExpr:
  1492. // Stop walking: emit typeof expression.
  1493. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1494. return;
  1495. case Type::Atomic:
  1496. type = cast<AtomicType>(ty)->getValueType();
  1497. break;
  1498. case Type::Pipe:
  1499. type = cast<PipeType>(ty)->getElementType();
  1500. break;
  1501. }
  1502. } while (type->isVariablyModifiedType());
  1503. }
  1504. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1505. if (getContext().getBuiltinVaListType()->isArrayType())
  1506. return EmitPointerWithAlignment(E);
  1507. return EmitLValue(E).getAddress();
  1508. }
  1509. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1510. return EmitLValue(E).getAddress();
  1511. }
  1512. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1513. llvm::Constant *Init) {
  1514. assert (Init && "Invalid DeclRefExpr initializer!");
  1515. if (CGDebugInfo *Dbg = getDebugInfo())
  1516. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1517. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1518. }
  1519. CodeGenFunction::PeepholeProtection
  1520. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1521. // At the moment, the only aggressive peephole we do in IR gen
  1522. // is trunc(zext) folding, but if we add more, we can easily
  1523. // extend this protection.
  1524. if (!rvalue.isScalar()) return PeepholeProtection();
  1525. llvm::Value *value = rvalue.getScalarVal();
  1526. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1527. // Just make an extra bitcast.
  1528. assert(HaveInsertPoint());
  1529. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1530. Builder.GetInsertBlock());
  1531. PeepholeProtection protection;
  1532. protection.Inst = inst;
  1533. return protection;
  1534. }
  1535. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1536. if (!protection.Inst) return;
  1537. // In theory, we could try to duplicate the peepholes now, but whatever.
  1538. protection.Inst->eraseFromParent();
  1539. }
  1540. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1541. llvm::Value *AnnotatedVal,
  1542. StringRef AnnotationStr,
  1543. SourceLocation Location) {
  1544. llvm::Value *Args[4] = {
  1545. AnnotatedVal,
  1546. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1547. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1548. CGM.EmitAnnotationLineNo(Location)
  1549. };
  1550. return Builder.CreateCall(AnnotationFn, Args);
  1551. }
  1552. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1553. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1554. // FIXME We create a new bitcast for every annotation because that's what
  1555. // llvm-gcc was doing.
  1556. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1557. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1558. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1559. I->getAnnotation(), D->getLocation());
  1560. }
  1561. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1562. Address Addr) {
  1563. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1564. llvm::Value *V = Addr.getPointer();
  1565. llvm::Type *VTy = V->getType();
  1566. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1567. CGM.Int8PtrTy);
  1568. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1569. // FIXME Always emit the cast inst so we can differentiate between
  1570. // annotation on the first field of a struct and annotation on the struct
  1571. // itself.
  1572. if (VTy != CGM.Int8PtrTy)
  1573. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1574. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1575. V = Builder.CreateBitCast(V, VTy);
  1576. }
  1577. return Address(V, Addr.getAlignment());
  1578. }
  1579. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1580. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1581. : CGF(CGF) {
  1582. assert(!CGF->IsSanitizerScope);
  1583. CGF->IsSanitizerScope = true;
  1584. }
  1585. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1586. CGF->IsSanitizerScope = false;
  1587. }
  1588. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1589. const llvm::Twine &Name,
  1590. llvm::BasicBlock *BB,
  1591. llvm::BasicBlock::iterator InsertPt) const {
  1592. LoopStack.InsertHelper(I);
  1593. if (IsSanitizerScope)
  1594. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1595. }
  1596. void CGBuilderInserter::InsertHelper(
  1597. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1598. llvm::BasicBlock::iterator InsertPt) const {
  1599. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1600. if (CGF)
  1601. CGF->InsertHelper(I, Name, BB, InsertPt);
  1602. }
  1603. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1604. CodeGenModule &CGM, const FunctionDecl *FD,
  1605. std::string &FirstMissing) {
  1606. // If there aren't any required features listed then go ahead and return.
  1607. if (ReqFeatures.empty())
  1608. return false;
  1609. // Now build up the set of caller features and verify that all the required
  1610. // features are there.
  1611. llvm::StringMap<bool> CallerFeatureMap;
  1612. CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
  1613. // If we have at least one of the features in the feature list return
  1614. // true, otherwise return false.
  1615. return std::all_of(
  1616. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  1617. SmallVector<StringRef, 1> OrFeatures;
  1618. Feature.split(OrFeatures, "|");
  1619. return std::any_of(OrFeatures.begin(), OrFeatures.end(),
  1620. [&](StringRef Feature) {
  1621. if (!CallerFeatureMap.lookup(Feature)) {
  1622. FirstMissing = Feature.str();
  1623. return false;
  1624. }
  1625. return true;
  1626. });
  1627. });
  1628. }
  1629. // Emits an error if we don't have a valid set of target features for the
  1630. // called function.
  1631. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  1632. const FunctionDecl *TargetDecl) {
  1633. // Early exit if this is an indirect call.
  1634. if (!TargetDecl)
  1635. return;
  1636. // Get the current enclosing function if it exists. If it doesn't
  1637. // we can't check the target features anyhow.
  1638. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
  1639. if (!FD)
  1640. return;
  1641. // Grab the required features for the call. For a builtin this is listed in
  1642. // the td file with the default cpu, for an always_inline function this is any
  1643. // listed cpu and any listed features.
  1644. unsigned BuiltinID = TargetDecl->getBuiltinID();
  1645. std::string MissingFeature;
  1646. if (BuiltinID) {
  1647. SmallVector<StringRef, 1> ReqFeatures;
  1648. const char *FeatureList =
  1649. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1650. // Return if the builtin doesn't have any required features.
  1651. if (!FeatureList || StringRef(FeatureList) == "")
  1652. return;
  1653. StringRef(FeatureList).split(ReqFeatures, ",");
  1654. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1655. CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
  1656. << TargetDecl->getDeclName()
  1657. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1658. } else if (TargetDecl->hasAttr<TargetAttr>()) {
  1659. // Get the required features for the callee.
  1660. SmallVector<StringRef, 1> ReqFeatures;
  1661. llvm::StringMap<bool> CalleeFeatureMap;
  1662. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  1663. for (const auto &F : CalleeFeatureMap) {
  1664. // Only positive features are "required".
  1665. if (F.getValue())
  1666. ReqFeatures.push_back(F.getKey());
  1667. }
  1668. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1669. CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
  1670. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  1671. }
  1672. }
  1673. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  1674. if (!CGM.getCodeGenOpts().SanitizeStats)
  1675. return;
  1676. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  1677. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  1678. CGM.getSanStats().create(IRB, SSK);
  1679. }