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