CGStmt.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  1. //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
  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 contains code to emit Stmt nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenModule.h"
  15. #include "CodeGenFunction.h"
  16. #include "TargetInfo.h"
  17. #include "clang/AST/StmtVisitor.h"
  18. #include "clang/Basic/PrettyStackTrace.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/InlineAsm.h"
  22. #include "llvm/Intrinsics.h"
  23. #include "llvm/Target/TargetData.h"
  24. using namespace clang;
  25. using namespace CodeGen;
  26. //===----------------------------------------------------------------------===//
  27. // Statement Emission
  28. //===----------------------------------------------------------------------===//
  29. void CodeGenFunction::EmitStopPoint(const Stmt *S) {
  30. if (CGDebugInfo *DI = getDebugInfo()) {
  31. SourceLocation Loc;
  32. if (isa<DeclStmt>(S))
  33. Loc = S->getLocEnd();
  34. else
  35. Loc = S->getLocStart();
  36. DI->EmitLocation(Builder, Loc);
  37. }
  38. }
  39. void CodeGenFunction::EmitStmt(const Stmt *S) {
  40. assert(S && "Null statement?");
  41. // These statements have their own debug info handling.
  42. if (EmitSimpleStmt(S))
  43. return;
  44. // Check if we are generating unreachable code.
  45. if (!HaveInsertPoint()) {
  46. // If so, and the statement doesn't contain a label, then we do not need to
  47. // generate actual code. This is safe because (1) the current point is
  48. // unreachable, so we don't need to execute the code, and (2) we've already
  49. // handled the statements which update internal data structures (like the
  50. // local variable map) which could be used by subsequent statements.
  51. if (!ContainsLabel(S)) {
  52. // Verify that any decl statements were handled as simple, they may be in
  53. // scope of subsequent reachable statements.
  54. assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
  55. return;
  56. }
  57. // Otherwise, make a new block to hold the code.
  58. EnsureInsertPoint();
  59. }
  60. // Generate a stoppoint if we are emitting debug info.
  61. EmitStopPoint(S);
  62. switch (S->getStmtClass()) {
  63. case Stmt::NoStmtClass:
  64. case Stmt::CXXCatchStmtClass:
  65. case Stmt::SEHExceptStmtClass:
  66. case Stmt::SEHFinallyStmtClass:
  67. case Stmt::MSDependentExistsStmtClass:
  68. llvm_unreachable("invalid statement class to emit generically");
  69. case Stmt::NullStmtClass:
  70. case Stmt::CompoundStmtClass:
  71. case Stmt::DeclStmtClass:
  72. case Stmt::LabelStmtClass:
  73. case Stmt::GotoStmtClass:
  74. case Stmt::BreakStmtClass:
  75. case Stmt::ContinueStmtClass:
  76. case Stmt::DefaultStmtClass:
  77. case Stmt::CaseStmtClass:
  78. llvm_unreachable("should have emitted these statements as simple");
  79. #define STMT(Type, Base)
  80. #define ABSTRACT_STMT(Op)
  81. #define EXPR(Type, Base) \
  82. case Stmt::Type##Class:
  83. #include "clang/AST/StmtNodes.inc"
  84. {
  85. // Remember the block we came in on.
  86. llvm::BasicBlock *incoming = Builder.GetInsertBlock();
  87. assert(incoming && "expression emission must have an insertion point");
  88. EmitIgnoredExpr(cast<Expr>(S));
  89. llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
  90. assert(outgoing && "expression emission cleared block!");
  91. // The expression emitters assume (reasonably!) that the insertion
  92. // point is always set. To maintain that, the call-emission code
  93. // for noreturn functions has to enter a new block with no
  94. // predecessors. We want to kill that block and mark the current
  95. // insertion point unreachable in the common case of a call like
  96. // "exit();". Since expression emission doesn't otherwise create
  97. // blocks with no predecessors, we can just test for that.
  98. // However, we must be careful not to do this to our incoming
  99. // block, because *statement* emission does sometimes create
  100. // reachable blocks which will have no predecessors until later in
  101. // the function. This occurs with, e.g., labels that are not
  102. // reachable by fallthrough.
  103. if (incoming != outgoing && outgoing->use_empty()) {
  104. outgoing->eraseFromParent();
  105. Builder.ClearInsertionPoint();
  106. }
  107. break;
  108. }
  109. case Stmt::IndirectGotoStmtClass:
  110. EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
  111. case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
  112. case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
  113. case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
  114. case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
  115. case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
  116. case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
  117. case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
  118. case Stmt::ObjCAtTryStmtClass:
  119. EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
  120. break;
  121. case Stmt::ObjCAtCatchStmtClass:
  122. llvm_unreachable(
  123. "@catch statements should be handled by EmitObjCAtTryStmt");
  124. case Stmt::ObjCAtFinallyStmtClass:
  125. llvm_unreachable(
  126. "@finally statements should be handled by EmitObjCAtTryStmt");
  127. case Stmt::ObjCAtThrowStmtClass:
  128. EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
  129. break;
  130. case Stmt::ObjCAtSynchronizedStmtClass:
  131. EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
  132. break;
  133. case Stmt::ObjCForCollectionStmtClass:
  134. EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
  135. break;
  136. case Stmt::ObjCAutoreleasePoolStmtClass:
  137. EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
  138. break;
  139. case Stmt::CXXTryStmtClass:
  140. EmitCXXTryStmt(cast<CXXTryStmt>(*S));
  141. break;
  142. case Stmt::CXXForRangeStmtClass:
  143. EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
  144. case Stmt::SEHTryStmtClass:
  145. // FIXME Not yet implemented
  146. break;
  147. }
  148. }
  149. bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
  150. switch (S->getStmtClass()) {
  151. default: return false;
  152. case Stmt::NullStmtClass: break;
  153. case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
  154. case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
  155. case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
  156. case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
  157. case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
  158. case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
  159. case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
  160. case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
  161. }
  162. return true;
  163. }
  164. /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
  165. /// this captures the expression result of the last sub-statement and returns it
  166. /// (for use by the statement expression extension).
  167. RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
  168. AggValueSlot AggSlot) {
  169. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
  170. "LLVM IR generation of compound statement ('{}')");
  171. // Keep track of the current cleanup stack depth, including debug scopes.
  172. LexicalScope Scope(*this, S.getSourceRange());
  173. for (CompoundStmt::const_body_iterator I = S.body_begin(),
  174. E = S.body_end()-GetLast; I != E; ++I)
  175. EmitStmt(*I);
  176. RValue RV;
  177. if (!GetLast)
  178. RV = RValue::get(0);
  179. else {
  180. // We have to special case labels here. They are statements, but when put
  181. // at the end of a statement expression, they yield the value of their
  182. // subexpression. Handle this by walking through all labels we encounter,
  183. // emitting them before we evaluate the subexpr.
  184. const Stmt *LastStmt = S.body_back();
  185. while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
  186. EmitLabel(LS->getDecl());
  187. LastStmt = LS->getSubStmt();
  188. }
  189. EnsureInsertPoint();
  190. RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
  191. }
  192. return RV;
  193. }
  194. void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
  195. llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
  196. // If there is a cleanup stack, then we it isn't worth trying to
  197. // simplify this block (we would need to remove it from the scope map
  198. // and cleanup entry).
  199. if (!EHStack.empty())
  200. return;
  201. // Can only simplify direct branches.
  202. if (!BI || !BI->isUnconditional())
  203. return;
  204. BB->replaceAllUsesWith(BI->getSuccessor(0));
  205. BI->eraseFromParent();
  206. BB->eraseFromParent();
  207. }
  208. void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
  209. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  210. // Fall out of the current block (if necessary).
  211. EmitBranch(BB);
  212. if (IsFinished && BB->use_empty()) {
  213. delete BB;
  214. return;
  215. }
  216. // Place the block after the current block, if possible, or else at
  217. // the end of the function.
  218. if (CurBB && CurBB->getParent())
  219. CurFn->getBasicBlockList().insertAfter(CurBB, BB);
  220. else
  221. CurFn->getBasicBlockList().push_back(BB);
  222. Builder.SetInsertPoint(BB);
  223. }
  224. void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
  225. // Emit a branch from the current block to the target one if this
  226. // was a real block. If this was just a fall-through block after a
  227. // terminator, don't emit it.
  228. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  229. if (!CurBB || CurBB->getTerminator()) {
  230. // If there is no insert point or the previous block is already
  231. // terminated, don't touch it.
  232. } else {
  233. // Otherwise, create a fall-through branch.
  234. Builder.CreateBr(Target);
  235. }
  236. Builder.ClearInsertionPoint();
  237. }
  238. void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
  239. bool inserted = false;
  240. for (llvm::BasicBlock::use_iterator
  241. i = block->use_begin(), e = block->use_end(); i != e; ++i) {
  242. if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(*i)) {
  243. CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
  244. inserted = true;
  245. break;
  246. }
  247. }
  248. if (!inserted)
  249. CurFn->getBasicBlockList().push_back(block);
  250. Builder.SetInsertPoint(block);
  251. }
  252. CodeGenFunction::JumpDest
  253. CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
  254. JumpDest &Dest = LabelMap[D];
  255. if (Dest.isValid()) return Dest;
  256. // Create, but don't insert, the new block.
  257. Dest = JumpDest(createBasicBlock(D->getName()),
  258. EHScopeStack::stable_iterator::invalid(),
  259. NextCleanupDestIndex++);
  260. return Dest;
  261. }
  262. void CodeGenFunction::EmitLabel(const LabelDecl *D) {
  263. JumpDest &Dest = LabelMap[D];
  264. // If we didn't need a forward reference to this label, just go
  265. // ahead and create a destination at the current scope.
  266. if (!Dest.isValid()) {
  267. Dest = getJumpDestInCurrentScope(D->getName());
  268. // Otherwise, we need to give this label a target depth and remove
  269. // it from the branch-fixups list.
  270. } else {
  271. assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
  272. Dest = JumpDest(Dest.getBlock(),
  273. EHStack.stable_begin(),
  274. Dest.getDestIndex());
  275. ResolveBranchFixups(Dest.getBlock());
  276. }
  277. EmitBlock(Dest.getBlock());
  278. }
  279. void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
  280. EmitLabel(S.getDecl());
  281. EmitStmt(S.getSubStmt());
  282. }
  283. void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
  284. // If this code is reachable then emit a stop point (if generating
  285. // debug info). We have to do this ourselves because we are on the
  286. // "simple" statement path.
  287. if (HaveInsertPoint())
  288. EmitStopPoint(&S);
  289. EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
  290. }
  291. void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
  292. if (const LabelDecl *Target = S.getConstantTarget()) {
  293. EmitBranchThroughCleanup(getJumpDestForLabel(Target));
  294. return;
  295. }
  296. // Ensure that we have an i8* for our PHI node.
  297. llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
  298. Int8PtrTy, "addr");
  299. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  300. // Get the basic block for the indirect goto.
  301. llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
  302. // The first instruction in the block has to be the PHI for the switch dest,
  303. // add an entry for this branch.
  304. cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
  305. EmitBranch(IndGotoBB);
  306. }
  307. void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
  308. // C99 6.8.4.1: The first substatement is executed if the expression compares
  309. // unequal to 0. The condition must be a scalar type.
  310. RunCleanupsScope ConditionScope(*this);
  311. if (S.getConditionVariable())
  312. EmitAutoVarDecl(*S.getConditionVariable());
  313. // If the condition constant folds and can be elided, try to avoid emitting
  314. // the condition and the dead arm of the if/else.
  315. bool CondConstant;
  316. if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
  317. // Figure out which block (then or else) is executed.
  318. const Stmt *Executed = S.getThen();
  319. const Stmt *Skipped = S.getElse();
  320. if (!CondConstant) // Condition false?
  321. std::swap(Executed, Skipped);
  322. // If the skipped block has no labels in it, just emit the executed block.
  323. // This avoids emitting dead code and simplifies the CFG substantially.
  324. if (!ContainsLabel(Skipped)) {
  325. if (Executed) {
  326. RunCleanupsScope ExecutedScope(*this);
  327. EmitStmt(Executed);
  328. }
  329. return;
  330. }
  331. }
  332. // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
  333. // the conditional branch.
  334. llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
  335. llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
  336. llvm::BasicBlock *ElseBlock = ContBlock;
  337. if (S.getElse())
  338. ElseBlock = createBasicBlock("if.else");
  339. EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
  340. // Emit the 'then' code.
  341. EmitBlock(ThenBlock);
  342. {
  343. RunCleanupsScope ThenScope(*this);
  344. EmitStmt(S.getThen());
  345. }
  346. EmitBranch(ContBlock);
  347. // Emit the 'else' code if present.
  348. if (const Stmt *Else = S.getElse()) {
  349. // There is no need to emit line number for unconditional branch.
  350. if (getDebugInfo())
  351. Builder.SetCurrentDebugLocation(llvm::DebugLoc());
  352. EmitBlock(ElseBlock);
  353. {
  354. RunCleanupsScope ElseScope(*this);
  355. EmitStmt(Else);
  356. }
  357. // There is no need to emit line number for unconditional branch.
  358. if (getDebugInfo())
  359. Builder.SetCurrentDebugLocation(llvm::DebugLoc());
  360. EmitBranch(ContBlock);
  361. }
  362. // Emit the continuation block for code after the if.
  363. EmitBlock(ContBlock, true);
  364. }
  365. void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
  366. // Emit the header for the loop, which will also become
  367. // the continue target.
  368. JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
  369. EmitBlock(LoopHeader.getBlock());
  370. // Create an exit block for when the condition fails, which will
  371. // also become the break target.
  372. JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
  373. // Store the blocks to use for break and continue.
  374. BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
  375. // C++ [stmt.while]p2:
  376. // When the condition of a while statement is a declaration, the
  377. // scope of the variable that is declared extends from its point
  378. // of declaration (3.3.2) to the end of the while statement.
  379. // [...]
  380. // The object created in a condition is destroyed and created
  381. // with each iteration of the loop.
  382. RunCleanupsScope ConditionScope(*this);
  383. if (S.getConditionVariable())
  384. EmitAutoVarDecl(*S.getConditionVariable());
  385. // Evaluate the conditional in the while header. C99 6.8.5.1: The
  386. // evaluation of the controlling expression takes place before each
  387. // execution of the loop body.
  388. llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
  389. // while(1) is common, avoid extra exit blocks. Be sure
  390. // to correctly handle break/continue though.
  391. bool EmitBoolCondBranch = true;
  392. if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
  393. if (C->isOne())
  394. EmitBoolCondBranch = false;
  395. // As long as the condition is true, go to the loop body.
  396. llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
  397. if (EmitBoolCondBranch) {
  398. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  399. if (ConditionScope.requiresCleanups())
  400. ExitBlock = createBasicBlock("while.exit");
  401. Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
  402. if (ExitBlock != LoopExit.getBlock()) {
  403. EmitBlock(ExitBlock);
  404. EmitBranchThroughCleanup(LoopExit);
  405. }
  406. }
  407. // Emit the loop body. We have to emit this in a cleanup scope
  408. // because it might be a singleton DeclStmt.
  409. {
  410. RunCleanupsScope BodyScope(*this);
  411. EmitBlock(LoopBody);
  412. EmitStmt(S.getBody());
  413. }
  414. BreakContinueStack.pop_back();
  415. // Immediately force cleanup.
  416. ConditionScope.ForceCleanup();
  417. // Branch to the loop header again.
  418. EmitBranch(LoopHeader.getBlock());
  419. // Emit the exit block.
  420. EmitBlock(LoopExit.getBlock(), true);
  421. // The LoopHeader typically is just a branch if we skipped emitting
  422. // a branch, try to erase it.
  423. if (!EmitBoolCondBranch)
  424. SimplifyForwardingBlocks(LoopHeader.getBlock());
  425. }
  426. void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
  427. JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
  428. JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
  429. // Store the blocks to use for break and continue.
  430. BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
  431. // Emit the body of the loop.
  432. llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
  433. EmitBlock(LoopBody);
  434. {
  435. RunCleanupsScope BodyScope(*this);
  436. EmitStmt(S.getBody());
  437. }
  438. BreakContinueStack.pop_back();
  439. EmitBlock(LoopCond.getBlock());
  440. // C99 6.8.5.2: "The evaluation of the controlling expression takes place
  441. // after each execution of the loop body."
  442. // Evaluate the conditional in the while header.
  443. // C99 6.8.5p2/p4: The first substatement is executed if the expression
  444. // compares unequal to 0. The condition must be a scalar type.
  445. llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
  446. // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
  447. // to correctly handle break/continue though.
  448. bool EmitBoolCondBranch = true;
  449. if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
  450. if (C->isZero())
  451. EmitBoolCondBranch = false;
  452. // As long as the condition is true, iterate the loop.
  453. if (EmitBoolCondBranch)
  454. Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
  455. // Emit the exit block.
  456. EmitBlock(LoopExit.getBlock());
  457. // The DoCond block typically is just a branch if we skipped
  458. // emitting a branch, try to erase it.
  459. if (!EmitBoolCondBranch)
  460. SimplifyForwardingBlocks(LoopCond.getBlock());
  461. }
  462. void CodeGenFunction::EmitForStmt(const ForStmt &S) {
  463. JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
  464. RunCleanupsScope ForScope(*this);
  465. CGDebugInfo *DI = getDebugInfo();
  466. if (DI)
  467. DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
  468. // Evaluate the first part before the loop.
  469. if (S.getInit())
  470. EmitStmt(S.getInit());
  471. // Start the loop with a block that tests the condition.
  472. // If there's an increment, the continue scope will be overwritten
  473. // later.
  474. JumpDest Continue = getJumpDestInCurrentScope("for.cond");
  475. llvm::BasicBlock *CondBlock = Continue.getBlock();
  476. EmitBlock(CondBlock);
  477. // Create a cleanup scope for the condition variable cleanups.
  478. RunCleanupsScope ConditionScope(*this);
  479. llvm::Value *BoolCondVal = 0;
  480. if (S.getCond()) {
  481. // If the for statement has a condition scope, emit the local variable
  482. // declaration.
  483. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  484. if (S.getConditionVariable()) {
  485. EmitAutoVarDecl(*S.getConditionVariable());
  486. }
  487. // If there are any cleanups between here and the loop-exit scope,
  488. // create a block to stage a loop exit along.
  489. if (ForScope.requiresCleanups())
  490. ExitBlock = createBasicBlock("for.cond.cleanup");
  491. // As long as the condition is true, iterate the loop.
  492. llvm::BasicBlock *ForBody = createBasicBlock("for.body");
  493. // C99 6.8.5p2/p4: The first substatement is executed if the expression
  494. // compares unequal to 0. The condition must be a scalar type.
  495. BoolCondVal = EvaluateExprAsBool(S.getCond());
  496. Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
  497. if (ExitBlock != LoopExit.getBlock()) {
  498. EmitBlock(ExitBlock);
  499. EmitBranchThroughCleanup(LoopExit);
  500. }
  501. EmitBlock(ForBody);
  502. } else {
  503. // Treat it as a non-zero constant. Don't even create a new block for the
  504. // body, just fall into it.
  505. }
  506. // If the for loop doesn't have an increment we can just use the
  507. // condition as the continue block. Otherwise we'll need to create
  508. // a block for it (in the current scope, i.e. in the scope of the
  509. // condition), and that we will become our continue block.
  510. if (S.getInc())
  511. Continue = getJumpDestInCurrentScope("for.inc");
  512. // Store the blocks to use for break and continue.
  513. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  514. {
  515. // Create a separate cleanup scope for the body, in case it is not
  516. // a compound statement.
  517. RunCleanupsScope BodyScope(*this);
  518. EmitStmt(S.getBody());
  519. }
  520. // If there is an increment, emit it next.
  521. if (S.getInc()) {
  522. EmitBlock(Continue.getBlock());
  523. EmitStmt(S.getInc());
  524. }
  525. BreakContinueStack.pop_back();
  526. ConditionScope.ForceCleanup();
  527. EmitBranch(CondBlock);
  528. ForScope.ForceCleanup();
  529. if (DI)
  530. DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
  531. // Emit the fall-through block.
  532. EmitBlock(LoopExit.getBlock(), true);
  533. }
  534. void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
  535. JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
  536. RunCleanupsScope ForScope(*this);
  537. CGDebugInfo *DI = getDebugInfo();
  538. if (DI)
  539. DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
  540. // Evaluate the first pieces before the loop.
  541. EmitStmt(S.getRangeStmt());
  542. EmitStmt(S.getBeginEndStmt());
  543. // Start the loop with a block that tests the condition.
  544. // If there's an increment, the continue scope will be overwritten
  545. // later.
  546. llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
  547. EmitBlock(CondBlock);
  548. // If there are any cleanups between here and the loop-exit scope,
  549. // create a block to stage a loop exit along.
  550. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  551. if (ForScope.requiresCleanups())
  552. ExitBlock = createBasicBlock("for.cond.cleanup");
  553. // The loop body, consisting of the specified body and the loop variable.
  554. llvm::BasicBlock *ForBody = createBasicBlock("for.body");
  555. // The body is executed if the expression, contextually converted
  556. // to bool, is true.
  557. llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
  558. Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
  559. if (ExitBlock != LoopExit.getBlock()) {
  560. EmitBlock(ExitBlock);
  561. EmitBranchThroughCleanup(LoopExit);
  562. }
  563. EmitBlock(ForBody);
  564. // Create a block for the increment. In case of a 'continue', we jump there.
  565. JumpDest Continue = getJumpDestInCurrentScope("for.inc");
  566. // Store the blocks to use for break and continue.
  567. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  568. {
  569. // Create a separate cleanup scope for the loop variable and body.
  570. RunCleanupsScope BodyScope(*this);
  571. EmitStmt(S.getLoopVarStmt());
  572. EmitStmt(S.getBody());
  573. }
  574. // If there is an increment, emit it next.
  575. EmitBlock(Continue.getBlock());
  576. EmitStmt(S.getInc());
  577. BreakContinueStack.pop_back();
  578. EmitBranch(CondBlock);
  579. ForScope.ForceCleanup();
  580. if (DI)
  581. DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
  582. // Emit the fall-through block.
  583. EmitBlock(LoopExit.getBlock(), true);
  584. }
  585. void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
  586. if (RV.isScalar()) {
  587. Builder.CreateStore(RV.getScalarVal(), ReturnValue);
  588. } else if (RV.isAggregate()) {
  589. EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
  590. } else {
  591. StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
  592. }
  593. EmitBranchThroughCleanup(ReturnBlock);
  594. }
  595. /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
  596. /// if the function returns void, or may be missing one if the function returns
  597. /// non-void. Fun stuff :).
  598. void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
  599. // Emit the result value, even if unused, to evalute the side effects.
  600. const Expr *RV = S.getRetValue();
  601. // FIXME: Clean this up by using an LValue for ReturnTemp,
  602. // EmitStoreThroughLValue, and EmitAnyExpr.
  603. if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
  604. !Target.useGlobalsForAutomaticVariables()) {
  605. // Apply the named return value optimization for this return statement,
  606. // which means doing nothing: the appropriate result has already been
  607. // constructed into the NRVO variable.
  608. // If there is an NRVO flag for this variable, set it to 1 into indicate
  609. // that the cleanup code should not destroy the variable.
  610. if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
  611. Builder.CreateStore(Builder.getTrue(), NRVOFlag);
  612. } else if (!ReturnValue) {
  613. // Make sure not to return anything, but evaluate the expression
  614. // for side effects.
  615. if (RV)
  616. EmitAnyExpr(RV);
  617. } else if (RV == 0) {
  618. // Do nothing (return value is left uninitialized)
  619. } else if (FnRetTy->isReferenceType()) {
  620. // If this function returns a reference, take the address of the expression
  621. // rather than the value.
  622. RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
  623. Builder.CreateStore(Result.getScalarVal(), ReturnValue);
  624. } else if (!hasAggregateLLVMType(RV->getType())) {
  625. Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
  626. } else if (RV->getType()->isAnyComplexType()) {
  627. EmitComplexExprIntoAddr(RV, ReturnValue, false);
  628. } else {
  629. CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
  630. EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment, Qualifiers(),
  631. AggValueSlot::IsDestructed,
  632. AggValueSlot::DoesNotNeedGCBarriers,
  633. AggValueSlot::IsNotAliased));
  634. }
  635. EmitBranchThroughCleanup(ReturnBlock);
  636. }
  637. void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
  638. // As long as debug info is modeled with instructions, we have to ensure we
  639. // have a place to insert here and write the stop point here.
  640. if (getDebugInfo() && HaveInsertPoint())
  641. EmitStopPoint(&S);
  642. for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
  643. I != E; ++I)
  644. EmitDecl(**I);
  645. }
  646. void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
  647. assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
  648. // If this code is reachable then emit a stop point (if generating
  649. // debug info). We have to do this ourselves because we are on the
  650. // "simple" statement path.
  651. if (HaveInsertPoint())
  652. EmitStopPoint(&S);
  653. JumpDest Block = BreakContinueStack.back().BreakBlock;
  654. EmitBranchThroughCleanup(Block);
  655. }
  656. void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
  657. assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
  658. // If this code is reachable then emit a stop point (if generating
  659. // debug info). We have to do this ourselves because we are on the
  660. // "simple" statement path.
  661. if (HaveInsertPoint())
  662. EmitStopPoint(&S);
  663. JumpDest Block = BreakContinueStack.back().ContinueBlock;
  664. EmitBranchThroughCleanup(Block);
  665. }
  666. /// EmitCaseStmtRange - If case statement range is not too big then
  667. /// add multiple cases to switch instruction, one for each value within
  668. /// the range. If range is too big then emit "if" condition check.
  669. void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
  670. assert(S.getRHS() && "Expected RHS value in CaseStmt");
  671. llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
  672. llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
  673. // Emit the code for this case. We do this first to make sure it is
  674. // properly chained from our predecessor before generating the
  675. // switch machinery to enter this block.
  676. EmitBlock(createBasicBlock("sw.bb"));
  677. llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
  678. EmitStmt(S.getSubStmt());
  679. // If range is empty, do nothing.
  680. if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
  681. return;
  682. llvm::APInt Range = RHS - LHS;
  683. // FIXME: parameters such as this should not be hardcoded.
  684. if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
  685. // Range is small enough to add multiple switch instruction cases.
  686. for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
  687. SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
  688. LHS++;
  689. }
  690. return;
  691. }
  692. // The range is too big. Emit "if" condition into a new block,
  693. // making sure to save and restore the current insertion point.
  694. llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
  695. // Push this test onto the chain of range checks (which terminates
  696. // in the default basic block). The switch's default will be changed
  697. // to the top of this chain after switch emission is complete.
  698. llvm::BasicBlock *FalseDest = CaseRangeBlock;
  699. CaseRangeBlock = createBasicBlock("sw.caserange");
  700. CurFn->getBasicBlockList().push_back(CaseRangeBlock);
  701. Builder.SetInsertPoint(CaseRangeBlock);
  702. // Emit range check.
  703. llvm::Value *Diff =
  704. Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
  705. llvm::Value *Cond =
  706. Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
  707. Builder.CreateCondBr(Cond, CaseDest, FalseDest);
  708. // Restore the appropriate insertion point.
  709. if (RestoreBB)
  710. Builder.SetInsertPoint(RestoreBB);
  711. else
  712. Builder.ClearInsertionPoint();
  713. }
  714. void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
  715. // If there is no enclosing switch instance that we're aware of, then this
  716. // case statement and its block can be elided. This situation only happens
  717. // when we've constant-folded the switch, are emitting the constant case,
  718. // and part of the constant case includes another case statement. For
  719. // instance: switch (4) { case 4: do { case 5: } while (1); }
  720. if (!SwitchInsn) {
  721. EmitStmt(S.getSubStmt());
  722. return;
  723. }
  724. // Handle case ranges.
  725. if (S.getRHS()) {
  726. EmitCaseStmtRange(S);
  727. return;
  728. }
  729. llvm::ConstantInt *CaseVal =
  730. Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
  731. // If the body of the case is just a 'break', and if there was no fallthrough,
  732. // try to not emit an empty block.
  733. if (isa<BreakStmt>(S.getSubStmt())) {
  734. JumpDest Block = BreakContinueStack.back().BreakBlock;
  735. // Only do this optimization if there are no cleanups that need emitting.
  736. if (isObviouslyBranchWithoutCleanups(Block)) {
  737. SwitchInsn->addCase(CaseVal, Block.getBlock());
  738. // If there was a fallthrough into this case, make sure to redirect it to
  739. // the end of the switch as well.
  740. if (Builder.GetInsertBlock()) {
  741. Builder.CreateBr(Block.getBlock());
  742. Builder.ClearInsertionPoint();
  743. }
  744. return;
  745. }
  746. }
  747. EmitBlock(createBasicBlock("sw.bb"));
  748. llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
  749. SwitchInsn->addCase(CaseVal, CaseDest);
  750. // Recursively emitting the statement is acceptable, but is not wonderful for
  751. // code where we have many case statements nested together, i.e.:
  752. // case 1:
  753. // case 2:
  754. // case 3: etc.
  755. // Handling this recursively will create a new block for each case statement
  756. // that falls through to the next case which is IR intensive. It also causes
  757. // deep recursion which can run into stack depth limitations. Handle
  758. // sequential non-range case statements specially.
  759. const CaseStmt *CurCase = &S;
  760. const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
  761. // Otherwise, iteratively add consecutive cases to this switch stmt.
  762. while (NextCase && NextCase->getRHS() == 0) {
  763. CurCase = NextCase;
  764. llvm::ConstantInt *CaseVal =
  765. Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
  766. SwitchInsn->addCase(CaseVal, CaseDest);
  767. NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
  768. }
  769. // Normal default recursion for non-cases.
  770. EmitStmt(CurCase->getSubStmt());
  771. }
  772. void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
  773. llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
  774. assert(DefaultBlock->empty() &&
  775. "EmitDefaultStmt: Default block already defined?");
  776. EmitBlock(DefaultBlock);
  777. EmitStmt(S.getSubStmt());
  778. }
  779. /// CollectStatementsForCase - Given the body of a 'switch' statement and a
  780. /// constant value that is being switched on, see if we can dead code eliminate
  781. /// the body of the switch to a simple series of statements to emit. Basically,
  782. /// on a switch (5) we want to find these statements:
  783. /// case 5:
  784. /// printf(...); <--
  785. /// ++i; <--
  786. /// break;
  787. ///
  788. /// and add them to the ResultStmts vector. If it is unsafe to do this
  789. /// transformation (for example, one of the elided statements contains a label
  790. /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
  791. /// should include statements after it (e.g. the printf() line is a substmt of
  792. /// the case) then return CSFC_FallThrough. If we handled it and found a break
  793. /// statement, then return CSFC_Success.
  794. ///
  795. /// If Case is non-null, then we are looking for the specified case, checking
  796. /// that nothing we jump over contains labels. If Case is null, then we found
  797. /// the case and are looking for the break.
  798. ///
  799. /// If the recursive walk actually finds our Case, then we set FoundCase to
  800. /// true.
  801. ///
  802. enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
  803. static CSFC_Result CollectStatementsForCase(const Stmt *S,
  804. const SwitchCase *Case,
  805. bool &FoundCase,
  806. SmallVectorImpl<const Stmt*> &ResultStmts) {
  807. // If this is a null statement, just succeed.
  808. if (S == 0)
  809. return Case ? CSFC_Success : CSFC_FallThrough;
  810. // If this is the switchcase (case 4: or default) that we're looking for, then
  811. // we're in business. Just add the substatement.
  812. if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
  813. if (S == Case) {
  814. FoundCase = true;
  815. return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
  816. ResultStmts);
  817. }
  818. // Otherwise, this is some other case or default statement, just ignore it.
  819. return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
  820. ResultStmts);
  821. }
  822. // If we are in the live part of the code and we found our break statement,
  823. // return a success!
  824. if (Case == 0 && isa<BreakStmt>(S))
  825. return CSFC_Success;
  826. // If this is a switch statement, then it might contain the SwitchCase, the
  827. // break, or neither.
  828. if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
  829. // Handle this as two cases: we might be looking for the SwitchCase (if so
  830. // the skipped statements must be skippable) or we might already have it.
  831. CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
  832. if (Case) {
  833. // Keep track of whether we see a skipped declaration. The code could be
  834. // using the declaration even if it is skipped, so we can't optimize out
  835. // the decl if the kept statements might refer to it.
  836. bool HadSkippedDecl = false;
  837. // If we're looking for the case, just see if we can skip each of the
  838. // substatements.
  839. for (; Case && I != E; ++I) {
  840. HadSkippedDecl |= isa<DeclStmt>(*I);
  841. switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
  842. case CSFC_Failure: return CSFC_Failure;
  843. case CSFC_Success:
  844. // A successful result means that either 1) that the statement doesn't
  845. // have the case and is skippable, or 2) does contain the case value
  846. // and also contains the break to exit the switch. In the later case,
  847. // we just verify the rest of the statements are elidable.
  848. if (FoundCase) {
  849. // If we found the case and skipped declarations, we can't do the
  850. // optimization.
  851. if (HadSkippedDecl)
  852. return CSFC_Failure;
  853. for (++I; I != E; ++I)
  854. if (CodeGenFunction::ContainsLabel(*I, true))
  855. return CSFC_Failure;
  856. return CSFC_Success;
  857. }
  858. break;
  859. case CSFC_FallThrough:
  860. // If we have a fallthrough condition, then we must have found the
  861. // case started to include statements. Consider the rest of the
  862. // statements in the compound statement as candidates for inclusion.
  863. assert(FoundCase && "Didn't find case but returned fallthrough?");
  864. // We recursively found Case, so we're not looking for it anymore.
  865. Case = 0;
  866. // If we found the case and skipped declarations, we can't do the
  867. // optimization.
  868. if (HadSkippedDecl)
  869. return CSFC_Failure;
  870. break;
  871. }
  872. }
  873. }
  874. // If we have statements in our range, then we know that the statements are
  875. // live and need to be added to the set of statements we're tracking.
  876. for (; I != E; ++I) {
  877. switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
  878. case CSFC_Failure: return CSFC_Failure;
  879. case CSFC_FallThrough:
  880. // A fallthrough result means that the statement was simple and just
  881. // included in ResultStmt, keep adding them afterwards.
  882. break;
  883. case CSFC_Success:
  884. // A successful result means that we found the break statement and
  885. // stopped statement inclusion. We just ensure that any leftover stmts
  886. // are skippable and return success ourselves.
  887. for (++I; I != E; ++I)
  888. if (CodeGenFunction::ContainsLabel(*I, true))
  889. return CSFC_Failure;
  890. return CSFC_Success;
  891. }
  892. }
  893. return Case ? CSFC_Success : CSFC_FallThrough;
  894. }
  895. // Okay, this is some other statement that we don't handle explicitly, like a
  896. // for statement or increment etc. If we are skipping over this statement,
  897. // just verify it doesn't have labels, which would make it invalid to elide.
  898. if (Case) {
  899. if (CodeGenFunction::ContainsLabel(S, true))
  900. return CSFC_Failure;
  901. return CSFC_Success;
  902. }
  903. // Otherwise, we want to include this statement. Everything is cool with that
  904. // so long as it doesn't contain a break out of the switch we're in.
  905. if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
  906. // Otherwise, everything is great. Include the statement and tell the caller
  907. // that we fall through and include the next statement as well.
  908. ResultStmts.push_back(S);
  909. return CSFC_FallThrough;
  910. }
  911. /// FindCaseStatementsForValue - Find the case statement being jumped to and
  912. /// then invoke CollectStatementsForCase to find the list of statements to emit
  913. /// for a switch on constant. See the comment above CollectStatementsForCase
  914. /// for more details.
  915. static bool FindCaseStatementsForValue(const SwitchStmt &S,
  916. const llvm::APInt &ConstantCondValue,
  917. SmallVectorImpl<const Stmt*> &ResultStmts,
  918. ASTContext &C) {
  919. // First step, find the switch case that is being branched to. We can do this
  920. // efficiently by scanning the SwitchCase list.
  921. const SwitchCase *Case = S.getSwitchCaseList();
  922. const DefaultStmt *DefaultCase = 0;
  923. for (; Case; Case = Case->getNextSwitchCase()) {
  924. // It's either a default or case. Just remember the default statement in
  925. // case we're not jumping to any numbered cases.
  926. if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
  927. DefaultCase = DS;
  928. continue;
  929. }
  930. // Check to see if this case is the one we're looking for.
  931. const CaseStmt *CS = cast<CaseStmt>(Case);
  932. // Don't handle case ranges yet.
  933. if (CS->getRHS()) return false;
  934. // If we found our case, remember it as 'case'.
  935. if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
  936. break;
  937. }
  938. // If we didn't find a matching case, we use a default if it exists, or we
  939. // elide the whole switch body!
  940. if (Case == 0) {
  941. // It is safe to elide the body of the switch if it doesn't contain labels
  942. // etc. If it is safe, return successfully with an empty ResultStmts list.
  943. if (DefaultCase == 0)
  944. return !CodeGenFunction::ContainsLabel(&S);
  945. Case = DefaultCase;
  946. }
  947. // Ok, we know which case is being jumped to, try to collect all the
  948. // statements that follow it. This can fail for a variety of reasons. Also,
  949. // check to see that the recursive walk actually found our case statement.
  950. // Insane cases like this can fail to find it in the recursive walk since we
  951. // don't handle every stmt kind:
  952. // switch (4) {
  953. // while (1) {
  954. // case 4: ...
  955. bool FoundCase = false;
  956. return CollectStatementsForCase(S.getBody(), Case, FoundCase,
  957. ResultStmts) != CSFC_Failure &&
  958. FoundCase;
  959. }
  960. void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
  961. JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
  962. RunCleanupsScope ConditionScope(*this);
  963. if (S.getConditionVariable())
  964. EmitAutoVarDecl(*S.getConditionVariable());
  965. // Handle nested switch statements.
  966. llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
  967. llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
  968. // See if we can constant fold the condition of the switch and therefore only
  969. // emit the live case statement (if any) of the switch.
  970. llvm::APInt ConstantCondValue;
  971. if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
  972. SmallVector<const Stmt*, 4> CaseStmts;
  973. if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
  974. getContext())) {
  975. RunCleanupsScope ExecutedScope(*this);
  976. // At this point, we are no longer "within" a switch instance, so
  977. // we can temporarily enforce this to ensure that any embedded case
  978. // statements are not emitted.
  979. SwitchInsn = 0;
  980. // Okay, we can dead code eliminate everything except this case. Emit the
  981. // specified series of statements and we're good.
  982. for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
  983. EmitStmt(CaseStmts[i]);
  984. // Now we want to restore the saved switch instance so that nested switches
  985. // continue to function properly
  986. SwitchInsn = SavedSwitchInsn;
  987. return;
  988. }
  989. }
  990. llvm::Value *CondV = EmitScalarExpr(S.getCond());
  991. // Create basic block to hold stuff that comes after switch
  992. // statement. We also need to create a default block now so that
  993. // explicit case ranges tests can have a place to jump to on
  994. // failure.
  995. llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
  996. SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
  997. CaseRangeBlock = DefaultBlock;
  998. // Clear the insertion point to indicate we are in unreachable code.
  999. Builder.ClearInsertionPoint();
  1000. // All break statements jump to NextBlock. If BreakContinueStack is non empty
  1001. // then reuse last ContinueBlock.
  1002. JumpDest OuterContinue;
  1003. if (!BreakContinueStack.empty())
  1004. OuterContinue = BreakContinueStack.back().ContinueBlock;
  1005. BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
  1006. // Emit switch body.
  1007. EmitStmt(S.getBody());
  1008. BreakContinueStack.pop_back();
  1009. // Update the default block in case explicit case range tests have
  1010. // been chained on top.
  1011. SwitchInsn->setDefaultDest(CaseRangeBlock);
  1012. // If a default was never emitted:
  1013. if (!DefaultBlock->getParent()) {
  1014. // If we have cleanups, emit the default block so that there's a
  1015. // place to jump through the cleanups from.
  1016. if (ConditionScope.requiresCleanups()) {
  1017. EmitBlock(DefaultBlock);
  1018. // Otherwise, just forward the default block to the switch end.
  1019. } else {
  1020. DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
  1021. delete DefaultBlock;
  1022. }
  1023. }
  1024. ConditionScope.ForceCleanup();
  1025. // Emit continuation.
  1026. EmitBlock(SwitchExit.getBlock(), true);
  1027. SwitchInsn = SavedSwitchInsn;
  1028. CaseRangeBlock = SavedCRBlock;
  1029. }
  1030. static std::string
  1031. SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
  1032. SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
  1033. std::string Result;
  1034. while (*Constraint) {
  1035. switch (*Constraint) {
  1036. default:
  1037. Result += Target.convertConstraint(Constraint);
  1038. break;
  1039. // Ignore these
  1040. case '*':
  1041. case '?':
  1042. case '!':
  1043. case '=': // Will see this and the following in mult-alt constraints.
  1044. case '+':
  1045. break;
  1046. case ',':
  1047. Result += "|";
  1048. break;
  1049. case 'g':
  1050. Result += "imr";
  1051. break;
  1052. case '[': {
  1053. assert(OutCons &&
  1054. "Must pass output names to constraints with a symbolic name");
  1055. unsigned Index;
  1056. bool result = Target.resolveSymbolicName(Constraint,
  1057. &(*OutCons)[0],
  1058. OutCons->size(), Index);
  1059. assert(result && "Could not resolve symbolic name"); (void)result;
  1060. Result += llvm::utostr(Index);
  1061. break;
  1062. }
  1063. }
  1064. Constraint++;
  1065. }
  1066. return Result;
  1067. }
  1068. /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
  1069. /// as using a particular register add that as a constraint that will be used
  1070. /// in this asm stmt.
  1071. static std::string
  1072. AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
  1073. const TargetInfo &Target, CodeGenModule &CGM,
  1074. const AsmStmt &Stmt) {
  1075. const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
  1076. if (!AsmDeclRef)
  1077. return Constraint;
  1078. const ValueDecl &Value = *AsmDeclRef->getDecl();
  1079. const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
  1080. if (!Variable)
  1081. return Constraint;
  1082. AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
  1083. if (!Attr)
  1084. return Constraint;
  1085. StringRef Register = Attr->getLabel();
  1086. assert(Target.isValidGCCRegisterName(Register));
  1087. // We're using validateOutputConstraint here because we only care if
  1088. // this is a register constraint.
  1089. TargetInfo::ConstraintInfo Info(Constraint, "");
  1090. if (Target.validateOutputConstraint(Info) &&
  1091. !Info.allowsRegister()) {
  1092. CGM.ErrorUnsupported(&Stmt, "__asm__");
  1093. return Constraint;
  1094. }
  1095. // Canonicalize the register here before returning it.
  1096. Register = Target.getNormalizedGCCRegisterName(Register);
  1097. return "{" + Register.str() + "}";
  1098. }
  1099. llvm::Value*
  1100. CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
  1101. const TargetInfo::ConstraintInfo &Info,
  1102. LValue InputValue, QualType InputType,
  1103. std::string &ConstraintStr) {
  1104. llvm::Value *Arg;
  1105. if (Info.allowsRegister() || !Info.allowsMemory()) {
  1106. if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
  1107. Arg = EmitLoadOfLValue(InputValue).getScalarVal();
  1108. } else {
  1109. llvm::Type *Ty = ConvertType(InputType);
  1110. uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
  1111. if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
  1112. Ty = llvm::IntegerType::get(getLLVMContext(), Size);
  1113. Ty = llvm::PointerType::getUnqual(Ty);
  1114. Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
  1115. Ty));
  1116. } else {
  1117. Arg = InputValue.getAddress();
  1118. ConstraintStr += '*';
  1119. }
  1120. }
  1121. } else {
  1122. Arg = InputValue.getAddress();
  1123. ConstraintStr += '*';
  1124. }
  1125. return Arg;
  1126. }
  1127. llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
  1128. const TargetInfo::ConstraintInfo &Info,
  1129. const Expr *InputExpr,
  1130. std::string &ConstraintStr) {
  1131. if (Info.allowsRegister() || !Info.allowsMemory())
  1132. if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
  1133. return EmitScalarExpr(InputExpr);
  1134. InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
  1135. LValue Dest = EmitLValue(InputExpr);
  1136. return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
  1137. }
  1138. /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
  1139. /// asm call instruction. The !srcloc MDNode contains a list of constant
  1140. /// integers which are the source locations of the start of each line in the
  1141. /// asm.
  1142. static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
  1143. CodeGenFunction &CGF) {
  1144. SmallVector<llvm::Value *, 8> Locs;
  1145. // Add the location of the first line to the MDNode.
  1146. Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
  1147. Str->getLocStart().getRawEncoding()));
  1148. StringRef StrVal = Str->getString();
  1149. if (!StrVal.empty()) {
  1150. const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
  1151. const LangOptions &LangOpts = CGF.CGM.getLangOpts();
  1152. // Add the location of the start of each subsequent line of the asm to the
  1153. // MDNode.
  1154. for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
  1155. if (StrVal[i] != '\n') continue;
  1156. SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
  1157. CGF.Target);
  1158. Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
  1159. LineLoc.getRawEncoding()));
  1160. }
  1161. }
  1162. return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
  1163. }
  1164. void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
  1165. // Analyze the asm string to decompose it into its pieces. We know that Sema
  1166. // has already done this, so it is guaranteed to be successful.
  1167. SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
  1168. unsigned DiagOffs;
  1169. S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
  1170. // Assemble the pieces into the final asm string.
  1171. std::string AsmString;
  1172. for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
  1173. if (Pieces[i].isString())
  1174. AsmString += Pieces[i].getString();
  1175. else if (Pieces[i].getModifier() == '\0')
  1176. AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
  1177. else
  1178. AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
  1179. Pieces[i].getModifier() + '}';
  1180. }
  1181. // Get all the output and input constraints together.
  1182. SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
  1183. SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
  1184. for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
  1185. TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
  1186. S.getOutputName(i));
  1187. bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
  1188. assert(IsValid && "Failed to parse output constraint");
  1189. OutputConstraintInfos.push_back(Info);
  1190. }
  1191. for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
  1192. TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
  1193. S.getInputName(i));
  1194. bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
  1195. S.getNumOutputs(), Info);
  1196. assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
  1197. InputConstraintInfos.push_back(Info);
  1198. }
  1199. std::string Constraints;
  1200. std::vector<LValue> ResultRegDests;
  1201. std::vector<QualType> ResultRegQualTys;
  1202. std::vector<llvm::Type *> ResultRegTypes;
  1203. std::vector<llvm::Type *> ResultTruncRegTypes;
  1204. std::vector<llvm::Type*> ArgTypes;
  1205. std::vector<llvm::Value*> Args;
  1206. // Keep track of inout constraints.
  1207. std::string InOutConstraints;
  1208. std::vector<llvm::Value*> InOutArgs;
  1209. std::vector<llvm::Type*> InOutArgTypes;
  1210. for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
  1211. TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
  1212. // Simplify the output constraint.
  1213. std::string OutputConstraint(S.getOutputConstraint(i));
  1214. OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
  1215. const Expr *OutExpr = S.getOutputExpr(i);
  1216. OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
  1217. OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
  1218. Target, CGM, S);
  1219. LValue Dest = EmitLValue(OutExpr);
  1220. if (!Constraints.empty())
  1221. Constraints += ',';
  1222. // If this is a register output, then make the inline asm return it
  1223. // by-value. If this is a memory result, return the value by-reference.
  1224. if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
  1225. Constraints += "=" + OutputConstraint;
  1226. ResultRegQualTys.push_back(OutExpr->getType());
  1227. ResultRegDests.push_back(Dest);
  1228. ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
  1229. ResultTruncRegTypes.push_back(ResultRegTypes.back());
  1230. // If this output is tied to an input, and if the input is larger, then
  1231. // we need to set the actual result type of the inline asm node to be the
  1232. // same as the input type.
  1233. if (Info.hasMatchingInput()) {
  1234. unsigned InputNo;
  1235. for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
  1236. TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
  1237. if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
  1238. break;
  1239. }
  1240. assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
  1241. QualType InputTy = S.getInputExpr(InputNo)->getType();
  1242. QualType OutputType = OutExpr->getType();
  1243. uint64_t InputSize = getContext().getTypeSize(InputTy);
  1244. if (getContext().getTypeSize(OutputType) < InputSize) {
  1245. // Form the asm to return the value as a larger integer or fp type.
  1246. ResultRegTypes.back() = ConvertType(InputTy);
  1247. }
  1248. }
  1249. if (llvm::Type* AdjTy =
  1250. getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
  1251. ResultRegTypes.back()))
  1252. ResultRegTypes.back() = AdjTy;
  1253. } else {
  1254. ArgTypes.push_back(Dest.getAddress()->getType());
  1255. Args.push_back(Dest.getAddress());
  1256. Constraints += "=*";
  1257. Constraints += OutputConstraint;
  1258. }
  1259. if (Info.isReadWrite()) {
  1260. InOutConstraints += ',';
  1261. const Expr *InputExpr = S.getOutputExpr(i);
  1262. llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
  1263. InOutConstraints);
  1264. if (Info.allowsRegister())
  1265. InOutConstraints += llvm::utostr(i);
  1266. else
  1267. InOutConstraints += OutputConstraint;
  1268. InOutArgTypes.push_back(Arg->getType());
  1269. InOutArgs.push_back(Arg);
  1270. }
  1271. }
  1272. unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
  1273. for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
  1274. const Expr *InputExpr = S.getInputExpr(i);
  1275. TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
  1276. if (!Constraints.empty())
  1277. Constraints += ',';
  1278. // Simplify the input constraint.
  1279. std::string InputConstraint(S.getInputConstraint(i));
  1280. InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
  1281. &OutputConstraintInfos);
  1282. InputConstraint =
  1283. AddVariableConstraints(InputConstraint,
  1284. *InputExpr->IgnoreParenNoopCasts(getContext()),
  1285. Target, CGM, S);
  1286. llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
  1287. // If this input argument is tied to a larger output result, extend the
  1288. // input to be the same size as the output. The LLVM backend wants to see
  1289. // the input and output of a matching constraint be the same size. Note
  1290. // that GCC does not define what the top bits are here. We use zext because
  1291. // that is usually cheaper, but LLVM IR should really get an anyext someday.
  1292. if (Info.hasTiedOperand()) {
  1293. unsigned Output = Info.getTiedOperand();
  1294. QualType OutputType = S.getOutputExpr(Output)->getType();
  1295. QualType InputTy = InputExpr->getType();
  1296. if (getContext().getTypeSize(OutputType) >
  1297. getContext().getTypeSize(InputTy)) {
  1298. // Use ptrtoint as appropriate so that we can do our extension.
  1299. if (isa<llvm::PointerType>(Arg->getType()))
  1300. Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
  1301. llvm::Type *OutputTy = ConvertType(OutputType);
  1302. if (isa<llvm::IntegerType>(OutputTy))
  1303. Arg = Builder.CreateZExt(Arg, OutputTy);
  1304. else if (isa<llvm::PointerType>(OutputTy))
  1305. Arg = Builder.CreateZExt(Arg, IntPtrTy);
  1306. else {
  1307. assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
  1308. Arg = Builder.CreateFPExt(Arg, OutputTy);
  1309. }
  1310. }
  1311. }
  1312. if (llvm::Type* AdjTy =
  1313. getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
  1314. Arg->getType()))
  1315. Arg = Builder.CreateBitCast(Arg, AdjTy);
  1316. ArgTypes.push_back(Arg->getType());
  1317. Args.push_back(Arg);
  1318. Constraints += InputConstraint;
  1319. }
  1320. // Append the "input" part of inout constraints last.
  1321. for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
  1322. ArgTypes.push_back(InOutArgTypes[i]);
  1323. Args.push_back(InOutArgs[i]);
  1324. }
  1325. Constraints += InOutConstraints;
  1326. // Clobbers
  1327. for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
  1328. StringRef Clobber = S.getClobber(i)->getString();
  1329. if (Clobber != "memory" && Clobber != "cc")
  1330. Clobber = Target.getNormalizedGCCRegisterName(Clobber);
  1331. if (i != 0 || NumConstraints != 0)
  1332. Constraints += ',';
  1333. Constraints += "~{";
  1334. Constraints += Clobber;
  1335. Constraints += '}';
  1336. }
  1337. // Add machine specific clobbers
  1338. std::string MachineClobbers = Target.getClobbers();
  1339. if (!MachineClobbers.empty()) {
  1340. if (!Constraints.empty())
  1341. Constraints += ',';
  1342. Constraints += MachineClobbers;
  1343. }
  1344. llvm::Type *ResultType;
  1345. if (ResultRegTypes.empty())
  1346. ResultType = VoidTy;
  1347. else if (ResultRegTypes.size() == 1)
  1348. ResultType = ResultRegTypes[0];
  1349. else
  1350. ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
  1351. llvm::FunctionType *FTy =
  1352. llvm::FunctionType::get(ResultType, ArgTypes, false);
  1353. llvm::InlineAsm *IA =
  1354. llvm::InlineAsm::get(FTy, AsmString, Constraints,
  1355. S.isVolatile() || S.getNumOutputs() == 0);
  1356. llvm::CallInst *Result = Builder.CreateCall(IA, Args);
  1357. Result->addAttribute(~0, llvm::Attribute::NoUnwind);
  1358. // Slap the source location of the inline asm into a !srcloc metadata on the
  1359. // call.
  1360. Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
  1361. // Extract all of the register value results from the asm.
  1362. std::vector<llvm::Value*> RegResults;
  1363. if (ResultRegTypes.size() == 1) {
  1364. RegResults.push_back(Result);
  1365. } else {
  1366. for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
  1367. llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
  1368. RegResults.push_back(Tmp);
  1369. }
  1370. }
  1371. for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
  1372. llvm::Value *Tmp = RegResults[i];
  1373. // If the result type of the LLVM IR asm doesn't match the result type of
  1374. // the expression, do the conversion.
  1375. if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
  1376. llvm::Type *TruncTy = ResultTruncRegTypes[i];
  1377. // Truncate the integer result to the right size, note that TruncTy can be
  1378. // a pointer.
  1379. if (TruncTy->isFloatingPointTy())
  1380. Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
  1381. else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
  1382. uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
  1383. Tmp = Builder.CreateTrunc(Tmp,
  1384. llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
  1385. Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
  1386. } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
  1387. uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
  1388. Tmp = Builder.CreatePtrToInt(Tmp,
  1389. llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
  1390. Tmp = Builder.CreateTrunc(Tmp, TruncTy);
  1391. } else if (TruncTy->isIntegerTy()) {
  1392. Tmp = Builder.CreateTrunc(Tmp, TruncTy);
  1393. } else if (TruncTy->isVectorTy()) {
  1394. Tmp = Builder.CreateBitCast(Tmp, TruncTy);
  1395. }
  1396. }
  1397. EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
  1398. }
  1399. }